# Question
Title: Arduino Pro Micro clone not recognized, flickering RX LED
I have an Arduino Pro Micro clone that seems to be in some sort of reset loop. The RX LED is flickering very fast and very dim. The power LED also seems to flicker at the same frequency but has normal brightness.

The Arduino is not recognized by the PC at all anymore. It was working fine before. It doesn't matter if I try to go into the bootloader, by pressing reset twice, or not. Nothing happens. It feels like it is constantly resetting. The flickering stops if the reset pin stays connected to GND.

Another clone from the same shipment is still working fine. Both running the blink sketch. Just this one started to malfunction all of the sudden - after probing the pin I set in the blink sketch with my multimeter to see if the flashing was a success.

# Answer
> 4 votes
If your pro micro does not have a reset button, wire one between reset and ground.

Press reset twice, quickly, and immediately hit upload on the IDE.

Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.

# Answer
> 1 votes
I bricked my Pro-Micro within ten minutes of ripping it out the packet. I didn't realise that (a) it's not so brilliant on USB 3.0 - or in my case, unuseable, and (b) it's not actually an Arduino board - the Pro-Micro is a **SparkFun** product, and any clones thereof are from SparkFun's schematics.

The latter was only a problem to begin with, while I was scrabbling around on the Arduino website in vain trying to find answers. Once I realised to visit SF's website everything calmed down. Read this section on bricked/unrecognised pro-micros, and then have a look at the rest of the page as further reading.

# Answer
> 1 votes
Try this: unplug the Arduino, hold down the reset button, and then plug it in to power. Hold down the reset button a few seconds after you power it on. If this works, you should get the "blink" sketch, and be able to reprogram it.

Alternatively, if you have an ICSP programmer (I use the FreeTronics USBASP), plug this in (you will need to wire up the appropriate 6 pins), and then use the Arduino IDE to burn the bootloader - select the board, serial port, and programmer,then select "burn bootloader" - all from the "Tools" pull-down menu.

# Answer
> 1 votes
Try this:

1. Connect a push button switch to ground and reset (RST) pin;
2. Click upload then push the button twice (fast) = it doesn't matter if your computer does not recognize the pro micro;
3. Repeat this if it failed (repeat until you are successful).

After this the Pro Micro port will comeback to life.

I tested it. The reason I think that you bricked it, is because you uploaded using the wrong board setting - commonly the 3.3 V and 5 V (or vice versa)

# Answer
> 1 votes
This is a very common problem. See my answer to Arduino Micro just blinks, won't connect to PC.

As Asenkhan says in his answer, it is often caused by attempting to upload to a Pro Micro using the wrong board setting 3.3 V en lieu of 5V, or vice versa.

---

I have written two lengthy blogs about the whole experience:

# Answer
> 0 votes
You can make it work but only if you use a ISP programmer and burn the bootloader. The internal serial programmer would not work still some HID functions are retained. To me everything works fine except the Mouse functionality.

This a pain in the acc\* but it will work for other options. The other thing I have not tried is setting an old arduino ide and use the old addon for pro micro board to see if there a was a change in those files that caused it to fail.

So my next step would be as follow:

1. Setup the old arduino environment, download the old addon files and burn the bootloader.

Edit: While writting my findings I came with the solution. Just as I thought! You need to use the old files to make this work completely.

Steps:

**You'll need to buy an ISP Programmer for burning the bootloader or use another arduino board as an ISP Programmer**

I used the USBtinyISP Programmer. In specific:

Download the old sparkfun files (zip) version

Sparkfun Old Addon Files

Download the old Arduino IDE - I used the 1.0.6 portable (zip) version

\[Old Release Files\] (https://www.arduino.cc/en/Main/OldSoftwareReleases#previous)

Extract the Arduino IDE to Desktop. After doing so open the Sparkfun addon zip file and extract it to the Desktop. Then rename the extracted folder from:

> SF32u4\_boards-pre-1.6

To

> sparkfun

Alright copy that folder and if you do as I mentioned above now you'll head for the Arduino IDE we just downloaded. When you see the arduino files move into the hardware folder and paste the sparkfun folder inside of it (don't navigate any further than this).

Then connect the ISP following this diagram: Always double check the connections!

Now the next steps would be:

1. Open the Arduino IDE v1.0.6
2. Select your programmer under Tools (mine was USBtinyISP)
3. Select your Sparkfun Pro Micro board either the 3.3v or 5v version
4. Now under Tools select **Burn Bootloader**

If you do this right after a couple of seconds or minutes you will see a message that the process of burning the bootloader was completed. Depending on your hardware speed, if you store things in a flash drive or system is running on a linux live session you will need to wait a bit so just relax.

If things go according to plan then you can disconnect the ISP programmer and upload a simple sketch to corroborate the board is now working.

```
int ledPin=10; // let to pin 10

void setup() {
   pinMode(ledPin, OUTPUT);
}

void loop() {
   digitalWrite(ledPin, HIGH);
   delay(1000/2); // 1/2 a second
   digitalWrite(ledPin, LOW);
}

```

Upload as you normally would! Double check the board version!!

Perfecto! If the steps were followed in order you'll now have a working device

# Answer
> -1 votes
It can be problem with bootloader. You can try to burn bootloader again.

See for example:

http://angryelectron.com/how-to-update-the-bootloader-on-arduino-pro-mini-328/

Or use google

---
Tags: arduino-pro-micro, reset
---


title: 3.3v inductive proximity sensors

text:
# Question
Title: 3.3v inductive proximity sensors
I'm using an ESP8266 so I'm limited to 3.3v. I've found a number of inductive proximity sensors but they require 5v or more. Does a 3.3v sensor exist?

I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up. Stupid project? Maybe. But a good excuse to buy another sensor.

# Answer
I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use 3.3V–5V logic level converter modules. These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics. See the "Bi-directional level shifters" section of the TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V article at hackaday.com for a circuit explanation. See gearbest.com and sparkfun.com and Adafruit for inexpensive modules.

Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor. The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.
> 1 votes

---
Tags: sensors, esp8266, magnetometer
---


# Question
Title: Arduino based SPI programming of LT1257 not working
I am trying to talk to an LT1257 using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2\*FS output when the DAC powers on. Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).

```
#include<SPI.h>
#define SCLK 13
#define MISO 12
#define MOSI 11
#define DAC_LOAD 5

#define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

void setup()
{
Serial.begin(9600);
init();
SPI.begin();
dac_write();
}

void init()
{
pinMode(SCLK, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(DAC_LOAD, OUTPUT);
digitalWrite(SCLK, HIGH);
digitalWrite(MOSI, HIGH);
digitalWrite(DAC_LOAD, HIGH);
}

void dac_write()
{
SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
delay(10);
SPI.transfer(0x0000);
delay(10);
digitalWrite(DAC_LOAD, LOW);
delay(10);
digitalWrite(DAC_LOAD, HIGH);
delay(10);
SPI.endTransaction();
}

void loop()
{
while(1)
{
Serial.println("Ping!");
delay(1000);
}
}

```

# Answer
I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.
> 1 votes

# Answer
For a master to select an SPI slave to transmit data to it \[the slave\], the Slave Select pin is held low.
> -1 votes

---
Tags: spi
---


# Question
Title: DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface
What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

# Answer
Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.

https://www.dfrobot.com/wiki/index.php/I2C/TWI\_LCD1602\_Module\_(SKU:\_DFR0063)

Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.

There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.
> -1 votes

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


# Question
Title: Do we really need to upload Arduino bootloader for new Atmega IC
I am using `Atmega328p` in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using `USBasp` programmer. So before uploading code as `upload using programmer`, I will select my arduino board in board select menu and then I will select `USBasp` as my programmer. But I want to know that is it really necessary to burn bootloader on a new `Atmega328p` IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like `Serial.Begin()` etc.

So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

# Answer
No, you do not need the bootloader for your chip to function. The bootloader is merely a convenience.

If you are programming through USBasp you don't even need it on a "normal" Arduino board.

All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.

If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.
> 2 votes

---
Tags: bootloader
---


title: Problems creating 10Hz pulse wave

text:
# Question
Title: Problems creating 10Hz pulse wave
I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:

```
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB |= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

```

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?

Still doesnt work **edit:**

```
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1);
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

```

# Answer
> 3 votes
You have your whole 100ms wait time while the pin is low. You need half of it while low, half while high.

```
while(1){

    PORTB &= ~(1<<PORTB1);
    _delay_ms(50);
    PORTB |= (1<<PORTB1);
    _delay_ms(50); // You need a delay here too.
}

```

# Answer
> 1 votes
Your code doesn't clear anything.

```
    PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
    _delay_ms(100);
    PORTB |= (1<<PORTB1);  // set PORTB1 pin

```

And recommended tutorial: Bit manipulation (AKA "Programming 101") from the AVRFreaks.net

BTW: next issue might be "the pulse is way too fast so it seems there is none"

Try this:

```
while(1) {
    PINB = _BV(PINB1); // toggle pin
    _delay_ms(50);
}

```

# Answer
> 0 votes
```
   PORTB |= ~(1<<PORTB1);

```

change it to:

```
   PORTB &= ~(1<<PORTB1);

```

if you want to clear PB1.

---
Tags: avr
---


title: Can I set arbitrary SPI clock speeds?

text:
# Question
Title: Can I set arbitrary SPI clock speeds?
I would like to interface an ADC (in particular this one: http://www.linear.com/product/LTC1400) with an Arduino Nano via SPI. The specified max clock speed for the ADC is 6.4 MHz. The Nano can do up to 8 MHz clock speed, but I'm not able to set 6.4 MHz. If I try this

```
SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE0));

```

I get 4 MHz at the clock pin, which means the achievable acquisition rate of the ADC is reduced. Is there a way to get the 6.4 MHz going for maximum acquisition rate with the ADC? Or is there a different approach to get fast data transfer with the ADC (e.g. external clock)?

# Answer
> 3 votes
You are limited to what your microcontroller supports. You could use a 12MHz oscillator to clock your Arduino and set the SCK divider to fOSC/2 = 6MHz (even if it was possible, I wouldn't go higher. Having some margin just to be on the safe side is generally a good advice).
Drawback of this solution is that you lose CPU performance. Please consider also that just collecting ADC data is not enough. You also have to do something with it. Therefore the question should rather be:
"What **minimum** ADC acquisition rate do I need for my application?"

# Answer
> 2 votes
No, you cannot set 6.4MHz on SPI with a default hardware arrangement.

On the ATMega series of chips the SPI clock is generated by dividing the system clock (8 or 16MHz depending on if you have a 3.3 or 5V board) by one of: 2, 4, 8, 16, 32, 64 or 128.

Looking at the datasheet (section 25) it may be possible to configure the USART to run in SPI mode which allows a flexible clock speed, though this is not supported by the Arduino API.

---
Tags: arduino-nano, spi, adc
---


# Question
Title: Connecting to the Sparkfun Redboard on Mac OS X Sierra
I'm trying to connect to my Sparkfun Redboard (Arduino UNO compatible) on Mac OS X 10.12.3 (Sierra). The board comes with a USB mini to USB A FTDI cable. The board lights up and gets power over USB, but I don't see the right USB serial port in the Arduino IDE (I only see the Bluetooth port).

I've installed the VCP FTDI drivers v2.3 to no avail. When that didn't work, I also installed the CH340 CH341 drivers (but I doubt I need those). Rebooting the computer didn't help either.

I can only load the FTDI VCP v2.3 drivers using an explicit command `sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext/`. When I run `kextstat | grep FTDI`, I get:

```
 155    0 0xffffff7f83892000 0x7000     0x7000     com.FTDI.driver.FTDIUSBSerialDriver (2.3) ECC3AF36-431D-370D-86F2-5237785E9CF8 <127 41 5 4 3 1>

```

But it still doesn't show up in the Arduino IDE.

I've heard that Apple's own USB FTDI drivers (AppleUSBFTDI) could cause problems, but it seems these are never loaded. If I try to unload the Apple FTDI driver (`sudo kextunload –b com.apple.driver.AppleUSBFTDI`), I get the following:

```
(kernel) Kext com.apple.driver.AppleUSBFTDI not found for unload request.

```

Failed to unload com.apple.driver.AppleUSBFTDI - (libkern/kext) not found.

Any tips are welcome. Thanks!

# Answer
I'm using MacOS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever.

Some people have reported problems using the manufacturer (FTDI) drivers that they had already installed **after** upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and relying on the default Apple FTDI drivers uninstalling the conflicting drivers and relying on the default Apple FTDI drivers instead. It's worth a try.

OTOH, the CG340 driver doesn't currently work under Mac OS Sierra. Fortunately, Adrian Mihalko patched the driver and made it available at GitHub, along with some troubleshooting instructions.
> 0 votes

---
Tags: serial, ftdi, mac-os
---


# Question
Title: How to properly use interruptions with twi (I2C)
I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.

In the datasheet, page 262, 24.9.2, bit 0, I can read that I have to set the `TWIE` flag to one to be able to catch the interruption.

So, I started to write this code :

```
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

int etat = 0;
uint8_t currentstep = 0;
uint8_t _addr;
uint8_t _data;

ISR(TWI_vect)
{
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);

  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
        //Serial.println(etat);
      }
      else
      {
        etat = -1;
      }
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
        //Serial.println(etat);
      }
      else
      {
        etat = -2;
      }
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
        //Serial.println(etat);
      }
      else
      {
        etat = -3;
      }
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      //Serial.println(etat);
      //Serial.println("Next");
      break;
  }
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b1010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }
  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

```

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.

EDIT : Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the datasheet, p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).

Thanks for your help, julien

# Answer
After some tests, it's working ! First off all, I used Serial.println in my ISR, that's made it freeze apparently. Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.

This is my code working :

```
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

volatile int8_t etat = 0;
volatile uint8_t _addr;
volatile uint8_t _data;

ISR(TWI_vect)
{
  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
      }
      else
        etat = -1;
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
      }
      else
        etat = -2;
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
      }
      else
        etat = -3;
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      break;
  }
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b0010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }

  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

```

Thanks a lot to jfpoilpret !
> 2 votes

# Answer
Two observations.

1. The datasheetss does a fairly good job of Laying out the states and required conditions to move forward. Your code simply needs to mimic that. A short cut is to take a look at lpc210x datasheetss as it has fairly simple c code for the state machine implementation in the Isr.
2. What I typically do for slow multi byte transmission, i2c or UART, is to point a pointer to a string to be transmission, load up the datasheetss register and enable the interrupt. In the Isr, test if all the data has been transmission. If yes, turn off the Isr. Otherwise, load up thee next char. The data received can be processed via a callback function.

This approach minimizes user involvement. On a SPI with buffer, it can transmit without interruption.
> 1 votes

# Answer
**Why ?**

The Arduino Mega 2560 is not very fast. The gain by using interrupts is not a lot.

The Wire.endTransmission and Wire.requestFrom wait until the I2C transaction has finished. That might seem a waste of time, but for the slow ATmega microcontrollers, not a lot of time is wasted.

The overhead by more code might even slow it down. A I2C library that is completely in software might even be faster than the original Arduino Wire library. Although the Arduino Wire library uses interrupts, the overhead by the Wire library creates a few extra delays during the I2C transaction.

It took years (it really did) to have a normal working Wire library for ATmega microcontrollers and it still is not very good. For example a hardware problem on the I2C bus could halt a sketch. I have seen a number of custom I2C libraries that run into problems one way or the other.

You can waste less time with:

1. Make a well designed sketch, using millis instead of delay.
2. Write a good interface to the sensor. I see a lot bad usage of the Wire library with unnecessary I2C transactions.
3. Increase the I2C speed to 200kHz or 400kHz with Wire.setClock.
4. Try to use the SPI bus if possible. For a 3.3V sensor with a SPI interface, a 3.3V Arduino board is the best choice. For example the Arduino Due with ARM M4 or a small board with ARM M0+ processor.
5. When using the SPI bus with a Ethernet shield, try setting the SPI bus faster.
6. When using a SD card, try full speed, instead of half speed.
7. Use the newest Arduino IDE, because the 'lto' optimization was enabled which helps a lot.

Really serious work for better I2C functions has been done for the Teensy. It is still compatible with the Arduino Wire functions, but extra functions have been added that do not wait.
> 1 votes

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


title: wire.h onReceive only triggering once

text:
# Question
Title: wire.h onReceive only triggering once
I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.

I have wire.h set up and the code in place to decode chip commands and load the segment data to an array. That all works, and I can take that data and drive a new LCD just fine.

My problem is that the onReceive handler only triggers once. To get it to be armed and trigger again I need to press the reset button on the Uno board. I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.

When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.

Does anyone have any clue what's happening here? I tried commenting out most of my code but it still won't trigger on each receive. Obviously there's something subtle I changed that I'm missing, but what?

# Answer
> 2 votes
You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!

# Answer
> 1 votes
I looked at what docs I can find (not much) for 'onReceive' handler, but have not looked at the code itself. I would ask, does the system keep running in spite of the fact that your handler isn't being invoked? I'm asking if the bus is actually working after the first invocation of the handler? My guess is no. I also guess this ("onReceive" handler) has never worked as designed (hoped for?)

Also it sounds like you have a DSO scope, neat. Decades in electronics and I still get fooled by them (or the software:) now and then. So make sure it's setup properly. Sounds like you do... but...

Does the i2c bus have only this **one** device?

I've found that 99.99% of my problems turn out to be chip configuration. Improper interrupt or mask bits, etc. If it's driven by an interrupt, then it almost has to be the chip's interrupt configuration. Of course if your code goes awry then it could change some of these bits that control the micro's operation and most can also write over the **interrupt vector table**.

Since it **works** after a reset, *once*, it may be wise to track down what happens in your particular micro's configuration after the reset, compared to what you change to get it to work. Some of the parts of the micro I use (328p, maybe you also) have to be reset after an interrupt.

A last but not least option, since I'm not familiar with the function is to look at the assembler and see if it's resetting the required interrupt enable flags or masks. Most of these handlers end with some type of return from interrupt instruction that enables the interrupts and returns. Generally alleviating the programmer of that task.

Best of luck :)

# Answer
> -1 votes
An Arduino as a I2C Slave to replace something in a device often fails. The Arduino uses hardware and software, while I2C chips use only hardware. The Arduino as Slave is often recognized on the I2C bus because it acknowledges to its I2C address. However, as soon as data needs to be transferred, the Arduino stretches the clock signal to create some time to call the onReceive function. Do you know if the I2C Master controller is able to handle the clock pulse stretching ? Sometimes it is a software I2C, and almost no software implementation takes care of clock stretching.

---
Tags: arduino-uno, i2c, wire-library
---


# Question
Title: Does the reset button clean a programe that you programmed?
does the code clean from arduino if i touch reset button?

# Answer
No, it only causes the microcontroller to start over the existing program/code.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: is it possible to power esp8266 with button cell
is it possible to power esp8266 wifi module with button cell for long period(1 year ) real time applications?? Needs only wifi features (no need of gpio)

what will be voltage and current of the cell??

# Answer
No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.

The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.
> 3 votes

---
Tags: esp8266
---


title: Identification of IoT

text:
# Question
Title: Identification of IoT
For a school project I Have to make an IoT solution in the retail. We were thinking of a smart clothing hanger. We want to make the hanger smart enough to recognize what clothing is hanging on it. In order to do so the clothing has to be able to send some sort of ID to the hanger.

first thing we thought of was RFID but the hanger next to an one hanger would pick up the signal from the other hanger so that wouldn’t be an option.

Does anyone have any other ideas on what we could try to let the piece of clothing talk to the hanger?

# Answer
> 0 votes
Well I guess the signal strength could be measured but clothes hanged in wardrobe are too close to each other to distinguish them. Maybe close range NFC?

**I have other solution to be considered.**

Maybe you look at the wrong touchpoint of that interaction. What if the desired action occurs not while it's already hanged but when user put the clothes on hanger? During that, it's not with other clothes (as you grab the hanger in your hand to put the clothes on it).

There are a few things to consider. I guess people put things only on one hanger at once while having clothes in second hand. How many % of users puts clothes on hanger by grabbing it outside of wardrobe (as mundane event/behavior)?

Why it's important?

**During that interaction there is a moment when user tries to pair single cloth with single hanger separated from the rest.**

The hanger could have additional sensor to know when it happens:

* Magnetic field sensor and small magnet in collar?
* Capacitive sensor?
* Accelerometer?

...so the device will know when that interaction occurs and then activate the reading from single rfid tag.

I guess my answer is more about user experience and the aesthetics of interaction but it can give you some clues to finish your project.

---
Tags: communication
---


# Question
Title: How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. For transmitting I use the library `VirtualWire` and It works very well for this code:

```
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','!'};
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  delay(1000);
}

```

I was wondering if I want to send some `string` or `int` data how I can do that. I tried to use it for string data but I couldn't because the `Input` of function `vw_send(...)` is char and I couldn't use `int` or `string`. finally I run this code:

```
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

```

and I could send Hello there !, but I'm looking for the correct way for sending `string` and `int`.

# Answer
Have a look at the Easy Transfer library. I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules. In essence the EasyTransfer library transmits the data as a structure with the same format on each module. The structure can contain any data type.
> 1 votes

---
Tags: arduino-uno, wifi
---


title: Problem with TIMER in Arduino DUE

text:
# Question
Title: Problem with TIMER in Arduino DUE
I'm writing a code to print/update the value of sensors for each 10 ms, and I decide to use Timer instead of delay function (I'm afraid it's not exactly 10ms with delay function).But when I watch the result on terminal, it stops running at about 0.5s. I guess there is a problem with my code in using Timer because when I remove timer, it prints normally. I debug all day but still cannot find any errors. I guess this is related to memory or pointer or print function.

Please help me :( !!

Here is the code. The code is very long but you can ignore all the unnecessary things:

```
  #include <DueTimer.h>

  int mod_11k = 12;
  int mod_17k = 13;

  int analog1 = 0;              //output pin of signal 1
  int analog2 = 1;              //output pin of signal 2
  int analog3 = 2;              //output pin of signal 3

  float xf; float yf;
  unsigned long t1;
  unsigned long t2;

void myHandler(){
    Serial.print(t2-t1);
    Serial.print(" ");
    Serial.print(xf,3);
    Serial.print(" ");
    Serial.println(yf,3);
}

void setup() {
  Serial.begin(38400);
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  Timer1.attachInterrupt(myHandler).start(10000);
  digitalWrite(mod_17k,LOW);
  digitalWrite(mod_11k,HIGH);
}

void loop() {
    afficherSig(analog1,analog2,analog3);
}

void afficherSig(int pin1, int pin2, int pin3){
  unsigned int i;
  float mes[3];
  float mesflt[3];
  float x; float y;
  int  nb_ech = 10000;
  float res = 0.0049;
  float Te;
  float Tbeg;
  float QR1[2],QR2[2] ;
  float *sol1;float *sol2;float *sol3;
  float P1[4];float P2[4];float P3[4];
  float xprec1[2];float xprec2[2];float xprec3[2];
  float *s1_11k;
  float *s1f_11k;

  float H = 80;

                                       //------------------------------>>>
  QR1[0] = 1;
  QR1[1] = 10;
  QR2[0] = 1;
  QR2[1] = 100;
  P1[0] =QR1[0]; P1[1] =0; P1[2] =0; P1[3] =QR1[0];
  P2[0] =QR1[0]; P2[1] =0; P2[2] =0; P2[3] =QR1[0];
  P3[0] =QR1[0]; P3[1] =0; P3[2] =0; P3[3] =QR1[0];
  xprec1[0] =0; xprec1[1] =0;
  xprec2[0] =0; xprec2[1] =0;
  xprec3[0] =0; xprec3[1] =0;
                                      //------------------------------>>>
  t1 = millis();
  Tbeg= millis();
  mes[0]  = res*analogRead(analog1);
  mes[1]  = res*analogRead(analog2);
  mes[2]  = res*analogRead(analog3);

  xprec1[0] = mes[0];
  xprec2[0] = mes[1];
  xprec3[0] = mes[2];
  Te = (millis() - Tbeg)/1000;
  Tbeg = millis();
  sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
  sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
  sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

                                      //------------------------------->>>
 for(i=1;i<nb_ech;i++) {

    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];

    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];

    free(sol1);
    free(sol2);
    free(sol3);

    mes[0]  = res*analogRead(analog1);
    mes[1]  = res*analogRead(analog2);
    mes[2]  = res*analogRead(analog3);

    Te = (millis() - Tbeg)/1000;
    Tbeg = millis();
    sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
    sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
    sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

    mesflt[0] = sol1[0];
    mesflt[1] = sol2[0];
    mesflt[2] = sol3[0];                               // Envoie des résultats  à la sortie série

//Traitment du signal
    s1_11k = traitement1(mes[0],mes[1],mes[2]);
    s1f_11k = traitement1(mesflt[0],mesflt[1],mesflt[2]);

    x = H*s1_11k[0];
    xf = H*s1f_11k[0];
    y = -H*s1_11k[1];
    yf = -H*s1f_11k[1];
    t2 = millis();
  }
}

float *Fkalman(float xprec[2],float ymes,float P[4],float QR[2] ,float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = QR[0];
    int r = QR[1];

    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];
    Ppred[0] = q*q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q*q+ P[3];
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

  float *traitement1(float mes1,float mes2,float mes3)
  {
    float *sol11 = NULL ;
    sol11 = (float*) malloc (sizeof(float) * 2);
    sol11[0] = (mes1-mes2)/(mes1+mes2);
    sol11[1] = (((mes1+mes2)/2)-mes3)/(((mes1+mes2)/2)+mes3);
    return sol11;
  }

```

Here is the result using Timer (stop at about 0.5 second):

# Answer
> 0 votes
As noted in the last part of Nick Gammon's answer to the question How does the Arduino handle serial buffer overflow?, if the serial output buffer fills up, serial output blocks, waiting for an interrupt telling it it's ok to send the next byte out the serial port. When interrupts are turned off, that interrupt is never processed, so the program deadlocks. Don't do Serial prints in an ISR.

Looking at your code, it looks like a typical message has about 20 characters. Sending at 38400 bps, or 384 characters per second, it seems to me the buffer shouldn't fill, even if it's small (16 bytes) instead of large (64 bytes). However, I don't know of another explanation for the behavior you describe.

Summary: In your ISR, just store the current time and other relevant data in volatile variables, set a flag in a volatile variable, and in your main loop print stuff and clear the flag (or clear the flag and print stuff) whenever you see that the flag has been set.

---

*Edit 1:* I've struck out some erroneous numbers above. Here is a correction: 100 sends per second at 20 characters each is 2000 characters per second. 38400 bps of asynchronous data at 10 bits per transmitted byte is 3840 characters per second. So the raw data rate should be fast enough that the buffer ordinarily doesn't overfill.

---

In the summary above, I suggested that the ISR store the current time and other relevant data in volatile variables and set a flag in a volatile variable. That is, read `millis()` and store it, perhaps as follows:

```
// at file level ...
volatile unsigned long isrMillis;
volatile byte isrFlag;

// in ISR ...
  isrMillis = millis();
  isrFlag = true;

// in main loop ...
  unsigned long mlMillis;
  ...
  // when flag is true...
  cli();
  mlMillis = isrMillis;
  isrFlag = false;
  sei();
  // Now do stuff with mlMillis
  ...

```

However, looking at your ISR, perhaps it should go like the following instead:

```
// at file level ...
volatile float xf, yf, xfc, yfc;
volatile unsigned long t1, t2, tdelt;
volatile byte isrflag;

// in ISR ...
void myHandler(){
  tdelt = t2-t1;
  xfc = xf;
  yfc = yf;
  isrFlag = true;
}

// in main loop ...
  // when flag is true...
  isrFlag = false;
  // Now do stuff with tdelt, xfc, and yfc
  ...

```

Note that if an interrupt occurs while `xf` and `yf` are in the middle of being computed via your Kalman filter or whatever, the statements `xfc = xf;` and `yfc = yf;` may pick up partially-stored results. You can avoid that problem at least in part by protecting stores of `t1, t2, xf, yf` in the main loop:

```
  cli();
  xf = someXResult;
  yf = someYResult;
  t1 = someT1Result;
  t2 = someT2Result;
  sei();

```

In the above I've pointed out a few issues with races and concurrency and suggested technical solutions. Those suggestions may be quite wide of the mark rather than appropriate. In general I don't have a precise understanding of what you are trying to do with the software and don't know what redesign should be done to make it coherent.

---
Tags: arduino-due, timers
---


# Question
Title: How to connect a digital sensor through SPI
I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data\_ready pin is never high and I can't read the registers. The connections (user guide):

I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.

Code:

```
//modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

#include <SPI.h>

const int ID = 0x00;
const int FIFO = 0x11;
const byte READ = 0b11111100;
const byte WRITE = 0b00000010;

const int dataReadyPin = 6;
const int chipSelectPin = 7;

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

    // put your setup code here, to run once:
    SPI.begin();

    // initalize the  data ready and chip select pins:
    pinMode(dataReadyPin, INPUT);
    pinMode(chipSelectPin, OUTPUT);

    delay(100);
    readRegister(ID);
}

void loop() {
    if (digitalRead(dataReadyPin) == HIGH){
        Serial.println("data ready");
        delay(500);
    }
}
void readRegister (byte thisRegister){
    byte inByte = 0 ;
    Serial.println(thisRegister, BIN);

    thisRegister = thisRegister<< 2;
    byte dataToSend = thisRegister & READ;
    Serial.println(thisRegister, BIN);
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(dataToSend);
    inByte = SPI.transfer(0x00);
    Serial.println("data: ");
    Serial.println(inByte);
}

```

# Answer
> 1 votes
You're shifting your address too far.

* Read should be 0b00000001 not 0b00000010.
* Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

---

```
byte readRegister (byte thisRegister){
    byte inByte = 0 ;
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer((thisRegister << 1) | 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}

void writeRegister (byte thisRegister, byte value){
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

```

---
Tags: sensors, spi
---


# Question
Title: SOLVED: Soft Power On SIM900 module - JP pads missing!
I have this SIM900 board and working just fine. But i can't find a way to soft power on this board from arduino. I read for JP pads. They need soldering first, but from my board this JP pads missing. Know someone other way to soft power on this from arduino?

# Answer
> 1 votes
OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:

```
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  pinMode(9, INPUT);

```

I don't know how it works, but it solves my problem.

# Answer
> 1 votes
Near C6 and J15 you have 2 points. You need to solder it. Before soldering yon can hold wire on one of it (down pin , during code execution).

---
Tags: hardware
---


# Question
Title: 2G/3G vs 4G/LTE Cell Connectivity for Sensor Prototype?
Would love any advice on Arduino cell connectivity. From what I understand:

* **2G (GSM/GPRS)** is a dying technology. AT&T is shutting down its 2G network on Jan 1, 2017.
* **2G (CDMA)** will have a longer lifespan than GSM in the U.S., although the options for CDMA modules are much more limited than GSM.
* **3G** has poorer coverage than 2G and is no longer growing.
* **4G** is overkill but is also future-proofed.
* **4G LTE** ^ ditto

I am prototyping sensors that will send GPS/accel/gyro/temp data to a server every 30 seconds or so. They will be in the U.S., operate outside of wifi range, and likely not move very much (roaming isn't a factor).

Am I right in ruling out 2G GSM at this point? From what I've seen, the AT&T 4G LTE IoT Dev Kit looks like a decent option but this is the first time I've worked with IoT devices so any suggestions are welcome (http://cloudconnectkits.org/product/att-cellular-iot-starter-kit).

# Answer
2G GSM/GPRS are almost dead in the US. CDMA is still working and it would be supported atleast till 2020 becaasue it is used in M2M devices. 3G is still one of the most widely used networks and it has great coverage and it would not likely be phased out till 2024. 4G is widely deployed now and is the future.

Coming back to this from the perspective of developing hardware projects/products and availability of module for DIY use.

**2G chip-sets** are very cheap (~$10) and easily available with lots of documentation. Example 2g module here

**3G modules** have been in the market for a little while and there are a couple of modules at a good price-point with decent documentation. Example 3g module here

4g is still bleeding edge and there are not a lot of modules available for DIY users with great documentation and at a good price. I was able to find one with good documentation here.

There are a couple of other factors that come in play when you are working on a project. One is just the support and documentation around the hardware. These modems usually need a good library built around them which can handle most of the functionality and most of the time, the manufacturer gives just a datasheet specifying what all the functionality is and the user is supposed to build the libraries for them in the platform of their choice. Here is adafruit's library for the cellular module to show you the complexity. Also, when you are just using a few of these then the modules are just building blocks and it usually makes sense to use the modules with the best possible support around them.

Tl;dr, use a 3G module with good software support for your platform.
> 1 votes

---
Tags: sensors, gsm, networking
---


title: ADC with better performance

text:
# Question
Title: ADC with better performance
I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

# Answer
> 3 votes
ADS7835 from Texas Instrument.

> can be interfaced with Arduino Mega or Raspberry Pi

It is interfaced through SPI, 12 bit data, and up to 500kHz throughput rate.

# Answer
> 2 votes
> I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.

even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.

precision is another matter.

---
Tags: arduino-mega, voltage-level, adc, raspberrypi, analog-sampling
---


# Question
Title: Making the speaker play a certain frequency of sound
I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

```
digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

```

What could be the problem?

# Answer
> 2 votes
Have you looked at the Tone library? That does what you want, with some other niceties besides.

Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:

```
digitalWrite(buzzer, LOW);
delayMicroseconds(500000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(500000 / frequency);

```

---
Tags: arduino-uno, frequency, speaker
---


# Question
Title: ESP8266 Timing question / Do something in 2 seconds even
I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

1. The MC recieves the signal for trigger by the user on 09:25:18:312
2. It waits until it is exactly 09:25:19:000
3. It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!

Edit: Corrected Times.

# Answer
You can, but I think you are probably not looking at the best solution. This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...

The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes. It might be better to use "something" to trigger a HW interrupt. From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).

Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.

You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm. The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin. The limiting factor here is the accuracy you require.
> 0 votes

---
Tags: esp8266, timers, time
---


# Question
Title: Read data from arduino once only serial communications (jSSC)
I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.

Here is Arduino code:

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

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

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

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522

    //mfrc522.PCD_DumpVersionToSerial();    // Show details of PCD - MFRC522 Card Reader details
    //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
  String code = "";
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
  for (byte i = 0; i < mfrc522.uid.size; i++) {
      code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
      code += String(mfrc522.uid.uidByte[i], HEX);
  }
  code.toUpperCase();
  Serial.println(code);
  mfrc522.PICC_HaltA();
}

```

# Answer
> 1 votes
Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.

The fault is with the receiving java code, pump test data into that to see what is wrong.

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


# Question
Title: Difference between SoftwareSerial and Serial
From the sample code

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

```

What is the difference between, why use 2 types of calls to make AT command calls.

> SoftwareSerial mySerial (10,11) mySerial.begin(10,11)

and

> Serial.begin(9600)

**Edit, this answers my question in my own words based on @jfpoilpret response.**

1. It is important to **initialize both Serial and SoftwareSerial**, since SoftwareSerial is used to send the actual commands to the GSM, and Serial is used to `view` all the commands and their responses on the debug port of the GSM
2. The pins on the GSM and Arduino are used to connect the the 2, and pass on **actual commands**. While the RS232 is only used for debugging. We can however connect a RS232 to USB connector so as to connect the GSM to the desktop(or laptop)
3. The code in the loop is essential to help **convert** all actual commands to the debugging RS232 port, and the other way around, so as to enable us to use a tool like `cutecom` (on ubuntu) to pass commands to the GSM serial input pins.

> Important Note : When using cutecom ensure that you select **CR line end** to send commands.

# Answer
All Atmel MCU, on which Arduino models are based, include special hardware for serial communication; this part of the MCU is called **USART** (stands for *Universal Synchronous/Asynchronous Receiver/Transmitter*).

Based on the Arduino model you have, you may have only one (eg on UNO) or more USART (leonardo, mega...) on the board MCU.

Each MCU USART is mapped to specific pins of the board, you cannot change those pins.

On Arduino, if you use the monitor to send debug information to your PC, then one USART is used, this is when you used `Serial`.

If you need more than one serial communication link (e.g. because you have some devices that communicate through serial) but your Arduino model has only one USART, then you have to use the library `SoftwareSerial` that "simulates" the job of an USART only by software. Hence it is much less optimized than the hardware USART.

One advantage of `SoftwareSerial` is that you can map it to any pair of pins you like.

Going to your code sample:

```
if (mySerial.available())
    Serial.write(mySerial.read());
if (Serial.available())
    mySerial.write(Serial.read());

```

Obviously here, `Serial` is used for debugging (sending info to the serial monitor of your PC), whereas `mySerial` is used to communciate with the GSM device.

So this sketch is used to allow you to type AT commands on the monitor, which will then be forwarded to the GSM device; conversely, any strings returned from the GSM device will be echoed to the serial monitor.
> 10 votes

# Answer
```
#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(7, 8); //use pins 7 and 8 as RX and TX

void setup() {
   GSMSerial.begin(19200);               // the GPRS/GSM baud rate
   Serial.begin(19200);                 // the GPRS/GSM baud rate
}

void loop() {
    if(Serial.available()) {
       //to send commands received from Serial Monitor to GSM module
       GSMSerial.print((char)Serial.read());
    }
    else  if(GSMSerial.available()) {
       //To print data responded from GSM module to the Serial Monitor.
       Serial.print((char)GSMSerial.read());
    }
}

```

In the code above inside loop function first `if` statement is needed to talk to GMS module from Serial Monitor, e.g. when you type `AT` in the monitor and press enter your command gets sent to the GSM module.

The second if statement `else if` is to print whatever is received or responded from GSM module e.g. GSM module responds the received command like `AT` and its result `OK` after you send command `AT` to the module.
> 0 votes

---
Tags: gsm
---


# Question
Title: Question about configuration EEPROM or Flash
I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).

This 'setup file' needs be stored in the Arduino.

Now I thought of the following alternatives:

* Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
* Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
* Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
* Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

# Answer
> Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

> Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

> Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

> Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.

The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

> To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can `seek()` straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.
> 2 votes

---
Tags: eeprom, flash, sram
---


# Question
Title: If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)
I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

1. How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
2. How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

# Answer
Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is **where do those 5V come from**. Basically, from 2 possible sources:

1. **USB**. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.
2. **Barrel connector (wall adapter)**. It accepts 7-12V and brings it down to 5V using a linear regulator whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, **preference is given to the wall adapter**. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.

This is done not only for convenience purposes (so you have more current available), but also for **protection**. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.

I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.
> 15 votes

# Answer
You might be mixing up voltage and ampereage. The Arduino takes in from 5volts up to 12, and uses a regulator to bring higher voltages down to 5V. Milliamps (mA) is the measure of what is drawn per circuit part. The Arduino itself only draws around 25 of these, which if running off of USB, leaves around 475mA that other things can draw.
> 2 votes

# Answer
On a basic level, the 5v of the USB port is regulated by the power supply of the external device, be it a computer USB port or a USB type charging module. When you are using the power jack on the Arduino, you can provide a range of voltage, from 7v (recommended minimum) to as much as 20v. This input power passes through a voltage regulator to provide the regulated 5v necessary to operate the Arduino.

Voltage is not "used up" by the Arduino, but you may have little reserve power for additional devices which are tied into the 5v bus.

Consider that voltage can be viewed in a manner similar to water pressure, while current can be compared to the volume of water flowing. If you have a 1000 mA power supply and the Arduino uses 500 mA, you have still available 500mA at 5v for other uses.

You can experience voltage drop in a circuit, depending on the way components are connected. That's more advanced than necessary for this discussion.

This is a very basic overview and details will vary from one model Arduino to another.

Also note that one should not apply 5v to other pins marked 5v as it bypasses the regulator and can damage the board or other devices attached.
> 1 votes

# Answer
@enric blanco made a good description. I just point out the strange difference between USB (5V) and barrel connector (7-12V).

The barrel connector has to accept different power supplies (with different voltages), moreover they may need voltage regulation; thus arduino needs a "regulator" after the barrel connector. There are different composants that can do it. This simple one will provoke a minimal loss of voltage. That is why you have to input more than 5V.

There are other components (buck/boost) that could accept input voltage from 3V to 12V and always provide 5V as output, but they are more expensive (5$).
> 1 votes

# Answer
You can supply five 5V directly to the 5V pin, which is effectively what the USB interface does. The quoted 7 to 12V is only if you are using the power jack. That converts it down to 5V which is what the processor needs.
> 0 votes

# Answer
No, you don't have to input more than 5V at the raw pin while exactly 5V is output at the VCC pin (at least with the Pro Mini). How this is done I have no idea.
> 0 votes

---
Tags: power, usb
---


# Question
Title: Sound or motion activated long term battery powered Arduino
Basically, I want an Arduino to power up whenever a "creature" enters viscinity (at least within up to 3 meters).

I would really like this to be able to keep monitoring for at least 4-8 weeks, without having to replace batteries. I don't want to use more than 1 or 2 18650 Liion cells.

Couple of methods that I believe would work:

* Changes in light-conditions.
* Sound.
* Small vibrations in the ground.

Approaches to conserve power:

* Checking for changes in light at most every 30 seconds (boot the Arduino, and power off quickly).
* Checking for 1 second for sound, every 10-15 seconds.
* Vibrations in the ground using an accelerometer?

The ideal solution does not run the Arduino at all, unless a trigger causes it to run. When the Arduino starts, it will have to turn itself off again to resume monitoring mode.

What approach should I go for? I'm not very good with electronics, and would like to avoid configurations involving transistors, resistors and so on - unless stricktly required.

Is it possible/easy to wire an Arduino Pro Mini to run directly off a 3.7 V battery, bypassing any power hungry voltage regulators?

# Answer
> 0 votes
For a truly low-power, Arduino-based, solution the following it's needed:

**A) HARDWARE SIDE:**

1. Use a supply voltage and clock frequency as low as possible. The Arduino Pro Mini 3.3V @ 8Mhz board is a good starting point for a first project.
2. Get rid of all the LEDs in the board. Their consumption is in the mA range, way too high.
3. Get rid of the onboard regulator and replace it with a low quiescent current, low dropout regulator like the MCP1700. You don't need a switching regulator unless your Arduino spends most of the time awake and consuming a lot of current, which is a very unlikely scenario. The high quiescent current of switching regulators rules them out for this kind of applications.
4. Select a low-power consumption sensor and signal conditioning circuitry. PIR and CMOS logic family 74HC are good technologies for this.
5. The signal conditioning circuit must generate a level interrupt from whichever signal is delivered by the sensor. Timing elements (like capacitors) may be required for this. To be on the safe side, design it for a 100 ms resettable pulse.

**B) SOFTWARE SIDE:**

1. Install a low power Arduino library like this one. Use the ATmega328p power-down sleep mode.
2. Write a interrupt service routine (ISR). This is the piece of code will deal with whichever needs to be done upon an interrupt event.
3. Configure the interrupts as required. Note that only level-triggered interrupts can wake up ATmega328p from power-down sleep mode, as per its datasheet:

Here you can find really good information on the way to go low power.

# Answer
> 0 votes
What you want to do after the triggering is an important part of this design.

An Arduino platform is not necessarily the best choice for power sensitive applications. You identified one problem in your post: Linear regulators. What you are likely wanting is an efficient switching power supply to support a wide range of voltages as your batteries drain.

Many embedded processor have low power modes. Some are specially designed to reduce current draw down into the nA range when idle or sleeping. However, all such processors require special care when configuring for these deep sleep modes. That is to say, the application plays an important roll in deciding how to put a processor into such modes.

Supporting hardware is perhaps the most important aspect of a low power designs. Contributions from the most advanced low power processors can be wiped out if supporting hardware runs at mA ranges. A simple 10K pull up resistor will draw 0.5mA in a 5 volt circuit. The impact is meaningless in a mains powered application. But for long term battery operation is could means days of lost time.

All that said, there are resources for Arduino low power operation. Here is a low power library. You will have to decide if it is sufficient for you application. Or if you need to also investigate low power hardware solutions.

# Answer
> 0 votes
Rechargeable lithium batteries have great energy density but they also have some significant self-discharge, making a bad choice for low-power applications. Have a look on this Arduino "clone": https://talk2.wisen.com.au/product-talk2-whisper-node-avr/, which is designed to run from standard Alkaline batteries and consumes very little (under 4µA when sleeping).

For the sensors, you should look for smart ones. You can find some very sophisticated MEMs sensors which will produce interrupt based on thresholds. You normally use I²C interface to talk to those little devices.

For example, you could use something similar to this one for light sensing: http://www.vishay.com/optical-sensors/list/product-83462/. Although this is a proximity sensor, it also has thresholds for the ambient light as well as consumes very little current.

The most important is to design the solution to run at lower voltage (3.3V instead of 5V) and also use interrupts to wake-up everywhere. If you like to run a bare ATMega328p directly from a 18650 cell, make sure everything will be ok to run from 4.2V to 3.0V as you're not using any regulation.

---
Tags: power
---


title: LCD isn't working with if statement

text:
# Question
Title: LCD isn't working with if statement
```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define trigpinyellow 10
#define echopingreen 9
#define Grove_Water_Sensor 8
void setup()
{
    Serial.begin(9600);
    pinMode(trigpinyellow,OUTPUT);
    pinMode(echopingreen,INPUT);
    pinMode(Grove_Water_Sensor, INPUT);
    lcd.begin(16, 2);
}

void loop()
{
    long duration,distance;
    digitalWrite(trigpinyellow,LOW);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,LOW);
    duration=pulseIn(echopingreen,HIGH);
    distance = (duration/2) / 29.1;
    Serial.println(distance);

    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) >=20  )
    {
        lcd.clear();
        lcd.print("water_came");
        lcd.setCursor(0, 1);
    }
    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.write("Tank_is_full");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) >=20 )
    {
        lcd.clear();
        lcd.print("Fill The Tank PLEASE");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.print("Tank_is_FULL");
    }
}

```

# Answer
> 1 votes
Every time you instantiate digitalread(), you poll the pin. Here, you're polling pins 8 times every loop. Instead, poll the two pins at the start of the loop to update the variable, and then do your math and make your decisions afterward. Right now you're doing math with your distance variable, and then overwriting the variable during your if conditionals. Not sure if that's what you intend. You're also creating the variables duration and distance every single loop. instead, create those variables globally and just update them every loop.

---
Tags: programming, lcd
---


# Question
Title: Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors?
I am using PWM (*analogWrite*) with a common *anode* LED. My previous experience is using a common cathode. My breadboard is as shown:

simulate this circuit – Schematic created using CircuitLab

This creates a semi-bright white (ugly red-green-blue mixture) like I expected. I am using only one PWM output (It is currently fading).

Now, what I ask is how can I use multiple PWM outputs to make different colors display *without* transistors? I was thinking that I could have 3 dedicated pins on the Arduino that switch from ground to floating extremely fast, but is there an easier way? If not, a little explanation on how to do it with transistors (mostly just a small wiring diagram) would be great. Cheers!

# Answer
> 2 votes
As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

simulate this circuit – Schematic created using CircuitLab

Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.

Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.

# Answer
> 1 votes
> I am using only one PWM output (It is currently fading).

use three independent pwm channels to drive three leds.

> how can I use multiple PWM outputs to make different colors display without transistors?

the answer depends on the leds. for leds that require small current, it is totally doable, just connect the pwm output to them.

for leds that require lots of current, no solution.

---
Tags: led, pwm
---


# Question
Title: Ultrasonic sensors with 12v motors will not work! (ADRUINO)
ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results... in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple! but the wheels on the left side of my robot will stop! and just do nothing!

The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.

this is the shield I am using: https://www.pololu.com/product/2507

if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...

the code.

```
#include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;

#define trigPin 7
#define echoPin 8

void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

//This is the sensor testing if somthing is in range!
if (distance < 4){
        Serial.println("in range");
        md.setM1Speed(100);
        md.setM2Speed(-100);
}
else {
        Serial.println("not in range");
        md.setM1Speed(-100);
        md.setM2Speed(100);
}

if (distance >= 200){
        Serial.println("!");
}
else {
        Serial.print(distance);
        Serial.println(" cm");
}
    Serial.println(distance);
    delay(500);
}

```

# Answer
> 1 votes
**TLDR:** change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

---

You are using `pins 7 and 8` for ultrasound.

At the same time you are using the shield https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture `Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).`https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5 You will see, that the shield is using `pin 7` as `M2INA` and `pin 8` as `M2PINB`

So each loop you push `M2INA` (`trigPin`) LOW, then HIGH then LOW, then wait until the sensor write HIGH to `M2INB` (`echoPin`) just to immediately send PWM pulses to both `trigPin` (`M2INA`) and `echoPin` (`M2INB`) via commands

```
    md.setM1Speed(100);
    md.setM2Speed(-100);

```

No way it can work as you expect.

You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare

```
#define trigPin 3
#define echoPin 5

```

and connect your ultrasound sensor there acordingly.

(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").

Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.

---
Tags: sensors, motor, arduino-motor-shield
---


# Question
Title: Arduino MIDI Program Change to Voodoo Labs GCX Converter
To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

# Answer
> 2 votes
To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.

For reference:

* A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D =\> Binary 01001101
* A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD =\> Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0

Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.

The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)

It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.

I have tested this on a Arduino UNO board with an Olimex MIDI Shield.

```
// GCX Editor
// By Rich Maes
// Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
// Allows everything else to pass.

#define MIDI_PC_CH16 0xCF
#define MIDI_CC_CH16 0xBF
#define MIDI_SYSEX 0xF0
#define MIDI_SYSRT_CLK 0xF8

boolean byteReady;
boolean sendCCMessage;
int ccMsgsToSend;
unsigned char midiByte;
unsigned char capturePCByte;
unsigned char captureCCByte;

// Queue Logic for storing messages
int headQ = 0;
int tailQ = 0;
unsigned char tx_queue[128];

int getQDepth();
void addQueue(unsigned char myByte);
void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
unsigned char deQueue();

static enum {
    STATE_UNKNOWN,
    STATE_1PARAM,
    STATE_1PARAM_CONTINUE,
    STATE_2PARAM_1,
    STATE_2PARAM_2,
    STATE_2PARAM_1_CONTINUE,
    STATE_PASSTHRU
  } state = STATE_UNKNOWN;

void setup() {
  // put your setup code here, to run once:
  //  Set MIDI baud rate:
  Serial.begin(31250);
  sendCCMessage = false;
  byteReady = false;
  midiByte = 0x00;
  state = STATE_UNKNOWN;
  captureCCByte = 0;
  capturePCByte = 0;
  ccMsgsToSend = 0;
}

int getQDepth() {
int depth = 0;
    if (headQ < tailQ) {
        depth = 128 - (tailQ - headQ);
    } else {
        depth = headQ - tailQ;
    }
    return depth;
}

void addQueue (unsigned char myByte) {
    int depth = 0;
    depth = getQDepth();

    if (depth < 126) {
        tx_queue[headQ] = myByte;
        headQ++;
        headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
    }
}

void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
    int i;
    if (getQDepth() < 80) {
        // There is enough space to add our CC messages
        for (i = 0; i < 8; i++) {
            addQueue(0xBF);
            addQueue(80 + i);
            addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
        }
    } else {
        // This is an error condition.  So reset the queue and pointers
        headQ = 0;
        tailQ = 0;
        byteReady = false;
        for (i = 0; i < 128; i++) {
            tx_queue[i] = 0;
        }
    }
}

unsigned char deQueue() {
    unsigned char myByte;
    myByte = tx_queue[tailQ];
    tailQ++;
    tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
    // Now that we dequeed the byte, it must be sent.
    return myByte;
}

void loop() {
    if (byteReady) {
        if (midiByte >= 0xF0) {
            // This automatically passes all clocks and System Realtime Messages
            state = STATE_PASSTHRU;
        } else if (midiByte >= 0x80) {
            switch (midiByte) {
            case MIDI_PC_CH16:
                state = STATE_1PARAM;
                break;
            case MIDI_CC_CH16:
                state = STATE_2PARAM_1;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }  else {
            switch (state) {
            case  STATE_1PARAM:
                capturePCByte = midiByte;
                state = STATE_1PARAM_CONTINUE;
                addCCQueue(captureCCByte, capturePCByte);
                break;
            case STATE_2PARAM_1:
                if (midiByte == 32) state = STATE_2PARAM_2;
                else state = STATE_2PARAM_1_CONTINUE;
                break;
            case STATE_2PARAM_2:
                state = STATE_2PARAM_1_CONTINUE;
                captureCCByte = midiByte;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }
    }

    if ((state == STATE_PASSTHRU) && byteReady) {
        // Just pass messages unaltered.  Also don't let any of our modified message through if
        // we are passing though.  Our burst of modified CC# can wait.
        // Serial.write(midiByte);
        addQueue(midiByte);
        // state = STATE_UNKNOWN;
    }
    byteReady = false;

    if (getQDepth() > 0) {
        // We have a byte to send, dequeu and send it
        Serial.write(deQueue());
    }
}

// The little function that gets called each time loop is called.
// This is automated somwhere in the Arduino code.
void serialEvent() {
  if (Serial.available()) {
    // get the new byte:
    midiByte = (unsigned char)Serial.read();
    byteReady = true;
  }
}

```

---
Tags: arduino-uno, midi
---


title: Toggle a led with a switch

text:
# Question
Title: Toggle a led with a switch
My code:

```
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool buttonState = 0;         // variable for reading the pushbutton status
bool ledState = 0;
void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
  buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
 {
  ledState = !ledState;
 }
  if (ledState == HIGH)
 {
   digitalWrite(ledPin, HIGH); // turn LED on:
 }
   else
 {
    digitalWrite(ledPin, LOW); // turn LED off:
 }
}

```

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

# Answer
In addition to the debouncing suggested by the other answers, you have a further problem: your `loop()` will whiz through in a very short time, and run again while your finger is still on the button, turning the light off. And then run again, turning it back on again, and so on.

You need to wait for the button to be released before registering another change.

```
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool ledState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop() {
  bool buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
  {
    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);

    ledState = !ledState;
    if (ledState == HIGH)
    {
      digitalWrite(ledPin, HIGH); // turn LED on:
    }
    else
    {
      digitalWrite(ledPin, LOW); // turn LED off:
    }

    // Wait for the button to be released
    while (digitalRead(buttonPin)) {}

    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);
}

```
> 1 votes

# Answer
If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

```
pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

```

Also, you need to debounce the button.
> 1 votes

# Answer
The mechanical switches bounces. That's all. It's too fast for you to see it but MCU is much faster, so output state is switched many times before contacts are stabilized and no more bounces are causing "turning on and off".

The term you are looking for is **debouncing**
> 0 votes

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


# Question
Title: Interrupt routine for button somehow respondng to room lamp turning off and on
I have a sketch that has been running fine on an Uno 24x7 for a few months now. The part of interest is an interrupt routine associated with a momentary contact switch \[on pin 2\]. When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable. The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.

Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light \[not connected to anything but a 120v outlet\].

The Uno buzzer went off, and appropriate msgs were written to the serial connection. I flipped the light back on, and got the same kind of results. I repeated this numerous times and got the same. I could flip the light or push the button attached to the Uno, and the results were indistinguishable.

I unplugged the USB cable and used the power jack instead. I got the same results, sans the print msgs to the serial connection.

The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.

What is happening? How can I resolve the problem? \[If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.\]

I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

# Answer
Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

1. **Conducted EMI** through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).
2. **Radiated EMI** (most likely). There are some things you can do to mitigate its effects:

* Use wires as short as possible.
    * Twist wire pairs whenever possible.
    * Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
    * Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
    * Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
    * Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this this. You'll have a better grasp about the art of debouncing inputs.

SPOILER: One thing you can do to make your debouncing routine far more robust is to **wait for N consecutive readings with the same value** (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.
> 1 votes

# Answer
My guess: pickup on the input line from interference. (I'd expect this more if the switch were on a long cable away from the Arduino.)

If the button uses an external pull-up resistor, try a smaller value (maybe 5k?). If it uses the internal pull-up, try adding an external one.
> 0 votes

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