title: Is cheap away arduino trustworthy

text:
# Question
Title: Is cheap away arduino trustworthy
I have recently decided to buy an arduino over a raspberri pi and have been shopping for a good deal and learning about which model I need and where to buy.

I have come across a few very cheap arduino uno boards that are identical to every other board. These range from an unbelievable $4-$15. Are they officially branded and/or are they trustworthy?

Here is a link to a few links to some I've found:

http://m.ebay.com/itm/New-UNO-R3-ATmega328P-Development-Board-For-Arduino-Compatible-USB-Cable-DIY-/311418263595?nav=SEARCH

http://m.ebay.com/itm/NEW-UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-WL-/161883302204?nav=SEARCH

# Answer
> 1 votes
Caveat Emptor.

If it's not genuine you can never be sure quite what you are getting. You have to ask with some of then just how they can make them so cheap. Poor quality components is one way. Either counterfeit or reject components which may fail after a short time, or under certain conditions is a big risk.

There are different grades of board each with their own risks...

1. Genuine. High price, good reliability and quality. Good after sales support. Supports the Arduino cause.
2. Arduino clone. Genuine Arduino design made by a reputable third party. Almost as good as option 1 but doesn't support Arduino financially.
3. Arduino Based. A board created for a specific job that is based around genuine Arduino design. Support really only from the (often smaller) manufacturer. Quality varies.
4. Chinese clone. Low grade components made to original Arduino designs. Little or no support. Poor quality. Often with different USB interface that is unstable and low quality.
5. Counterfeit. Low quality components. Claims to be a genuine Arduino. Bad build quality.

Options 1-3 are ones I would consider buying. 4 and 5 I would stay well away from.

# Answer
> 0 votes
How many Arduinos do you need? If you are just getting one to learn on, for heaven's sake pay the extra fifteen bucks and support the cause.

If you are manufacturing something and need a few dozen boards, buy 50 Chinese ones and chuck the ones that don't work.

# Answer
> 0 votes
While, yes, caveat emptor, I have purchased a number of devices which are based on the Arduino open design. I have not yet had a problem.

Remember that, if you buy more expensive, prominently "Arduino" branded parts, from a third party, you also have no guarantee that they are quality controlled by Arduino. Even "genuine" electronics parts are usually manufactured in China, often in the same factories.

To answer your question, there are a number of ways the costs can be kept down:

Lack of unions, lack of labor laws, economies of scale, markup by the "official" companies, lack of development costs (remember, Arduino is open hardware, copying is allowed), cheap labor, tax, transport costs (there is some trickery in some countries, including Hong Kong, which makes shipping essentially free), shorter supply chain, cheaper components, smaller marketing budget.

---
Tags: arduino-uno
---


# Question
Title: Are there ultrasonic transducers which are able to produce a "chirp" sound wave?
I'm working in a ultrasonic radar project and the supervising teacher wants us to produce a chirp sound wave (a frequency-varying sinusoid).

I'm familiarised with the usual ultrasonic module, but as far as I know, it cannot do the task.

I searched on-line for transducers that I could use, but couldn't find anything useful. Are there any commercially available component that could do this task? If not, what could I possibly do?

# Answer
> 1 votes
Piezoelectric speakers, the kind commonly found in ultrasonic transducers generally operate in a narrow frequency range when operating at ultrasonic range (a resonate frequency of the metallic diaphragm). This is very true once you get above about ~60 kHz. However if the ultrasonic "chirp" you are looking for can be in the range of say 20-60 kHz you could be in luck, i.e., http://www.conrad-electronic.co.uk/ce/en/product/710991/KEPO-piezo-element-25-60-kHz-515-mm

You could use the Tone function (which goes up to 65535 Hz) to produce the frequency sweep you desire. However if you want to go up to frequencies in the 100+ kHz range you will be delving into research territory and hence extremely expensive equipment.

Having said that, technologies change very quickly and I my knowledge may already be out of date. Hope this helps.

---
Tags: arduino-uno, frequency, sound, components
---


title: ATTiny85 433Mhz with sleep

text:
# Question
Title: ATTiny85 433Mhz with sleep
I would like to micromize my Arduino project and move it to ATTiny85. The first step was using sleep functions because I just want it to run once a day. Now I need to connect the 433Mhz stuff but I'm getting into a fight with cores vs. libraries vs. missing functions.

No matter what core and library combination I pick, there always seems to be something missing.

```
/home/thijs/Documents/Arduino/libraries/VirtualWire/VirtualWire.cpp:260:18: error: 'WGM12' was not declared in this scope
     TCCR1B = _BV(WGM12) | _BV(CS10);

```

I have tried `Tiny` cores, `high lowtech` cores and Manchester and VirtualWire libraries. I don't want to dive into the libraries and make them 'suitable' for ATTiny because I have more than one project.

How do I approach this dependency problem?

\[**edit**\]
Found a better core here: https://github.com/SpenceKonde/ATTinyCore

# Answer
The error you posted has nothing to do with an Arduino core. This is just plain avr-libc stuff. In order to use this kind of functionality, you need to

```
#include <avr/io.h>

```

In the Arduino core, it is common to have this done by default. But if this is not the case with your chosen core, just add the `#include` yourself in the program.
> 2 votes

---
Tags: attiny, sleep
---


# Question
Title: Why is my pushbutton always reading LOW?
I know this is ridiculously simple task but I spent the last two hours trying to get this to work and it is not working. I don't have an Arduino but I have an ESP8266 Huzzah Feather which is programmable via the Arduino IDE. So, I don't think I can provide a Fritz diagram but in any case, I'm just trying to hook up a pushbutton and be able to read a HIGH or LOW (via my Serial monitor). Currently, everything is 0.

As best I can describe it is:

5V from Feather into resistor into one terminal of the pushbutton. Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground. Feather is also grounded.

My code is:

```
void setup()
{
  Serial.begin(9600);
  pinMode(12, INPUT);
}

void loop()
{
  int button_val = digitalRead(12);
  Serial.println(button_val);
}

```

It shouldn't be this hard for me. Whenever I open and run the serial monitor, it reads 0s. What am I missing?

Oh, an issue that I faced is determining which 2 out of the 4 terminals of the pushbutton to use. Some resources I find say that it is the same side as the terminal the voltage is flowing into; other resources say it is the terminal opposite to the side the voltage is flowing into. I currently have it opposite.

# Answer
> 3 votes
> Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.

That sounds to me like you have connected the IO pin direct to ground.

The IO pin should connect to the same pin as the resistor that connects to +5v. The other side of the button should connect to ground only.

For instance using @HansNeve's button picture you could connect pin A to the IO pin and via a resistor to +5V, and pin B to ground.

# Answer
> 4 votes
The pins on each side of the button are shorted, the "button" is between the *sides* of the button. Else your code looks alright.

Edit: Here's an image which shows how a push button is connected internally, make sure you're using the correct pins.

---
Tags: arduino-ide, button
---


# Question
Title: Cheapest Arduino wireless solution for home automation
I am from programming background and newbie to this field.

Couple of days ago I brought **Arduino Uno (5V)**. I want to control light bulb and fan from my **Android**. So I thought, I will buy **relays** and **ESP8266** module and its done.

But now read somewhere that ESP8266 works with **3.3v** and my Arduino supplies **5v**.

Should I go for different Arduino board (like Arduino pro or Arduino mini) or is there any **reliable & cheap** solution that will work my **Arduino Uno (5V)** ?

# Answer
> 2 votes
If you want to go for cheap just use a ESP8266 no arduino needed.

---
Tags: arduino-uno, power, wifi, wireless
---


# Question
Title: Arduino micro lost connection after first programming
I have just programmed a new micro, loaded the basic blink code in it. After that neither my laptop, nor my desktop sees it anyway with the following usb error:

```
Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: USB disconnect, device number 8
[Fri Apr  1 14:32:03 2016] usb 1-2: new full-speed USB device number 9 using ohci_hcd
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62

```

If I push the reset button on it it comes back a bit then disappears again:

```
22620.495256] usb 1-2: New USB device found, idVendor=2341, idProduct=0037
[22620.495263] usb 1-2: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[22620.495268] usb 1-2: Product: Arduino Micro
[22620.495272] usb 1-2: Manufacturer: Arduino LLC
[22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[22627.966141] usb 1-2: USB disconnect, device number 32
[22628.432089] usb 1-2: new full-speed USB device number 33 using ohci_hcd
[22628.572111] usb 1-2: device descriptor read/64, error -62

```

Anybody experienced this? I have tried to reconnect it multiple times to both computers, even tried a new cable doesn't help.

# Answer
> 3 votes
The USB part of the Atmega32U4 needs quite a bit of software to operate correctly, which is either not included in the basic blinky example or you got a binary for a different Arduino model.

The syslog looks like there is a bootloader present after Reset for a couple of seconds..

```
[22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
     ^
[22627.966141] usb 1-2: USB disconnect, device number 32
     ^

```

.. which shuts down and starts blinky. This is documented on the ArduinoBoardMicro page.

Re-flashing the chip is a bit tricky in this state, as you must press the reset button at the "right" time just before the software wants to access the chip.

# Answer
> 0 votes
> If I push the reset button on it it comes back a bit then disappears again:

That's exactly how it works. The Micro enumerates as a Serial interface for a couple of seconds after reset, enough time for you to upload a new sketch. If you don't upload in time, and unless your code specifies a serial port, the serial interface goes away. Blink doesn't use a serial port.

You need to quickly press and release Reset at the exact moment that the IDE says it is uploading, and the board should then detect the new sketch.

---
Tags: usb, arduino-micro
---


title: Wire Library send/receive

text:
# Question
Title: Wire Library send/receive
I'm doing a project that includes an Arduino Uno and custom hardware made by me. Everything is working perfectly independently, and I'm trying to implement a way for them (the Arduino and my hardware) to work together. In order to achieve that, I am using the Wire protocol (Arduino side) and I2C (custom hardware side). From now I can send data from **my hardware** to **my Arduino** in a **master-slave** relation, and I have no problem with that. Please take a look at my Arduino code for better understanding:

```
void setup(void) {
  Wire.begin(7);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int howMany) {
  int x = Wire.read(); // receive byte as an integer
  Serial.print(x);
  if (x==0)
    state = 0;
}

```

So far so good. Now I want to send data from the **Arduino** to my **custom hardware** full duple, and for that I am adding this code:

```
void frame(void){
  Wire.write('x');
  Wire.write('\r');
}

void loop() {
  if (state == 0){
    frame();
    state = 1;
  }
}

```

In order to receive the 'x' char in my custom hardware I have switched the I2C protocol bit from Write to Read using `I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_WRITE);` to `I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_READ);` in my custom hardware code.

I don't know why, I am not receiving the data from the Arduino. Am I missing any configuration on the Arduino side?

# Answer
> 1 votes
I've not done events on an Arduino so this could be a bum steer, but shouldn't the state variable be volatile and protected with a semaphore? You are accessing it in the main program and in your event/ISR.

Secondly, no offence intended, could you replace your hardware with a bit of tried and trusted hardware to eliminate the remote possibility that your hardware is at fault.

# Answer
> 1 votes
You use the `onReceive()` and `onRequest()` methods of the Wire library to implement an Arduino slave. In your case, something like this:

```
void setup(void){
  Wire.begin(18);
  Wire.onReceive(receiveEvent);  # register receive handler
  Wire.onRequest(requestEvent);  #register request handler
  Serial.begin(9600);
}

void receiveEvent(int howMany){
  int x = Wire.read();    // receive byte as an integer
  Serial.print(x);
  if (x == 0)
    state = 0;
}

void requestEvent(){
  Wire.write("x\r");
  state = 1;
}

```

See Slave Receiver and Slave Sender examples for more details.

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


title: LCD readout is odd

text:
# Question
Title: LCD readout is odd
I want it to display the current temperature in the middle of the screen, fade out for two seconds, display new temperature, rinse repeat. This is current (see images)\]

```
/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *THIS NOW WORKS!!! Except for reading to LCD.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);
   // when characters arrive over the serial port...
  if (Serial.available()) {
    // wait a bit for the entire message to arrive
    delay(100);
    // clear the screen
    lcd.clear();
    // read all the available characters
    while (Serial.available() > 0) {
      // display each character to the LCD
      lcd.write(Serial.read());

  // delay at the end of the full loop:
  delay(1000);

}
  }
}

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.print(" temp: ");

  if (isnan(temperature)) {
    lcd.println("Failed");
  }
  else {
    lcd.print(temperature);

  }
}

```

# Answer
> 1 votes
Before you write the first character of your temperature text, set the cursor to where you want that first character to display.

For example, use `lcd.setCursor(col, row);` to set the cursor at a specified column in a specified row. Row and column numbering starts from zero.

You can also use `lcd.home();` to set the cursor at (0,0).

The output cursor advances a column each time you write a character.

# Answer
> 0 votes
```
/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *THIS NOW WORKS!!! Except for reading to LCD.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 1);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);

  }

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.setCursor(1,1);
  lcd.print(temperature);
  lcd.setCursor(7,1);
  lcd.print("celcius");

}

```

# Answer
> 0 votes
```
/*
 * File:    readTemperature.ino
 * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
 * License: GPLv3
 *
 * For more information see www.freetronics.com/irtemp
 *After much playing around this is the finaL result.
 */

#include "IRTemp.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

static const byte PIN_DATA    = 2; // Choose any pins you like for these
static const byte PIN_CLOCK   = 3;
static const byte PIN_ACQUIRE = 4;

static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

void setup(void) {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 1);
  // initialize the serial communications:
  Serial.begin(9600);
}

void loop(void) {
  float irTemperature = irTemp.getIRTemperature(SCALE);
  printTemperature("",irTemperature);
 delay(1000);

  }

void printTemperature(
  char  *type,
  float  temperature) {

  lcd.print(type);
  lcd.setCursor(1,1);
  lcd.print(temperature);
  lcd.setCursor(7,1);
  lcd.print("celcius");

}

```

---
Tags: c++, lcd, display
---


title: IR remote unstable button numbers

text:
# Question
Title: IR remote unstable button numbers
**Question**

Is there a reason for unstable button numbers of an IR remote?

**Desciption**

I wrote a remote class where I identify the pressed number of the remote to set states. But however I get never the same number of the pressed key.

For example I press the number '1' and on the serial interface shows this:

```
3588650484
2740290906
3148594742
689746115
2396927248
2934053595
4294967295
3876827360

```

And it should look like this:

```
16724175 // Button 1
4294967295
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1

```

**Hardware**

I am using an arduino UNO board and the standart remote of the starter kit. There is no name just 'SPECIAL FOR MP3'.

**Some more infos**

Ok, in my first project I used the code from Noreddine Kessa(Example Project) which works fine. Next I copied some code in my new class 'IRControl.cpp' ( you can see below). Then I created an object IRControl in the main.cpp and run the menu() in the loop.

h-File:

```
/*
 * IRControl.h
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#ifndef IRCONTROL_H_
#define IRCONTROL_H_

//Remote Defines
#define buttonON 16753245
#define buttonMode 16736925
#define buttonSoundOff 16769565
#define buttonPlayStop 16743045
#define buttonTrackBack 16712445
#define buttonTrackForward 16761405
#define buttonEQ 16769055
#define buttonMinus 16754775
#define buttonPlus 16748655
#define button0 16738455
#define buttonRepeat 16750695
#define buttonJSD 16756815
#define button1 16724175
#define button2 16718055
#define button3 16743045
#define button4 16716015
#define button5 16726215
#define button6 16734885
#define button7 16728765
#define button8 16730805

#include "IRremote.h"
#include "wiring_private.h"

enum zustaende{Motor1, Motor2, Motor3, Sleep};
extern int zustand;

class IRControl {
private:
    IRrecv *irrecv;
    decode_results remoteValue;
public:
    IRControl(int RECV_PIN);
    virtual ~IRControl();
    void menu();
};

#endif /* IRCONTROL_H_ */

```

cpp-File:

```
* IRControl.cpp
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#include "IRControl.h"

IRControl::IRControl(int RECV_PIN) {
    // TODO Auto-generated constructor stub
    irrecv = new IRrecv(RECV_PIN);
    pinMode(RECV_PIN , INPUT);
    irrecv->enableIRIn();
}

IRControl::~IRControl() {
    // TODO Auto-generated destructor stub
    delete irrecv;
}

void IRControl::menu() {
    if (irrecv->decode(&remoteValue)) {
        //lReceived = remoteValue.value ;
        Serial.println(remoteValue.value);
        /*
        switch(remoteValue.value)
                {
                case button1:
                    zustand = Motor1;
                    //digitalWrite (LED1, HIGH); // for control
                    break;

                case button2:
                    zustand = Motor2;
                    //digitalWrite (LED2, HIGH);
                    break;
                case button3:
                    zustand = Motor3;
                    //digitalWrite (LED3, HIGH);
                    break;

                case button0:
                    zustand = Sleep;
                    break;

                default: break;
                }
                */
        irrecv->resume(); // Receive the next value
      }
}

```

**Where the problem could be**

I think there could be a problem with the `IRrecv *irrecv;`. But i'm not sure.

Thanks for your help

# Answer
Please post the code where you call the library. In particular where do you make an instance of IRControl?

I am guessing you are doing it at global scope which means you are probably running into the *C++ static initialization order fiasco*.

What it is: http://www.parashift.com/c++-faq/static-init-order.html

How to prevent it: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

To prevent this, you should **not** be doing this in the class constructor:

```
irrecv = new IRrecv(RECV_PIN);
pinMode(RECV_PIN , INPUT);
irrecv->enableIRIn();

```

Instead, make a `begin` function (like most Arduino classes do) and call that from `setup`.
> 1 votes

---
Tags: c++, button, remote-control
---


# Question
Title: How do I connect a vibration motor to Arduino?
I'm trying to figure out how to connect a vibration motor to my Arduino. I've come across this resource and it seems pretty straightforward though for a while my eye glazed over at how complicated the circuit was (do I really need all of that to run my vibration motor?).

My real question is that I have a vibration motor similar to the picture in the link and I'm trying to figure out how to actually connect it to my breadboard. Do I have to solder wires onto those flimsy ends or is that a better way to get this to work?

Thanks!

# Answer
Lets break down the circuit and have a look why everything in that circuit is there and what it does.

First we have the 33R resistor before the motor which limits the current to the motor. This particular motor is rated at 75mA and has a starting of 85mA. The 33R resistor limits the current to 130mA maximum through the motor. If the risk of the motor pulling too much current is an issue then stick a fuse in-line

Then there's the motor, not much to say here really. It's whatever motor you're using.

We then have both a diode and a capacitor across the motor. I find this a bit strange, I've seen the use of flyback diodes, I've seen the use of snubbers, but both? The purpose of the diode is to allow a return path for any spikes caused by switching off power to the inductive load (the motor) which stops them from damaging the transistor. For the capacitor, just remove it, it's not got any use here really.

Then comes the transistor, it might be easier to think of a transistor as a switch (especially in this example). When you put a little bit of current on the base, the transistor 'opens' allowing the motor to connect to ground. The reason we have to use a transistor is because the outputs of an arduino are only able to supply a maximum of 40mA, we need more than that to run our motor. Fortunately, the transistor is not going to need any more than 5mA on it's base which is why we use it to 'switch in' components that require more voltage/current. The 1K resistor on the base is to limit the current coming from the arduino and preventing it from killing our poor transistor.

tl;dr - You need everything except the capacitor
> 3 votes

# Answer
There are actually a number of things wrong with that circuit.

First the motor runs from 2.5 to 3.8V, yet they show it running off the 5V supply pin.

Secondly they include a 33Ω resistor to "limit the current". It doesn't! It drops a voltage depending on the current flowing through it, and the current flowing through it depends on the speed and load of the motor at the time. So the motor itself will be getting a fairly random voltage applied to it, which at times will be below the specifications.

E.g.:

* The start current is 85mA. V=RI, 33\*0.085 = 2.805V. 5 - 2.805 = 2.195V: way below the 2.5V required minimum.
* The run current of 75mA calculates as: 33\*0.075 = 2.475. 5 - 2.475 = 2.525V: only just enough for it to run.

So it should be powered from a 3.3V supply that has enough current capacity to drive it (85mA) and the 33Ω resistor should be removed entirely.
> 2 votes

# Answer
I've never used a vibration motor, but I think you do need all of the circuit. Its says in the text, but the transistor is needed because the Arduino 'doesn't supply enough current through the output port' and the diode and cap are required to prevent spikes.

As to the flimsy wires you could solder them onto a bit of strip board and then solder "proper" wires of connectors onto the board too.
> 1 votes

# Answer
You could make a simpler circuit by removing the diode, capacitor. BUT this comes at the cost of having a circuit that could kill your arduino.

Stick with it and build the entire thing. This isn't a shortcut worth taking.
> 1 votes

---
Tags: motor
---


# Question
Title: What would be the architecturally-right place to put custom -D defines?
What I am trying to accomplish is to include information about the state of my environment at build time in my code. For example, I may want the `setup()` code to print the git sha it was built against, and the time of build.

There are two related issues here:

1. How to include that information in the code
2. How to specify to the build environment what to generate in the first place.

The first can be addressed in a number of ways:

* -D options can be generated at build time, and the corresponding defined macros expanded in the code. For example, the compiler could be invoked as `g++ -DGIT_SHA=$(git rev-parse HEAD) -DDATE=$(date '+%Y%m%d-%H:%M:%S')`, and my code could have something like `#define strfy(_x) #_x` followed by `Serial.println(strfy(GIT_SHA));`. Or the build tool could generate a header file that would define these as external string variables, which the main sketch could then include and print. Or any other number of tricks.

The question I am really asking is: **how should I specify this sort of stuff for `arduino-builder`?**

Ideally, it would be a custom recipe in `platform.txt`, but if there is a way to invoke shell commands in recipes and use the results to modify other variables (such as `preproc.macro.flags`), I haven't been able to find it (if there is documentation, it's really well hidden). Ideally I would want to be able to say `preproc.macros.flags=-w -x c++ -E -CC -DGIT_SHA=$(git rev-parse HEAD)` and have the shell command be executed at the point.

So, before I set out to hack arduino-builder, do people have any opinion on this? My main criterion is something that would be of general value and has a chance of being incorporated in the code, rather than a kludge that only works for me and which I have to patch every time I upgrade. Please do not suggest workarounds. I can think of several myself!

I *did* try to search, and this sort of issue has come up before, but I didn't see any satisfactory answers from people who knew what they were talking about.

Thanks!

/ji

# Answer
That is a tough one... Because arduino-builder is basically a custom go script you don't get the facilities you get in a Makefile, like shell execution.

I would be inclined to do this kind of thing outside that environment - use some external program or tool to generate a config.h file (maybe use something like GNU Autotools) that contains your custom defines. That can then be #included in your sketch.
> 1 votes

# Answer
For the date and time of compilation there are predefined preprocessor symbols: `__DATE__` and `__TIME__`.
> 0 votes

---
Tags: arduino-ide, build
---


title: Changing timing intervals with millis()

text:
# Question
Title: Changing timing intervals with millis()
My goal is to run a vibrating motor for **specific** time intervals. I am using the `millis()` function to successfully turn the motor on and off, but only if the `intervalOn = intervalOff`. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the `millis()` code with one no-changing interval, it all works flawlessly... Is there any other way to change the intervals?

The `Vibrating()` function gets called from the `loop()` whenever `vibrEnabled = true`

```
unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;

void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;

if((unsigned long)(currentMillis - previousMillis) >= interval)
{
    PORTC ^= (1<<PC1);//toggle motor

    if(interval != last) //this part causes the problem
        interval = last; //
    else                 //
        interval = pause;//

    cyclesPassed++;
    if(cyclesPassed == 8)//motor is on 4x
    {
    cyclesPassed = 0;
    vibrEnabled = false;
    }

    previousMillis = millis();
 }
}

```

# Answer
> -1 votes
The problems were caused by the vibrating motor. It's shaking caused the rotating part touched the surface and the motor stopped for a while.
Thank you for you help.

# Answer
> 0 votes
1. Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
2. Maybe your vibrating motor is drawing too much current and power-cycling the board.
3. Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you *never* power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".

---
Tags: timers
---


# Question
Title: Is it safe to power an MQ-7 gas sensor with a 9V D.C supply?
I'm looking for a portable power source for an MQ-7 gas sensor. According to my research - it needs 5V D.C power with at least 0.3A of current. I'm not really good with electronics so I need to know if I can use a 9V battery instead which produces 0.5A. Will the cell damage my sensor and if it does may you please recommend me something else.

# Answer
You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.

To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.

Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.
> 0 votes

---
Tags: arduino-uno, electronics
---


title: How do I use SNAP protocol, correctly?

text:
# Question
Title: How do I use SNAP protocol, correctly?
I've reviewed the documentation

I'm still a little lost when it comes to applying the functions. Each of the redundancy check methods take in an unsigned char and return an unsigned char.

Shouldn't there be some sort of boolean return somewhere confirming that the data is accurate?

I've been trying to debug `unsigned char* tempData = "snap"` to the terminal, writing it directly to the register, according to the doc it should return `h17`:

```
  UDR0 = crc8(tempData,sizeof(tempData));

```

The terminal outputs '?' - as if it cannot be read.

# Answer
> 2 votes
The `crc8` function calculates the Cyclic Redundancy Check (8-bit) value for the data you provide. It is then up to you to compare that calculated value with the CRC you have received.

The `?` you are seeing in the serial terminal is an *unprintable* character. It is representing an 8-bit value that doesn't lie within the 32-127 range of normal ASCII characters, or 32-255 of the extended ASCII character set.

---
Tags: c, avr
---


# Question
Title: Extracting a substring from original string
I am trying to extract a substring out of another string, but it doesn't seem to be working. I am new to programming in arduino and c++ in general. Here is my code:

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

char rfid;

void loop()
{
  while (Serial.available() > 0)
  {
    rfid = Serial.read();
    String cardnum(rfid);
    cardnum.replace("", "");
    cardnum.replace("", "");
    String id = cardnum.substring(0,2);
    Serial.print(id);
  }
}

```

The first argument in `cardnum.replace("", "");` and `cardnum.replace("", "");` replaces the start and end bit with nothing, but it somehow doesn't display it correctly here.
Now on to the problem at hand. The output for `cardnum` is *1F006B471F2C* which it should be, but the ouput for `id` is the same, when i want it to be only the first two characters of `cardnum`. How would i go about achieving that.
Thanks in advance for any answers you can provide.

# Answer
> 2 votes
Let's dissect your program a moment and see why it's not doing what you want:

```
while (Serial.available() > 0)
{

```

So while there are characters available to read in the serial buffer

```
  rfid = Serial.read();

```

read one character into the `rfid` variable.

```
  String cardnum(rfid);

```

Convert that character into a string.

```
  cardnum.replace("", "");

```

Replace nothing (`""`) with nothing (`""`)

```
  cardnum.replace("", "");

```

Do the same again,

```
  String id = cardnum.substring(0,2);

```

Take the first two characters of the string that contains the single character that you have read.

```
  Serial.print(id);

```

Print it.

So basically you have read one character, made it into a string, done nothing to it, copied it to another string, then printed it.

Instead of this method, which does nothing useful, you should read the whole ID into a string (I'd use a C string \[i.e., char array\] rather than an Arduino String object) then perform operations on that string once you have read the whole ID code.

There's many methods of doing that, but how you do it is heavily influenced by exactly how the data is presented to you. Does it have a terminating CR or LF to indicate the end of the string? If not you will have to use some form of timeout to determine when the string has been completer.

---
Tags: string, rfid
---


# Question
Title: Looking for a Mega 2650 drawing or picture that shows the components labeled
I am Looking for a Mega 2650 drawing or picture that shows the components labeled.

I've seen the schematics but didn't find a labeled assembly drawing yet. Should this exist?

Thanks

# Answer
Yes, it exists, but not (commonly) as an "image" in the traditional sense.

You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.
> 2 votes

---
Tags: arduino-mega, components
---


# Question
Title: Trying to start a timer to change lights when a button is pressed
I am trying to setup a series of lights (traffic lights) that change based on a timer that begins when a button is pressed. The goal is to use the lights to track how long its been since you pressed the button.

The issue I am running into is trying to use the "TimeAlarms" library. I am getting an error 'Timer' was not declared in this scope

I think it may be an issue with the version of Arduino I am using (1.6.8) but I am not sure.

Board: Arduino Leonardo

**Here the code**:

```
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      void YellowTimer(){
         setLights(LOW, HIGH, LOW)
         }
      void RedTimer(){
         setLights(HIGH, LOW, LOW)
         }
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}

```

Any help would be greatly appreciated.

# Answer
> 1 votes
You must first declare your timer functions. I have placed them above so they are visible when you call the timer. Also in the loop() you want probably to call timer. I have changed the code to reflect what I told above. I do not have ability to test this, so please try. There may be some syntax errors, but I think you can handle it.

```
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void YellowTimer()
{
    setLights(LOW, HIGH, LOW)
}

void RedTimer()
{
    setLights(HIGH, LOW, LOW)
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}

```

---
Tags: programming, arduino-leonardo, button, time
---


# Question
Title: Assembled redboard PTH kit, when I turn it on the led flashes increasingly fast and stops
I assembled the following sparkfun redboard: **https://www.sparkfun.com/products/retired/10776**

When I plug the board in it start to blink but increasingly fast until the LED stops.

I'm very new to this and not sure what could be the issue or what to look. Any tips on how to debut this?

Here are images of the assembled board:

# Answer
> 1 votes
The board seems to be working. After I plugged in an ftdi connector (adafruit FTDI friend) and uploaded blink to it, it started blinking every second instead of really fast.

The documentation was a bit confusing as it implied that blink was pre-loaded on the device but instead it would just blink extremely fast until it went all the way on and then turn off the green led.

---
Tags: hardware
---


title: Forensic security of Arduino (SRAM)

text:
# Question
Title: Forensic security of Arduino (SRAM)
Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.

Original post: http://forum.arduino.cc/index.php?topic=391698.0

> I get the idea of uploading a "stop" sketch for the purpose of overriding a previously uploaded program in Flash memory space.
>
> Then of course we have EEPROM for "long-term" storage.
>
> However, let's say an Arduino: Read user input as secret key and store in memory (SRAM) Performed a signing operation with secret key Subsequently powered off
>
> We know that computers introduce a wide range of complications to security because data can still be recovered, even after being erased or overwritten in some cases, variables stored in memory float around (unless pinned for decryption in SecureString contexts, etc.), etc.
>
> To establish context for the following questions, let's \[overly\] simplify the attack vector in saying this would be a scenario where an Arduino used in a security application is physically disconnected, stolen, and then powered on sometime later.
>
> Question 1: Obviously we're not talking about storing keys on disk necessarily (i.e. EEPROM). How likely (or difficult) would it be to analyze SRAM with the intent to recover keys that may have been previously stored in memory?
>
> Question 2: Similarly, let's say sensitive information was in fact stored in EEPROM. Does the same hold true of data previously stored in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!

# Answer
RAM memory looses its contents when it's powered off. However, this natural erasure process is not instantaneous: it can take several seconds, or even minutes. It has been demonstrated that cooling down a memory chip can extend its data retention time to *hours*, which enables a type of attack known as cold boot attack.

This type of attack has been studied mostly on DRAM computer modules. The Arduino memory, however, is based on SRAM, which is physically very different from DRAM (a transistor feedback loop vs. a capacitor). There seems to be very little research on cold boot attacks against SRAM. I found nonetheless a technical report from the computer laboratory of the University of Cambridge: Low temperature data remanence in static RAM, by Sergei Skorobogatov. Quoting from the conclusion:

> Contrary to the established wisdom, there are several chips that retain data for dangerous periods of time at temperatures above −20°C. The temperature at which 80% of the data are retained for one minute varies widely between devices. Some require cooling to at least −50°C, while others retain data for this period at room temperature. Retention times can be significantly reduced by shorting VCC to ground rather than by leaving it floating.

From this perspective I would say that, although the attack seems non obvious, your secret key is not completely safe even in SRAM. Since the data retention time varies widely between devices, it could be worth testing on your Arduino. If possible, I would suggest you overwrite the key after the signing operation.

---

**Update**: I did a quick test on my Arduino Uno, at room temperature, by just unplugging and plugging back the board. Here is my test code:

```
// This memory buffer will not be zeroed at startup by the C runtime.
uint8_t __attribute__((section(".noinit"))) buffer[1024];

void setup()
{
    Serial.begin(9600);
    Serial.println(F("Program started."));
}

void loop()
{
    switch (Serial.read()) {
        case 'i':  // Initialize the buffer with pseudo-random bits.
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++)
                buffer[i] = rand();
            Serial.println(F("Buffer initialized."));
            break;
        case 'f':  // Report number of flipped bits.
            int count = 0;
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++) {
                uint8_t mask = buffer[i] ^ rand();
                while (mask) {
                    count += mask & 1;
                    mask >>= 1;
                }
            }
            Serial.print(F("Flipped bits: "));
            Serial.print(count);
            Serial.print(F(" / "));
            Serial.println(8 * sizeof buffer);
    }
}

```

And this is the output, with my comments on the right:

```
Program started.            ← fresh boot
Buffer initialized.         ← pressed 'i'
Program started.            ← pressed the reset button
Flipped bits: 0 / 8192      ← pressed 'f'
Program started.            ← unplugged and plugged back
Flipped bits: 4166 / 8192   ← pressed 'f'

```

It appears the RAM is preserved across a warm reboot (pressing the reset button), but it is completely lost after a power cycle: half the bits flipped is a total loss of information. I tried to do this as fast as I could, which is slightly less than one second. It would seem the SRAM in the ATmega chips decays pretty fast, at least at room temperature.

---

**Update 2**: I found an enlightening story about an unpowered AVR keeping data in RAM for more than 10 minutes, but only on mornings: The mystery of the Zombie RAM.
> 3 votes

# Answer
Uploading a new sketch using the IDE does "page erases" which means that a small sketch will not completely replace a larger one. However using a ICSP programmer starts with a complete flash erase, so that would be more secure. Or you could probably (and it would be better to) upload a new sketch containing mostly random data (eg. a large array in PROGMEM).

Rewriting EEPROM should be pretty secure, especially if you replace the EEPROM with random data, and preferably do it a number of times.

As for SRAM, I would be surprised if you could recover much after a power-off. If the attacker manages to keep the power on that would be different. If possible, write over sensitive data with random bytes as soon as you don't need it any more.

If the data has to stay in RAM, I could envisage a scenario where if I got access to the processor (still powered on) I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.

I think the AVR processors at least would be comparatively safe. After all they don't have disks, virtual memory, or fancy remapping of sectors like a USB stick might.

> Read user input as secret key and store in memory (SRAM) Performed a signing operation with secret key. Subsequently powered off.

Sounds pretty safe once you specify "powered off".

---

https://xkcd.com/538/
> 1 votes

---
Tags: arduino-uno, memory-usage, sram
---


# Question
Title: Regarding use of software serial two times
Can we configure two digital pins as serial pins using software serial library?

# Answer
> 1 votes
Kind of, yes - however you can't use them both at once. SoftwareSerial is blocking. That is, while one port is receiving or sending data the other port will be completely locked out so won't be able to receive anything. So it kind of breaks it in a nasty way.

Personally I never advocate the use of software serial unless there is absolutely no choice whatsoever, and that is something I have never found.

If you need more than one UART then pick a chip with more than one UART.

---
Tags: bluetooth, lcd, gsm
---


title: Bluetooth and another sketch

text:
# Question
Title: Bluetooth and another sketch
I uploaded a bluetooth sketch from IDE (File-\>Examples-\>Firmata-\>Standard Firmata) to Arduino Duo.

Now if I have a sensor attached to this Arduino, I can use bluetooth from another device (Raspberry pi or mobilephone) to read the sensor.

But what if I want to do something in the arduino itself? I see only one option which is to edit the standardfirmata to read the sensor and do something. So multiple sketches running in one sketch.

Am I correct?

# Answer
If you programmed the Arduino to read the sensor and the do something else, what would you do if a second request to read the sensor came in before you had stopped doing something else?

I don't know anything about Firmata. Could you add two sensor's, so the Pi could select to read from sensor 1 or sensor 2? If you could do that then you alter the 'readSensor2()' function so it did 'Something else'. This way you are exploiting any control/synchronisation logic within Firmata. If you need 'readSensor1()' to automatically 'do something else' ever time it was called then couldn't you just tag it onto the end of 'readSensor1()'.
> -1 votes

---
Tags: bluetooth
---


title: Not enough pins on Uno?

text:
# Question
Title: Not enough pins on Uno?
I'm making touch-sensitive, light up tic-tac-toe board.

That means 9 LEDs + 9 capacitive sensors.

Each LED needs 1 pin and each sensor needs 2...meaning I'd need 27 pins to properly control each touch-and-illuminate sequence.

There aren't enough inputs on the Uno for this, so what sort of workarounds should I explore to pull this off?

# Answer
> 5 votes
There are a number of common solutions to "not enough pins".

1. Reduce the number of pins you need. This option is often discarded out of hand, but may be the best. For example, you may be able to reduce the 18 individual pins for the on/off capacitive sensor, with a different part, which may be able to give you an X,Y co-ordinate of where it is touched, with fewer pins.
2. Multiplex the pins. This seems to be the most likely to work in this case - you will use (for example) 9 Uno pins to power the LED and capacitive sensor on each cell, one at a time. So, for example, you might attach D1 to the top left cell, D2 to the top-center, and so forth. Then you use another pin (e.g. D10) to connect to ALL the cathodes of the LEDs (via a single transistor, to protect the Uno from too much current), D11 and D12 to connect to one of the data pins of ALL of the capacitive sensors. So, you "select" cell one, by switching D1 from LOW to HIGH. Then, you put D10 to LOW, so current will from across the LEDs. Read the capacitive sensor, which is now also powered on. Although all of the censors are connected to D11 & D12, only one will be powered on, so you will only be reading that one. Once read, you probably want to delay a few milliseconds, to make sure the light shows up. Then move on to the next cell. Go round and round all cells. The LEDs will be off 8/9ths of the time, but it will still be visible. NOTE: reading more about capacitive sensors, I see that one is input, the other output. You would need a transistor for each of the "select" pins, used as a switch to connect D11 to the correct sensor.
3. Do the same thing, but using a decade counter. Connect 2 pins from the Arduino to the decade counter - one to "count", and one to reset. First, strobe the reset - this will set the first output of the decade counter high - connected to cell 1. Then, when you want to move to the next cell, drop the "count" low, then high again. You are now on the next cell. Repeat until you get to cell 9, then send the "reset" (which guarantees you know where you are up to) to get back to cell 1.
4. Charlieplexing (mostly suitable for output only). This is a somewhat complicated, but very efficient (pin-count wise) way of running lots of LEDs off only a few Arduino pins, by using them in combination. For example, 3 pins could run 6 LEDs - if you have pins A, B and C, run one LED from A to B, one from B to C, and one from C to A; then, run 3 more LEDs in the OPPOSITE direction (don't forget your resistors!). Depending on which LED you want lit, you might want pin A high, B low, and C high impedance (INPUT). 4 pins will get you 12 LEDs, 10 will get you 90 LEDs. If you think this might be useful, check out the Wikipedia
5. Use chips that are designed specifically for the application you need. For example, TLC5940 chips will run up to 16 LEDs each, controlling the brightness of each LED independently. You set the brightness of each LED, then let the TLC5940 take care of the work. SIPO chips such as the 74HC595 (8 outputs) are similar, but only allow "on" or "off" for each pin. Both of these can be "daisy chained" - with the same number of Arduino pins, you can connect the output of one to the input of the next, to control more outputs.
6. Use multiple Arduinos. Yes, this might sound expensive, but you can use an AtMega (e.g. AtMega328, which is the same chip used in the Arduino) for a fraction of the cost. You might even use an AtTiny - even cheaper (but less memory). All of these can run the same code. This is the most flexible, but is also the most work - you would need to think about which chip does what, how they interact, and how they talk to each other. This also has the advantage that, rather than a chip that runs at 16mhz, you can now have multiple chips that each run at that speed, and have more memory each. Some applications work well with one "master" chip controlling one (or more) "slaves", whereas other applications work really well as peer-to-peer, either with each node running the same code, or each doing their own thing, and passing information to other nodes. For this example, you might use one AtTiny85 for each of the 9 cells, with an Arduino to be the master. Or, use an AtTiny84, for each row of 3 cells, with one Arduino to rule them all. The AtTiny84 has 14 pins: power, ground, reset, and 11 data pins - 2 is enough for a shared data bus, such as i2c, leaving 3 pins for each of 3 cells.
7. (not relevant for this example) For multiple on/off sensors (e.g. pushbuttons, switches), you can attach them through different values of resistors, and connect them to an ADC pin as a voltage divider. For example, connect ground via R0 to an analog pin; then connect to the same pin: pin -\> resistor 1 -\> pushbutton 1 -\> +5v; pin -\> resistor 2 -\> pushbutton 2 -\> +5v, and so forth. Build the circuit, and test each combination of switches/pushbuttons on/off, what the output will be. Then, in your code, figure out which combination it is closest to. Each resistor will need to be different resistance. If you only expect one switch to be on at once, it's a lot easier.

# Answer
> 2 votes
7. Shift registers. A single shift register is typically 8 bits, so for nine cells you will need two parallel-in/serial-out (for the sensors) and two serial-in/parallel-out (for the leds). You can chain shift registers together to manage any number of bits, at the price of speed. Each chain of registers needs two pins - data and clock, and the parallel input needs a third pin to latch the data. 5 pins all up, for any number of inputs and outputs. You could even combine the clocks by combining 'read the sensors' and 'refresh the display' as a single operation.

# Answer
> 0 votes
As noted in Paul's comment, you could use NeoPixels instead of ordinary LEDs for the display. Each NeoPixel contains RGB LEDs and a microcontroller that accepts a serial stream of bits in, cleans up the waveform, and passes what it doesn't need on through, to the next NeoPixel. This would reduce the necessary number of pins by 8, since a string of NeoPixels uses one signal pin, independent of the number of NeoPixels in the string.

For the touch-sensitive (capacitive) buttons, rather than two wires per button, you can use one sense wire per button, and one drive wire per set of buttons, thus 10 pins to sense nine buttons, rather than the 18 pins mentioned in the question. A sketch is shown below that samples nine capacitive buttons about 1300 times per second. Here is some sample output from the sketch:

```
At t=2354 button 0 on at level 274  xoooooooo  nr= 3121
At t=2975 button 1 on at level 283  xxooooooo  nr= 3943
At t=3056 button 2 on at level 271  oxxoooooo  nr= 4048
At t=3235 button 3 on at level 280  oooxooooo  nr= 4283
At t=3272 button 4 on at level 278  oooxxoooo  nr= 4331
At t=3418 button 5 on at level 284  ooooxxooo  nr= 4521
At t=3460 button 6 on at level 275  ooooooxoo  nr= 4575
At t=3507 button 7 on at level 278  oooooooxo  nr= 4636
At t=3632 button 8 on at level 290  oooooooxx  nr= 4799

```

Each entry like “level 278” shows the value of a running average of counts for a button; since the program is using 270 as a threshhold value for a button being on, it's reasonable for the numbers to be slightly above 270. (Note, if the call to `secondlyReport()` were uncommented, one would see that the running averages go on up into the 300 to 500 count range when a button is pressed.) The strings of o's and x's show which buttons are on and which are off. The numbers after `nr=` are the number of button readings taken so far.

The program implements smoothing (via a running average with exponential decay), debounce (via “holdoff” counts, as explained in detail in a previous answer), and hysteresis (going from off to on at a high count (270) and from on to off at a lower count (170)).

The program may need tuning to work with a given set of capacitive buttons. The tuning variables used here (such as `ButtonIsOn = 270`, `ButtonIsOff = 170`, `usSettle=60`, `usPreWait=5`, and `nsamp = 40`) work ok with my nine-button setup where each capacitive button is attached to an input pin (like 4,5,...12) and to a 619K resistor (a size I have a number of). The other end of each of those resistors attaches to Uno pin 13. By changing `ButtonIsOn` and `ButtonIsOff`, one should be able to accomodate resistor sizes from a megohm on up to perhaps 4 or 5 megohms.

Note, to install `Streaming.h` (which doesn't increase code size) unzip `Streaming5.zip` from arduiniana.org in your `sketchbook/libraries` directory.

```
/* Via serial port, tell the current time when capacitive readings on
  various digital pins show a button has been "pressed" or "released".
  This version reads buttons using 13 as a drive pin, and two groups
  of pins as capacitive switches: group D = pins 4,5,6,7, group B =
  8,9,10,11,12.  Each of those pins should be connected to the drive
  pin via (eg) a 1M ohm resistor.   JW - April 2016

 See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
 http://www.arduino.cc/en/Reference/PortManipulation and
 http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html
 */
#include <Streaming.h>       // provides nicer syntax for printing
enum { pinsMax = 9 };        // upper size on pins count per sample;
enum { nPortReads = 40 };    // # bit samples saved per reading;
enum { bundleSize = 16 };    // 2^j samples carried in running average
enum { drivePin = 13 };      // # of pin to drive capacitors
enum { ButtonIsOn = 270 };   // button-on level, with hysteresis
enum { ButtonIsOff= 170 };   // button-off level "    "
enum { usSettle = 60 };      // Hold sense pins low this long.
enum { usPreWait = 5 };      // Ignore probably crosstalk this long.
enum { nKeys=9 };        // # of keys in PinSet. Cannot be > pinsMax
#define PinSet "4,5,6,7,8,9,10,11,12"
unsigned int AvCount[nKeys]={0};
unsigned long int nSamples; // # of samples taken
//-----------------------------------------------------------
// Use delta=0 for startup, vs delta=1 for exponential averaging
void makeSample(int delta) {  // Take a sample, add it to AvCount
  byte counts[nKeys], j, nc;
  unsigned int bundle;
  nc = countPins7(drivePin, PinSet, counts);
  for (j=0; j<nc; ++j) {
    bundle = AvCount[j] * (bundleSize-delta);
    AvCount[j] = bundle/bundleSize + counts[j];
  }
  ++nSamples;
}
//-----------------------------------------------------------
void setup() {
  Serial.begin(115200);     // initialize serial port
  nSamples = 0;
  // Initialize AvCount[] with a bundle of samplecounts
  for (byte j=0; j<bundleSize; ++j)
    makeSample(0);      // Add sample directly to total
}
//-----------------------------------------------------------
// portSampler7(): countPins7() calls this routine, which holds
// drivePin and involved pins on current port low for usSettle
// us, then makes them inputs and turns on drivePin.  It waits
// usPreWait us (to weed out crosstalk), then reads the port
// nPortReads times as the pins recharge.
// The set of nPortReads port readings is returned in portReadings.
//
// Inputs:  drivePin, portCode, pinsMask.  Constant nPortReads.
// Output:  array of nPortReads portReadings.
//
// This version takes 8 cycles per reading.  Inputs switch
// on after about one RC time constant.  On a 16MHz Arduino an
// m-count result (that is, a zero bit in m of the nPortReads reads)
// suggests RC is about m/2 us + usPreWait us.

void portSampler7(byte drivePin, byte portCode,
          byte pinsMask, byte *portReadings) {
  volatile byte *pin, *port, *ddr;
  // pin, port, and ddr are pointers to registers with volatile
  // contents: input port, output port, direction register.
  pinMode(drivePin, OUTPUT);
  digitalWrite(drivePin,LOW);
  pin =  portInputRegister (portCode); // eg points to PIND
  port = portOutputRegister(portCode); // eg points to PORTD
  ddr =  portModeRegister  (portCode); // eg points to DDRD
  *port &= ~pinsMask;        // Turn off our pins
  *ddr  |= pinsMask;         // Make our pins be outputs, briefly
  delayMicroseconds(usSettle); // Delay to let pins settle low
  *ddr &= ~pinsMask;         // Make our pins be high-impedance inputs
  digitalWrite(drivePin,HIGH); // Turn on driver pin
  delayMicroseconds(usPreWait);
  for (byte i=0; i<nPortReads; ++i) // Take and store nPortReads readings
    portReadings[i] = *pin;
}
//-----------------------------------------------------------
/* Decode a pins-list into one list per involved port.
   Use portSampler7() to get rise-time counts for each port.

   If pins are spread across k ports, countPins7()  will make
   k calls to portSampler7().  Results are in counts array.
   Note, make pinsMax larger if pinsMax < #(pins in list).

   pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
   etc.  A list may contain digits and commas only.  Pins may be
   listed in any desired order.  Elements of counts[] will be in
   list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
   count for pin 2, counts[1] is the count for pin 3, etc.  A
   larger count implies longer rise time and larger capacitance.
 */
byte countPins7(byte drivePin, char *pinsList, byte *counts) {
  byte pnum, pomask, pocode, potem, i, j, mul;
  byte sampl[nPortReads], pim[pinsMax], pat[pinsMax], bout=0, nat=0, pcon;
  char *c, cc;
  int usedPorts=0;  // To track which ports are done
  for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
    if (*c < '0' || *c > '9') counts[++pcon] = 0;
  // In each pass, group bit numbers by port and sample the port
  while (nat<pcon) { // Each loop pass sets one bit in usedPorts
    pnum = pocode = pomask = bout = pcon = 0;
    c = pinsList;
    while ((cc=*c++)) {  // Loop until c is at end of string
      if ('0' <= cc && '9' >= cc) {
        pnum = 10*pnum + cc - '0';
        if ( *c < '0' || *c > '9') { // See if pin # is complete
          potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
          if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
            if (!pocode)           // If pocode not set, set it
              pocode = digitalPinToPort(pnum);
            if (pocode == potem) {  // Process pin if it's in current port
              pomask |= (pim[bout] = digitalPinToBitMask(pnum));
              pat[bout++] = pcon; // Save location of pin's bit in results
            }
          }
          pnum = 0; // Clear # accumulator
          ++pcon;   // Count pin numbers
        }
      }
    }
    // Now pomask is a mask for all bits to be read from port pocode
    // and we are ready to sample current port.

    // Get nPortReads port readings into sampl array.
    portSampler7(drivePin, pocode, pomask, sampl);
    usedPorts |= 1<<pocode;       // Mark the port finished
    // Count up # of zeroes (ie rise times) in sampled bits
    for (j=0; j<bout; ++j) {
      int count;
      byte m=pim[j];
      for (count=i=0; i<nPortReads; ++i)
        count += sampl[i] & m;
      counts[pat[j]] += nPortReads - count/m; // Return the number of Zeroes
    }
    nat += bout;        // Count number of pins done so far
  }
  return pcon;          // Return # of pins processed
}
//-----------------------------------------------------------
// Measure rise times at designated pins and report
// current running averages of rise times, once per second
void secondlyReport() {
  unsigned int seconds=0, now;
  while (1) {
    now = millis()/1000;
    makeSample(1);      // Add a sample to running average
    if (now > seconds) {    // See if next second started
      Serial << "Counts: ";
      for (byte j=0; j<nKeys; ++j) // Show output
        //for (byte j=1; j<nKeys; j+=2) // Show output
        Serial << AvCount[j] << " ";
      Serial << " t=" << now << " sec." << endl;
    }
    seconds = now;
  }
}
//-----------------------------------------------------------
// Frequently sample rise times on designated pins, to
// find and report capacitive key press times & levels.
void keypressReport() {
  // Old-state and holdoff-count vars
  byte ostate[nKeys] = {0}, holdo[nKeys] = {0}, j, k;
  while (1) {
    makeSample(1);      // Add a sample to running average
    for (k=0; k<nKeys; ++k) {
      if (holdo[k]) {       // Ignore an on button during holdoff
      --holdo[k];
      } else {
    if (AvCount[k] > ButtonIsOn ||
       (AvCount[k] > ButtonIsOff && ostate[k])) {
      if (!ostate[k]) { // Were we off?
            ostate[k] = 1;  // New button press
            holdo[k] = 40; // Start a holdoff period
            Serial << "At t=" << millis() << " button " << k;
            Serial << " on at level " << AvCount[k] << "  ";
            for (j=0; j<nKeys; ++j)
              Serial << (ostate[j]? 'x' : 'o');
            Serial << "  nr= " << nSamples << endl;
          }
          ostate[k] = 1;     // We detected button is on
        } else {
          ostate[k] = 0;     // We detected button is off
        }
      }
    }
  }
}
//-----------------------------------------------------------
void loop() {
  if (0) secondlyReport();
  keypressReport();
}

```

# Answer
> 0 votes
Oh - capacitative sensors. I was fooling about with transistors (BD149s, I think) hooked up into darlington pairs, and I found that just touching the resistor on the base was enough to make them switch. No extra capacitor timing whatsamajig required.

---
Tags: arduino-uno, sensors, led, pins
---


# Question
Title: Why does this method return an unprintable character, how do I convert it to display correctly?
Page 14 says that the method should return the value 'h17'

```
typedef struct  {
  uint8_t data;
  uint8_t timestamp;
  unsigned char crc;
} tData;

int main(void)
{
  unsigned char* tempData = "snap";

    for(;;)
    {
      tData payload;
      payload.crc = crc8(tempData,sizeof(tempData));
      UDR0 = payload.crc;
    }

    return 0;
}

```

# Answer
> 1 votes
Because “h17” is an unprintable character, namely ASCII ETB. The 'h' in “h17” stands for “hexadecimal”, like the `0x` usually used in C.

You should convert the value to an ASCII number if you want to print it, using for example `Serial.print(payload.crc, 16);` or – if you are not using Arduino core – `(s)printf()`.

---

**Edit**: here is an implementation of my comment “*sprintf() into a buffer and dump the buffer to UDR0 one byte at a time*”:

```
#include <stdio.h>

void print_byte_in_hex(uint8_t byte)
{
    // Print the byte in ASCII into an internal buffer.
    char buffer[8];
    sprintf(buffer, "%02x\r\n", byte);

    // Send it one byte at a time through the USART.
    for (char * p = buffer; *p; p++) {
        loop_until_bit_is_set(UCSR0A, UDRE0);
        UDR0 = *p;
    }
}

```

---
Tags: c, terminal
---


title: Bluetooth HC-05 Library for Proteus

text:
# Question
Title: Bluetooth HC-05 Library for Proteus
I m working on a project in which I am using HC04 module so can anyone give me any Arduino Library for Proteus which have HC05 in it. Or tell me how to use HC05 in Proteus.

Thanks.

# Answer
> 0 votes
I have found this Bluetooth Library for Proteus. Thanks for helping me out guys. I am posting it here so that others can also get benefit out of it.

Thanks.

# Answer
> 1 votes
I don't know Proteus, but I think HC05 a bluetooth module? If so, the module interface from HC05 \<==\> arduino is done through Serial (UART) communication. Arduino has built in support for this - you don't need any special libraries besides SoftwareSerial. wire up the module as such:

Then run the following code:

```
#include <SoftwareSerial.h>

#define rxPin 10 // connected to TX pin of HC05
#define txPin 11 // connected to RX pin of HC05

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char bt;

void setup() {
  Serial.begin(9600);
  Serial.println("Hello");

  mySerial.begin(9600);
  mySerial.println("World");
}

void loop(){
  while(mySerial.available()){
    bt = mySerial.read();
    Serial.print(bt);
  }

  while(Serial.available()){
   bt= Serial.read();
   mySerial.print(bt);
  }
}

```

# Answer
> 0 votes
There is no Proteus Library for HC05. (Not one I know of.)

Now, your HC05 is a serial device i.e. it acts as a **Serial monitor**. and fortunately there is **Serial Monitor** in Proteus. You can use that.

Here, Have a look.

P.S. if you are using ISIS 7.x. there is a thing to be noted. You have placed a **serial monitor** and connected to arduino and you started execution and its working fine. Now, what happens sometimes is that when you stop execution and start again, serial monitor might not work. No need to worry about. Stop execution, delete that serial monitor and place a new.That will work.

---
Tags: programming
---


title: Send newline through serial monitor

text:
# Question
Title: Send newline through serial monitor
I know I can send a newline using the option in the bottom right:

But why doesnt it work to use the option 'No line ending', and send a '\n' or '\r\n' after the text using the arduino serial monitor?

# Answer
> 2 votes
The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers. It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.

"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return. I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"

---
Tags: serial
---


# Question
Title: How do I connect a vibration sensor/switch to a breadboard?
I have the following vibration sensor:

It has one short/firm-er terminal and one long/flimsy terminal. Now the shorter terminal slides easily into my breadboard but the flimsy one clearly does not. A few related questions:

1) How do I go about connecting this to my breadboard (simply plugging it in doesn't work)? Do I have to solder a wire onto the flimsy end?

2) Why is this switch manufactured this way (with a flimsy end)?

3) Is it right to assume that the longer end is positive (+) and the shorter end is negative (-)?

Thanks!

# Answer
> 1 votes
It appears from this information source: http://www.electrodragon.com/product/vibration-switch-sensor-sw-18020p/ that the sensor is an electrical contact on the firmer side surrounded by a very sensitive spring within the enclosure. The coil spring is by design made of a smaller diameter wire to provide sensitivity to movement. Rather than manufacture a translation to a heavier piece of material, the thinner lead is brought out of the enclosure.

I suspect that it will not work on your breadboard, due to the flimsy end being too small to make solid contact within the breadboard. You could resolve that aspect by soldering on a heavier segment.

Because it is designed as a simple switch, there is no plus or minus.

---
Tags: sensors
---


# Question
Title: No sketches will upload to Arduino Uno board; says "access denied"
I'm using an Arduino Uno board with an HP computer running Windows 10 and IDE version 1.6.8. Arduino was working fine for me until a few days ago, when (and I suspect this is the root of the problem) I accidentally tried to upload software with something connected to the RX and TX pins on the board. Now I continually get the error message below:

> avrdude: ser\_open(): can't open device "\\.\COM2": Access is denied.

The only other thing that changed is I disconnected a bluetooth dongle (Kinivo BTD-400 Bluetooth 4.0 USB Adapter for Windows) without uninstalling any software, so I suspect that software may be searching for open COM ports and disrupting the Arduino upload.

I've tried everything I could find about troubleshooting online, including that "did I brick my arduino" post elsewhere on this forum, and nothing has worked or even changed the problem - please help! I believe I've narrowed down the problem to my computer scanning open COM ports, but I can't find any reliable way to make sure that doesn't happen.

Thanks

# Answer
It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.
> 1 votes

---
Tags: arduino-uno, port-mapping
---


# Question
Title: Removing Element From Array While Keeping Order
I'm building a wireless mechanical keyboard. There is an array of 6 elements that stores the keys pressed by the user (since 6 is the max number of keys you can send at once over Bluetooth). An example would be `02-05-03-00-00-00`. Notice the "00" at the end, these are just "placeholders" and don't have a meaning other than to indicate that there are no more keys pressed. When the user releases key 05 for example, the array should become this `02-03-00-00-00-00`. I don't know how to do this however, since you can't just remove and item from an array and there doesn't seem to be a polished option for lists in Arduino.

Does anyone have any idea for an algorithm that finds the 0's in an array, places them at the end of the array and keeps the order of the other elements?

# Answer
> 0 votes
You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:

```
void setup()
{
  Serial.begin(57600);
  while (!Serial);

  char vec[] = { 2, 5, 3, 0, 0, 1 };
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));

  vec[1] = 0;
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));
}

void loop()
{
}

void compact(char* vec, size_t len)
{
  int i = 0;
  for (; i < len && vec[i] != 0; i++);
  if (i == len) return;
  int j = i;
  for (; i < len; i++) {
    char c = vec[i];
    if (c != 0) {
      vec[j++] = c;
      vec[i] = 0;
    }
  }
}

void print(char* vec, size_t len)
{
  for (int i = 0; i < len; i++) {
    unsigned c = vec[i];
    if (c < 16) Serial.print(0);
    Serial.print(c, HEX);
    if (i + 1 < len) Serial.print('-');
  }
  Serial.println();
}

```

This give the following output:

```
02-05-03-00-00-01
02-05-03-01-00-00
02-00-03-01-00-00
02-03-01-00-00-00

```

Cheers!

# Answer
> 0 votes
**Remove Zeros**

```
void removeZeros(uint8_t array[], size_t length) {
// Sanity check.
if(array != nullptr && length > 0) {
    for(size_t i = 0; i < length; i++) {
      if(array[i] == 0) {
        for(size_t j = i + 1; j < length; j++){
          if(array[j] != 0) {
            array[i] = array[j];
            array[j] = 0;
            break;
          }
        }
      }
    }
  }
}

```

Usage:

```
uint8_t keyBuffer[] = { 2, 0, 3, 0, 4, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0]);

```

New value of keyBuffer: { 2, 3, 4, 0, 0, 0 }

**Remove a single indexed value**

```
void removeIndex(uint8_t array[], size_t length, size_t index){
  // Sanity check.
  if(array != nullptr && length > 0) {
    for(size_t i = index; i < (length - 1); i++){
      array[i] = array[i + 1];
    }
    array[length-1] = 0;
  }
}

```

Usage:

```
uint8_t keyBuffer[] = { 2, 5, 3, 0, 0, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0], 1);

```

New value of keyBuffer: { 2, 3, 0, 0, 0, 0 }

---
Tags: arduino-ide, c, array
---


title: Join Serial Data Seperated by Newlines?

text:
# Question
Title: Join Serial Data Seperated by Newlines?
I have two Arduinos connected through Bluetooth. One sends a string of data similar to `506:507:1\r\n`. The data can vary similar to `0:1000:0\r\n`. I already have functions to break that string down into three variables. I send it from one Arduino over Bluetooth and the second Arduino receives it through `Serial`. The only problem is that the second Arduino receives this:

```
5
0
6
:
5
0
7
:
1
"\n"

```

At the end it adds a space at the end (`"\n"`) How can I parse this data back into a string similar to `506:507:1\r\n` that can still vary in length?

# Answer
> 1 votes
Simply reverse the steps you took on the sending side.

* Create a `char` array of sufficient size as well as an index variable to keep track of your position within the array. An Arduino String may be more convenient, though they can cause **a lot** of problems.
* In a loop, use `available()` to wait for incoming chars and add them to the array you've created, using your index variable.
* Keep going in the loop, while checking for that unique character (\n, perhaps) that signals the end of a packet. Add this last byte to the array and then terminate the string with null or `\0`.

If you want to re-use the array for another packet, simply set the index variable to 0 and continue.

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


title: radio wave generation using arduino

text:
# Question
Title: radio wave generation using arduino
```
const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

```

It is just toggling the mode of the pin, so how it is related to radio wave generation?

# Answer
This looks incredibly like the post on my page: Turn your Arduino into an AM radio transmitter!

As the page mentions:

> The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

These are the important lines:

```
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)

```

Timer 1 is set up to run at 800 kHz. That is a radio frequency. The toggling code just turns the output on or off as a simple form of "keying".
> 0 votes

---
Tags: arduino-uno, rf
---


# Question
Title: I²C only works when I short-circuit my Arduino
I'm trying to connect an Arduino Nano with a Raspberry Pi 3 via I²C.

This is the small test-program I found and used for I²C.

```
#include <Arduino.h>
#include <Wire.h>

void setup() {
  Wire.begin(4);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

```

After compiling and uploading, I ssh-ed into my Pi and executed `sudo i2cdetect -y 1` which prints an empty I²C table.

Here are images of how I connected the two devices, as far as I know the connection itself is okay. I also tested the cables with a multimeter.

Now the strange thing is, when I short-circuit my Arduino for a brief moment between GND and VIN I²C works, but Serial via USB with my PC stops working. Also the chip gets very hot and stays hot even though it isn't short-circuited anymore.

Any ideas what I'm doing wrong? I don't think the Arduinos are broken, since I tested it with 2 different ones. (while testing I accidentally short-circuited one and it worked)

EDIT: I tested I²C between the two Arduinos and it works flawlessly, but still doesn't want to work with my Pi. :(

# Answer
> 3 votes
> Any ideas what I'm doing wrong?

Apart from *deliberately shorting +5V to ground*? Sheesh!

---

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

---

> You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".

`Wire.begin()` enables the pull-ups. So make sure that *on the Nano side* you disable them again:

```
  Wire.begin (4);
  // disable internal pullups for twi.
  digitalWrite(SDA, LOW);
  digitalWrite(SCL, LOW);

```

# Answer
> 0 votes
There is not enough information in your question to know for sure, but remember that the rpi is three volt and the arduino is five volt. Given the heat you are seeing you have something miswired.

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


# Question
Title: 4-digit 7 Segment LED displaying numbers in the wrong order
I am a novice Arduino programmer and am currently having trouble with a SH5461AS 4-digit/7-segment LED when using it with an Arduino Uno. I have struggled to find an accurate datasheet/tutorial of any kind for this particular model (It is the LED without the colons in between digits 2 and 3) but I believe I have it figured out.

I currently have it going through a HC595 shift register but when I removed the register and connected the LED directly to the board the problem remained. My code below is with the shift register; I am displaying it this way because it is simpler to view and I thought it would make it easier to debug.

I can display a single digit at a time correctly. However, when I try to display 2+ digits at one time, they are in the incorrect order. For example, I can count 1-9 on the first digit, then 1-9 on the 2nd digit, and so on and everything displays correctly (other digits are off). But as soon as I try to display multiple digits they are in the wrong order. So if I try to display 12\__ with the last 2 digits off, 21\__ is displayed with the last two digits off. If I try to display *23*, *32* is displayed. If I try to display 1234, 4123 is displayed.

I am at a loss because the code seems like it should be simple.

```
const int DATA = 0;
const int LATCH = 1;
const int CLOCK = 2;

const int DIGIT_ONE = 3;
const int DIGIT_TWO = 4;
const int DIGIT_THREE = 5;
const int DIGIT_FOUR = 6;

//digits[0-9] corresponds to the patterns for numbers 0 -> 9.
//Add 1 to the digits[X] to turn on the dot.
byte digits[] = {B11111100, B00011000, B01101110, B00111110, B10011010, B10110110, B11110010, B00011100, B11111110, B10111110};

void setup() {
  pinMode(DATA, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(LATCH, OUTPUT);

  pinMode(DIGIT_ONE, OUTPUT);
  pinMode(DIGIT_TWO, OUTPUT);
  pinMode(DIGIT_THREE, OUTPUT);
  pinMode(DIGIT_FOUR, OUTPUT);

  digitalWrite(DIGIT_ONE, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);
  digitalWrite(DIGIT_FOUR, HIGH);
}

void loop() {
  writeDigit(DIGIT_TWO, 2);
  writeDigit(DIGIT_THREE, 3);
}

/*
 * Write a digit to the 4-digit 7-segment LED
 * - digitPin corresponding to the pin on the LED to light up the correct digit.
 * - number 0-9 to display on the LED
 */
void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

```

So in this instance, I am expecting *23* but *32* is displaying instead.

I am also having trouble with some bleeding (I don't know what the correct term is) where some segments are very faintly glowing even though I am not doing it intentionally. This is a much smaller issue, however, than digits randomly in the wrong order.

If it would help, I can try to post the circuit diagram as well.

# Answer
> 3 votes
Here is a datasheet I found that seems a better macth for your display model (that's the datasheet for a display that I use):

http://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom%2Fupload%2FFile-1356269320.pdf

This is the datasheet I directly got from my local supplier.

According to what you say, the problem does not seem to be a wiring problem.

It looks more like a **timing** issue:

```
void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

```

The first issue when you call `writeDigit()` is that it forces the cathod low **BEFORE** having set the shift register, so the digit will first show the current register value, i.e. the one from the previous call to `writeDigit()`.

Then it pushes the new value for the segments on the shift register, that will be fast but not as fast as two consecutive calls to `loop()`.

If we try to roll and expand the `loop()` call in your example that will be:

```
// First call: writeDigit(DIGIT_TWO, 2)
  digitalWrite(DIGIT_TWO, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);

// Second call: writeDigit(DIGIT_THREE, 3)
  digitalWrite(DIGIT_THREE, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);

```

The calls to `loop()` and `writeDigit()` are negligible in terms of timing here.

In the sequence above, most of the time is spent in:

```
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);

```

So that means your function will:

1. show the previous value on the new digit for `t1 us`
2. show the new value of the new digit for `t2 us`

with `t1 >> t2`, hence your eyes will see the opposite of your intent!

To fix that issue you definitely need to introduce some delay to reverse what your eyes will see:

```
void writeDigit(int digitPin, int number) {
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(digitPin, LOW);
  delayMicroseconds(100);
  digitalWrite(digitPin, HIGH);
}

```

In the code above:

* no digit shows while the shift register is set
* the requested digit shows immediately after the shift registry has been written and lacthed, and for a duration of 100us, which will be much longer than the rest of the time.

That code should also get rid of the "bleeding" you observed.

# Answer
> 1 votes
I found the data sheet here:

https://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AK2B-35.pdf.

It's a horrible bit of writing. Not at all clear.

It looks like it's multiplexed. You use pins 14, 16, 13, 3, 5, 11, 15, and 7 as the cathodes for the segments on a digit (ground the pins for the segments you want to light.) Pin 7 appears to be the decimal place for a given digit.

One of the pins 1, 2, 6, or 8 should be fed a +5V to light a particular digit.

The other pins control the colons and other dots on the display. Let's ignore those.

To light the display here's what I THINK you would do (I'm tired, and didn't study the data sheet that closely, so I may may be wrong here)

For pins 14, 16, 13, 3, 5, 11, 15, and 7: These are the cathodes for the segments in the current digit you are driving. Set the pins you want to light as digital outputs, LOW. Set the others as inputs, which will make them essentially open circuits. The selected pins will be grounded, and the ones set as inputs will not be connected to anything.

Pull pin 1 HIGH to light the selected segments in digit 1. Put it back low, set the segment pins, then pull pin 2 HIGH to light that digit. Repeat, pulling pins 6 and 8 high to light the selected segments in digits 3 and 4.

You'd have to cycle rapidly through the digits, lighting 1 at a time, in order to make them appear all lit at once.

Get that working first without using shift registers. (It will take 11 I/O lines to drive all 4 digits and their decimal places - 1 less if you don't care about the decimal place.)

I think that if your drive all the pins using a shift register then some of the unlit segments will be fed reverse voltage. (When set as an output, sending a LOW connects the output pin to ground, and setting it high drives it to 5V. With all the control pins driven from outputs of a shift register, the off segments will have 5 volts on them, and the off digit select pins will have ground on them.)

# Answer
> 1 votes
I don't have enough reputation to add a comment, but the datasheet link in @jfpoilpret is dead. This link has the datasheet from the same website.

Thanks.

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


# Question
Title: Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible
Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground. I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?

EDIT :

I found this somewhere, on a board that might be the one driving this LCD screen or not :

Operating Voltage VDD -0.3 to +7.0 V Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3

So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?

Thanks for your input :)

# Answer
> 1 votes
For me, it's extremely hard to tell if you did or did not fry a device. Even if you have the device right in front of you, it's often hard to tell.

You've got two options:

**Attempt to diagnose it**

First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.

If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.

**Buy a new one**

This will cost you some money. But if you get the new one working, you can test the same code on your old one.

**Tips**

1. First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
2. Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
3. Check the devices datasheets (which pins, what maximal voltage)
4. Try to use female connectors as power-output. (They don't short everything they touch)
5. Try to use irreversible connectors.
6. Don't have loose leads dangling around.
7. Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
8. Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.

---
Tags: lcd
---


title: "missing filename" compilation Error

text:
# Question
Title: "missing filename" compilation Error
I've recently got back to my Uno. I tried compiling my program and got the following error:

```
Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"

avr-g++: error: missing filename after '-o'

exit status 1
Error compiling.

```

This happens on any of the programs I've tried to compile/upload. I've searched around on Google but I have gotten no definite answers and how to fix this or what has caused this? Does anyone have an idea on what I could do?

# Answer
I had same problem. You should download Arduino IDE 1.6.8

https://www.arduino.cc/en/Main/Software
> 1 votes

---
Tags: arduino-ide, compile
---


# Question
Title: How to load Atmega328p 8mhz board using board manager
I need to load the Atmega328p 8kHz board definition using the board manager and can not find a way. Any help will be appreciated.

# Answer
**Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator:**

In the Arduino IDE click on `Tools`.
Scroll down until you see an option starting with the word `Board:`
Select the option called `Arduino Pro or Pro Mini`

Click the `Tools` menu once again.
This time select the option starting with `Processor:`
Select the `Atmega328P (3.3V, 8MHz)`
Done!

Alternatively you can edit the `boards.txt` file located somewhere similar to `C:\Program Files (x86)\Arduino\hardware\arduino\avr`
Fuse bits can be calculated using one of these online tools:
> 1 votes

---
Tags: atmega328
---


# Question
Title: Arduino UNO doesn't produce expected square waveform
I want to produce quick square waveform for testing purposes. If I will use this code:

```
void setup()
{
 pinMode(2, OUTPUT);
}

void loop()
{
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
}

```

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.

I use latest Arduino 1.6.9 environment.

Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.

Any idea what I'm doing wrong?

Same results if I use asm sbi and sci instead of macros bitSet/bitClear.

Thank you!

/\*

So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:

```
void setup()
{
 pinMode(2, OUTPUT);
 noInterrupts();
}

void loop()
{
 while(true)
 {
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
 }
}

```

# Answer
As I explained in my comment, the reason for this glitch is the Timer 0 overflow interrupt kicking in every 1024 µs. This interrupt is used by the Arduino core library for timekeeping. It is the basis of `millis()`, `micros()` and `delay()`. The interrupt is enabled by the `init()` function in wiring.c. There are several approaches to avoid that:

## Avoid the Arduino core initialization

This may be overkill, but since it seems you are already familiar with directly accessing the IO ports of the ATmega chip, it may well suit you. You can use the Arduino IDE without the Arduino core initialization simply by defining your own `main()`:

```
#include <util/delay.h>

int main(void)
{
    DDRD |= _BV(PD2);        // PD2 as output
    for (;;) {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
        _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
    }
}

```

Notice the extra delay: without it, the loop would complete in 6 CPU cycles (2 per port access, 2 more to loop back). Not doing the Arduino core initialization means you have no timekeeping and no `analogRead()` or `analogWrite()`. Other Arduino functions should work normally but some, like `Serial.begin()` will bring their own interrupts.

## Disable interrupts

As suggested by Majenko, this may be the simplest way to have a steady waveform:

```
void setup()
{
    pinMode(2, OUTPUT);
    noInterrupts();
}

void loop()
{
    PORTD |= _BV(PD2);   // PD2 high
    PORTD &= ~_BV(PD2);  // PD2 low
}

```

Without interrupts, you have no timekeeping, no serial communications and, obviously, no `attachInterrupt()`. Most other Arduino functions should work.

## Use a hardware timer

This allows you to generate the signal without relying on the CPU. You can keep interrupts enabled and do other work in the program while the waveform goes undisturbed. The simplest way to generate such a waveform is with `analogWrite()`. The resulting frequency is quite low though, like 0.5 to 1 kHz. If you want 1 MHz, you will have to configure the timer the hard way. For example:

```
void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 as output
    OCR2A = 15;           // period = 16 clock cycles
    OCR2B = 1;            // high during 2 clock cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS20);   // clock at f_CPU
}

void loop() { }

```

The output is on pin PD3 = digital 3. This configuration will disable `analogWrite()` on pins 3 (PD3) and 11 (PB3).
> 3 votes

# Answer
> I want to produce quick square waveform for testing purposes.
>
> Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal. Any idea what I'm doing wrong?

You are assuming that what goes on outside loop() and the call to loop() takes no time at all.

This is what the Arduino core main() looks like.

```
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

There is both the call to loop(), if-branch, and for-branch. This all adds up. On top of this there are a number of Interrupt Service Routines (ISR) such as for the Timer which is used for the micros() and millis() count. These will interleave periodically (as you have observed).

Now the question is how to fix this and I think @Edgar Bonet has done an excellent job with that.

Cheers!
> 1 votes

# Answer
If you just want a rough square wave to test and you don't care about the frequency then try this:

```
void setup()
{
   pinMode(2, OUTPUT);
}

void loop()
{
   digitalWrite(2, true);
   delay(2);
   digitalWrite(2, false);
   delay(2);
}

```
> 1 votes

---
Tags: arduino-uno
---