title: Imbedded loops based on inputs

text:
# Question
Title: Imbedded loops based on inputs
I'm working on a project with 4 inputs and 7 possible outputs on an Arduino Uno. Based on any combination of those inputs, I need to run a specific "loop" that will repeat until there is a change in ANY of the 4 inputs. Specifically:

* Input 1 = loop 1
* Input 2 = loop 2
* Input 3 = loop 3
* Input 4 = loop 4
* Input 2 and 3 = loop 5
* Input 2 and 4 = loop 6
* No input = do nothing

So I need to constantly read the 4 inputs and change output loops accordingly. I have basic Arduino knowledge but am stumped.

This is what I've tried - I have 4 input pins and 8 output pins

```
int outPin = 0;
int inPin = 0;
int CAR = 0;
int pinRead = 0;

void setup()
{
 for (int outPin = 3; outPin < 11; outPin++);  {  //set pins 3 thru 10 as OUTPUT
   pinMode(outPin, OUTPUT);
  }

 for (int inPin = 9; inPin < 13; inPin++);  {    //set pins 9 thru 12 as INPUT
   pinMode(inPin, INPUT);
  }

}

void loop()
{
  for (int CAR = 3; CAR <11; CAR++); {  //set all pins to LOW
   digitalWrite(CAR, LOW);
  }

  // BRAKE

    {while (digitalRead(9 == HIGH) && digitalRead(10 == LOW) && digitalRead (11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(10, HIGH);

  }}

  // LEFT

    {while (digitalRead(9 == LOW) && digitalRead(10 == HIGH) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(3, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    delay (200);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    delay (200);

  // RIGHT

  }}

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == HIGH) && digitalRead(12 == LOW)) {
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(4, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);

  // HAZARD

  }}

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == LOW) && digitalRead(12 == HIGH)) {
    digitalWrite(0, HIGH);
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
    delay (200);

      for (int CAR = 0; CAR < 8; CAR++); {  //set all pins to LOW
       digitalWrite(CAR, LOW);
    delay (200);}}

  // BRAKELEFT

  }

    {while ( digitalRead(9 == HIGH) && digitalRead(10 == HIGH) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(3, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    delay (200);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    delay (200);
    }
  }

  // BRAKERIGHT

    {while (digitalRead(9 == HIGH) && digitalRead(10 == LOW) && digitalRead(11 == HIGH) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(4, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
    }
  }

  // NOTHING

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {

       for (int CAR = 0; CAR < 8; CAR++); {  //set all pins to LOW
         digitalWrite(CAR, LOW); }}
    }
}

```

# Answer
> 2 votes
When you need repeating behaviour in an Arduino program, putting loops within the `loop()` function often isn't the best approach. It leads to a lot of confusing logic which is quite hard to get right, and becomes quite unwieldy to maintain.

A more effective approach would be something like a simple state machine. At the start of `loop()` you would check the input values and figure out which behaviour (or state) you want to execute: BRAKE, LEFT, RIGHT etc.. You might want to store this information in a variable somewhere, e.g. state `0` could be BRAKE, state `1` could be LEFT, and so on.

Next, you simply check what the state value is, and execute the appropriate instructions **once**. For example:

```
switch (state)
{
    case 0:
        // BRAKE instructions here...
        break;

    case 1:
        // LEFT instructions here...
        break;

    // etc...
}

```

There's no need for any `while` loops because `loop()` is going to get called all the time anyway. There are two big advantages of this approach. First, you only need all the input conditions in one place, which makes the code easier to manage. And second, it means you can easily have your program doing other things later in `loop()` because it's no longer stuck in nested loops all the time.

---

As a side note, it's very important to mention that lines like this are incorrect:

```
digitalRead(9 == HIGH)

```

What you're doing here is comparing the number `9` to `HIGH`, and then passing the result (which is 0) to the `digitalRead()` function. That means you're effectively only ever checking pin 0. What you actually want to do is pass `9` to the function, and then compare the overall result to `HIGH`, like this:

```
digitalRead(9) == HIGH

```

---
Tags: arduino-uno
---


# Question
Title: Bluetooth shield/module for file transfer?
I'm currently working on a project that requires to display images on a touchscreen on my arduino. These images are neither stored in arduino nor any memory card. I want to be able to send the images via Bluetooth from an app and display it on the touchscreen. The problem is I couldn't find a good and solid Bluetooth shield or module that provide file transfer via bluetooth from an iOS app to arduino. If you can name a few bluetooh shields or modules that'd be great. In the thread below, someone claimed hc-05 works. Can anyone support that claim? Thanks. http://forum.arduino.cc/index.php?topic=208306.0

# Answer
> 1 votes
I would use an HC-05 (or HC-06 - there seems to be little difference) - You will need to do your own file transfer protocol - for small images, zmodem or xmodem (usual file-over-serial) are probably completely overly complex. You would also need your own app for the phone.

Alternatively, you could use a network (ethernet or wifi) addon on your arduino - I think I read the Arduino Yun has built in ethernet and wifi.http://arduino.cc/en/Tutorial/WebServer has a webserver, this could be adapted to accept uploaded files. You can then use a webbrowser on your phone (or indeed anywhere else!) to send the files. If you want to send from outside your local network, you may need to set up port forwarding on your router (google: port forward) - the port you want to forwards is 80.

---
Tags: bluetooth
---


title: In system programming for avr?

text:
# Question
Title: In system programming for avr?
I generally use sockets for AVRs in standalone circuits, but sometimes I sell my items and therefore I soldier the chip on the circuit. As you guess I can upgrade the code inside the chip with socket simply putting the chip out and putting it into the programmer board, but It doesn't work the same way with the ones which are soldiered on the circuit.

I know there are some ISP devices like USBtinyISP etc., but I want to be more professional and know exactly how an in system programmer work.

Do I have to use Avrdude If I design my own In system programmer? Isn't there any way that is more universal?

I searched the internet for a long time and I found only hobbyist stuff. Can anyone explain or simply direct me to a good source that explains this topic? Thank you in advance.

# Answer
> 1 votes
ISP works by using a serial connection (usually via the SPI and nRESET pins) to the MCU. The programmer talks to the device using the low-level protocol that the device expects, and connects to the host using a different, high-level protocol. The host then directs the programmer to perform the various programming actions on the device, and in turn the programmer reports to the host about its current status.

There are a number of programming protocols that already exist, such as the one described in AVR910. As long as both the connection type and the protocol itself are supported by AVRDUDE it will work transparently once the hardware is assembled.

Further details about ISP are available in both AVR910 as well as the "Serial Programming" section of the datasheet for the device in question.

# Answer
> 0 votes
You can use an ISP using the Arduino UI - simply select your programmer (tools-\>programmer) then "upload using programmer" (under the file menu).

Alternatively, you could use a pre-programmed AVR to do the programming - see http://www.atmel.com/images/doc0943.pdf for the spec. I think an AtTiny would be enough, depending on how big your program is, you might need some external storage. You could set it up with a "read" and a "write" option, so you program your dev AVR normally, then use an AtTiny to suck the data off, then push it up to one of the others. This is left as an exercise to the reader.

In any case, you would just need access to the 6 pins - VCC(power), GND(ground), RST(reset), SCK(clock), MISO(master-\>slave) and MOSI (slave-\>master). Note that the RST pin has to go high/low at specific times during the programming, so if programming from another AVR, it will need to be a data pin.

---
Tags: avr, avrdude, isp
---


title: Why are pin 18 and 19 always HIGH?

text:
# Question
Title: Why are pin 18 and 19 always HIGH?
I wired my switch just like in the default button program. I know it works because it works fine on other pins, just not pin 18 or 19. What am I doing wrong?

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

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

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

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

# Answer
> 6 votes
The analog pins function as digital pins number 14 - 19, with 14 being A0 and 19 being A5. I had hooked it up backwards.

```
This time we're gonna get funky
Everybody check your pins
Check check check check your pins
Check check check check your pins

```

---
Tags: arduino-uno, button, digital
---


# Question
Title: Can stackable Arduino headers be automatically soldered?
I want to design an Arduino shield with stackable headers, so it will allow other shields to be mounted on top of it.

I was wondering if these could be soldered automatically. Neither wave nor reflow soldering seems to be an option. Wave soldering would leave solder on the pins so they won't fit in sockets, and for reflow (pin-in-paste) the long pins will completely pull the paste from the holes. Is hand-soldering the only way (making the board more expensive), or is there still another way? Would it be a good idea to supply the shield with the headers not mounted to save cost? Or shouldn't I assume the average Arduino user has a soldering iron?

# Answer
I would suggest using SMD headers on one side and through hole on the other side. One side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/partdetails.aspx?Class=ASSMANN&ClsID=/F\_ASSMANN/ASSMANN.010/ASSMANN.010.170/&PartID=10-18062010-079808 and one side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/PartDetails.aspx?Class=ASSMANN&clsid=/F\_ASSMANN/ASSMANN.010/ASSMANN.010.170/&ManID=ASSMANN&PartFamilyID=10-23062010-067691&PartID=10-23062010-067691&SrchRsltId=1&SrchRsltType=0

You will shift upper side a few mm from bottom side, and use glue to have upper side set in place and then reflow for soldering on both sides.
> 1 votes

# Answer
You might look at getting a solder stencil. It is still hand soldering, but significantly faster than doing it completely by hand. Another option would be a pick and place machine; there would be a significant upfront cost but it would be more automatic.
> 0 votes

---
Tags: shields
---


# Question
Title: Why does a Piezo Buzzer not require a PWM digital pin (Gallileo Gen2)?
According to my current (poor) understanding, only the PWM pins (with the ~) among the digital pins (ignoring Analog pins) can be passed to `analogWrite()`. I understand the servo therefore - since interfaced by a variable voltage signal - must be connected to such a PWM pin.

* Why is the humble Piezo Buzzer not bound to this condition?
* Why can I connect the buzzer to a digital pin that is not PWM (and so should only be able to output binary LOW, HIGH voltage at some consistent frequency) and still achieve a varying sound by calls to the `tone()` function?
* Surely under the limitations of being digital and non-PWM, the pin could only cause some consistent buzzer frequency?

I'm reading online that the Piezeo Buzzer does indeed require a PWM digital pin, but I can connect it to any digital pin on my Galileo gen2 and have it function seemingly correctly (differing tones produced).

Also, since slightly relevant; what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

# Answer
> 4 votes
> Why does a Piezo Buzzer not require a PWM digital pin?

Tone() uses the microcontroller's hardware timers to control the related code function but do not use the hardware PWM features. The timer can be assigned to any pin that has a digital output capability.
Tone() sends a "rail to rail" square wave (50% duty cycle) to the selected pin

Slightly more lower level information here under **Ugly details**
They say:

* The library uses the hardware timers on the microcontroller to generate square-wave tones in the audible range.

You can output the tones on any pin (arbitrary). The number of tones that can be played simultaneously depends on the number of hardware timers (with CTC capability) available on the microcontroller.

ATmega8: 2 (timers 2, and 1)
ATmega168/328: 3 (timers 2, 1, and 0)
ATmega1280: 6 (timers 2, 3, 4, 5, 1, 0)

The timer order given above is the order in which the timers are allocated. Timer 0 is a sensitive timer on the Arduino since it provides millis() and PWM functionality.

---

> ... what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

There is a misconception there.
Analog pins are capable of Analog INPUT functionality .
"PWM" output is known as "analogWrite" but is actually a purely digital function and is not related to whether a pin has analog read functionality.
PWM out = analogWrite is available on pins which have associated PWM hardware.
The actual signal is a "rail to rail" square wave with a mark:space (on:off)that varies. Filtering the PWM produces DC at the average DC level. PWM range is 0 to 255 (8 bits)

# Answer
> 0 votes
The signals that you mention are of different nature.

1) The PWM signal is a digital signal (output voltage is either ground or supply) that is modulated in time. It has a fixed period and its duty cycle varies from 0% (always ground) for value 0, to 100% (always supply) for value 255, the middle value being a signal that switches between ground and supply with 50% of its period at ground and 50% of its period at supply.

2) A servo is controlled by a signal that has a fixed period of 20 ms and a pulse of varying duration (between 0.5 to 2.5 ms).

3) A tone for a buzzer has a variable period (or variable frequency - both being linked by the equation frequency * period = 1). The period is audible if is is between 0.06 ms (15 kHz) and 60 ms (15 Hz) (the exact value change from person to person. If the frequency is higher than 15 kHz, you are entering ultra-sonic.

All three signals are digital in their voltage and modulated in time. But the modulation is very different as indicated above and the Arduino driver is therefore different for each one.

---
Tags: pins, pwm, analogwrite
---


title: How do I use this sound sensor?

text:
# Question
Title: How do I use this sound sensor?
I bought one of these:

There are 3 pins on it:

* 5V
* GND
* OUT

My guess is that OUT is an analogue signal that I can measure with my Arduino, am I right?

I am using the "Analogue Output" example code but I just get 5V all the time, it does not seems to change with the sound levels.

Am I doing something wrong? What am I adjusting with the blue square on the board? Should I maybe do that?

# Answer
> 3 votes
The wording on this particular eBay item is pretty poor but there are plenty of similar products with better descriptions that are photographically identical... example that make a little bit more sense.

Anyway, I don't think this gives an analog value output, the LM393 is a comparator, so I think the blue dial sets the 'threshold level' and any sounds over that level cause a logic low. i.e. it compares the audio level and the dial and when one exceeds the other it gives a signal.

The features also say "The output effective signal is low level" which is probably Chinglish for the signal is a logic low, i.e. when the sound is heard it goes to 0V rather than 5V which is what I think you were expecting.

In summary: This device is is more like a Clapper, it detects a loud noise and sends a digital low signal.

Try making a loud noise with the same setup you already have, and if not try adjusting the potentiometer by turning it, but not too far! It probably only turns 180-270º.

---
Tags: sensors
---


# Question
Title: Arduino UNO serial send and receive issue
I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?

# Answer
> 1 votes
You need a common ground between the Arduino and the PIC. Connect both grounds one to each other.

# Answer
> 1 votes
Is the Arduino running at all when on battery? You could be trying to pull too much current from the battery and killing the circuit. Another cause is that some programmers pull the reset pin to low when unplugged; took me a while to figure out that one.

---
Tags: serial
---


# Question
Title: Using MULTIPLE shields on Arduino Uno R3
I'm very new to using Arduino! I'll be using Ocean Controls KTA 259 thermocouple multiplexing shield AND a Sparkfun microSD shield on my UNO--to log temperature data for a study I'm doing. The KTA 259 has a library and the integral SD library should work for the SD shield.
Q1: I believe they *physically* connect no problem, but how can I be sure there are no pin conflicts, disastrous or otherwise? In other words--what conditions **MUST** I avoid using shields and multiple shields?
Q2: Can (or must) a single data pin be used by both shields, eg from thermo as output to SD as input, or does Arduino juggle all that? Q3: Can (or must) a single function, eg CS, be mapped onto the same pin on BOTH shields, or do they have to be separate allowing Arduino to handle that? Thank you; I appreciate the help!

# Answer
> 2 votes
You will have to consult a source like this one: http://shieldlist.org There are no simple rules for which pin conflicts are OK and which ones are not, it all depends on the concrete protocol (i.e. I2C is designed for all bus participants to share lines, while in SPI, each participant needs their own select line, while the other lines are shared).

In your concrete case, both shields you want to use are addressed by SPI, which means D13 (SCK) and D12 (MISO) are shared between the shields by design, while they MUST have different slave select pins. In your case, the SS pin for the microSD shield is fixed as D8, while the one for the KTA shield seems to be selectable, so either D9 or D10 should be OK.

Peripherals generally don't have facilities to become an SPI master, so all data has to be transferred through the Arduino.

# Answer
> 1 votes
I have used these ***exact* two shields** myself and can confirm they definitely work together. I can find my datalogger code to confirm if desired.

# Answer
> 0 votes
Q1: If its a well established source of Arduino compatible boards you can be pretty confident (in my experience) that there are no design flaws regarding pin use. A search on comments by other developers will also help confirm that for you further.

When you go to multiple shields you would need to look at fanout (driving more than one input from an output). The reverse problem is even more of an issue: driving one input from several outputs. In other words, an input on the Arduino would be connected to output pins on two shields providing different signals.

Q2: The answer relates to how I ended in Q1. By avoiding the use of certain pins on a shield the conflicting inputs could be avoided. The headers would simply pass through the signal. I don't think there is any rule that a shield has to use or touch every pin.

Q3: I'm not quite sure what you are asking in this question.

---
Tags: shields
---


title: Reading many analog signals in arduino

text:
# Question
Title: Reading many analog signals in arduino
I need to measure around **50 - 100 analog sensors** (resistors). This poses two challenges:

1. Arduino has fewer analog pins. I'm targeting something small like arduino Mini or Nano, which can have up to 8 analog pins. The solution for this could be several multiplexors like this one. **Is there a better option?** Is this the best way to read so many analog sensors with Arduino? I am thinking also in several arduino mini talking through wifi / bluetooth with the main one which would also aid with Problem #2.
2. There would be **a lot of cables** for this setup, and I need to keep it all as flat and flexible as possible. So I was thinking of some kind of adesive copper conductor, paper printed circuit or plastic. The thing is that it would become difficult to create if I do it myself. What would be the easiest way to achieve a multi-track, flexible circuit for substituing Arduino cables?

# Answer
Your question doesn't specify speed, cost, accuracy, or size, and it skimps on electrical and physical details (referring merely to 50–100 resistors and “a lot of cables”) so perhaps can't be properly answered.

ADC's (analog-digital converters) typically are high-impedance devices that measure voltages. A resistor may be measured in many ways, a few of which are:

* Place a known voltage across it; measure current through it
* Drive a known current through it; measure voltage across it
* Drive some current through it; measure both voltage and current using four-terminal sensing
* Measure how long it takes a given capacitor to charge to a trip point, using a known voltage through the resistor under test
* Use known resistances to null a Kelvin bridge

For some of the techniques listed above, measurement accuracy is little affected by multiplexer resistance; others might need to use a low-resistance MUX made with relays instead of a MUX ic like the 74HC4067. Some of the techniques are suitable for wide ranges of resistance, others not; and some for high accuracy, others not.

## Suggested Approach

Anyhow, those comments aside, circuits like the following might do the job. If you have eight analog inputs on your Arduino, you could use up to eight multiplexers to measure up to 128 resistors.

In Figures 1 and 2 above, **Rx** is a typical unknown resistance, and **Rs** is a known standard resistor. Both figures represent *voltage divider* circuits.

## Effect of multiplexer transmission gate resistance

Let **Rm** denote multiplexer transmission gate resistance. **Rm** is unimportant if the circuit of Figure 1 is used because **Rm** is tiny compared to the input impedance of a unity-gain follower op amp stage.

**Rm** might or might not be important if the circuit of Figure 2 is used. (a) If **Rm** differs somewhat from one multiplexer channel to another, Figure 2 may be unsuitable because calibration will be cumbersome. (b) If **Rm** is comparable to **Rx**, Figure 2 is unlikely to produce high-accuracy results.

## Whether unity-gain followers are necessary

Whether you need unity-gain followers depends mostly on the size of resistors you are measuring. Arduino analog inputs are high-impedance (10⁸Ω, but with about 14pF capacitance to **Vcc**/2). Atmel suggests analog source impedances of 10KΩ or less for best results. \[See (,,) for additional discussion.\] Briefly: If **Rs**+**Rx** is likely to exceed 20-40KΩ and you wish to measure quickly, use unity-gain followers.

## Resistance Formulas

Let **Vt** be the voltage at the lower end of **Rs** in either figure. **Vt** is the voltage that will be measured at an analog input Aj.

In Figure 1, because **Vt = Vcc·Rx/(Rx+Rs)**, we have **Rx** = **Vt·Rs/(Vcc-Vt)**.

For the circuit in Figure 2, an additional resistance **Rm** is in series with **Rx**, so **Vt = Vcc·(Rx+Rm)/(Rx+Rm+Rs)**, whence **Rx = Vt·Rs/(Vcc-Vt)-Rm**. If **Rs** and **Rx** are large (eg 40KΩ and 10KΩ) then ignoring **Rm** may cause only a fraction of a percent of error. But if **Rm** is comparable to either of **Rs** or **Rx**, either use the circuit of Figure 1 or devote some inputs of each multiplexer to use as calibration inputs.

## Analog input reference voltage

If **Vcc** is 5 V and we choose **Rs** four times as large as the largest resistance value that you intend to measure, then **Vt** will be between 0 and 1 V. You can use an `analogReference()` call like `analogReference(INTERNAL)` \[or `analogReference(INTERNAL1V1)` on a Mega\] to set the analog reference voltage at 1.1 V, to maximize accuracy of measurement and to minimize the amount of current required through **Rx**.

## Advantages of Figure 2

Unless **Rm** is a problem (as discussed above) the following advantages of Figure 2 suggest its use:

* Lower power requirements: In Figure 1, all the resistors under test always have current going through them. In Figure 2, only 1/16 of the resistors are powered at any given time. Also, by raising \EN to shut down the 4067's (or 74HC4067's if used) all the resistors can be powered off.
* Less wiring and fewer parts: At most eight **Rs** parts are needed, rather than one **Rs** per **Rx**. Each **Rx** connects to ground and to one mux input, rather than to ground and to the junction of a mux input with an **Rs**.

## Cable Note

For either figure, seven or eight wires run from the Arduino to each 4067 subcircuit. One wire from each subcircuit carries Vt back to an analog input. The other wires connect to all subcircuits in parallel: four channel select lines (A, B, C, D in figures, or S0-S4 in datasheets); Vcc; ground; and \EN unless that line is wired to ground. Each 4067 subcircuit should have a bypass capacitor, eg 10-100 nF, from Vcc to ground. Boards like the “Geeetech CD74HC4067 Analog Digital MUX Breakout Board” shown below (about $5 on ebay) might be used, or you could design a custom board and have it made at OSHPark or Seeedstudio.
> 2 votes

# Answer
As I read your question I was thinking of the 4067 chip as part of the solution.

You'd rig one 4067 as the anode and another as the cathode on a grid of 64 resistors. You'd then send select an anode channel and a cathode channel, feed +5 volts into the common for the anode channel, and then feed the common from the anode channel into an ADC input on your Arduino. You'd need to allow for the fact that those chips have an internal resistance of around 180 ohms, (at least the TI chip I looked up did. My CMOS cookbook lists 200 ohms resistance.) As long as you're measuring resistances that are substantially bigger than 400 ohms, that should work (or you could precisely measure the resistance of your 4067 chips at your operating temperature and then adjust your math to compensate.)

Mind you you'd have to sample these resistances one at a time, in round-robin fashion. It would be kinda slow.

If you want to test more than 64 resistances, you could use 2 4067s on either the anode side or the cathode side and use the inhibit pin to select the chip. That would give you the ability to sample 128 resistances.

I did find some 8 and 16-channel serial ADCs. You could use those and some select logic to do the same thing. Take a look at the AD7490. That's a 16 channel serial ADC. That and one of the 4067 16-channel MUX chips would give you 64 ADC inputs in banks of 16.
> 0 votes

---
Tags: pins, analogread
---


title: what is the use of "<<=" operator?

text:
# Question
Title: what is the use of "<<=" operator?
I recently read this piece of code and I dont know what is the use of "\<\<=" in the for loop:

```
for (mask = 0x01; mask>0; mask <<= 1) {
    if (data & mask){ // choose bit

```

This is the entire code:

```
//Created August 23 2006
//Heather Dewey-Hagborg
//http://www.arduino.cc

#include <ctype.h>

#define bit9600Delay 100
#define halfBit9600Delay 500
#define bit4800Delay 188
#define halfBit4800Delay 94

byte rx = 6;
byte tx = 7;
byte SWval;

void setup() {
  pinMode(rx,INPUT);
  pinMode(tx,OUTPUT);
  digitalWrite(tx,HIGH);
  delay(2);
  digitalWrite(13,HIGH); //turn on debugging LED
  SWprint('h');  //debugging hello
  SWprint('i');
  SWprint(10); //carriage return
}

void SWprint(int data)
{
  byte mask;
  //startbit
  digitalWrite(tx,LOW);
  delayMicroseconds(bit9600Delay);
  for (mask = 0x01; mask>0; mask <<= 1) {
    if (data & mask){ // choose bit
     digitalWrite(tx,HIGH); // send 1
    }
    else{
     digitalWrite(tx,LOW); // send 0
    }
    delayMicroseconds(bit9600Delay);
  }
  //stop bit
  digitalWrite(tx, HIGH);
  delayMicroseconds(bit9600Delay);
}

int SWread()
{
  byte val = 0;
  while (digitalRead(rx));
  //wait for start bit
  if (digitalRead(rx) == LOW) {
    delayMicroseconds(halfBit9600Delay);
    for (int offset = 0; offset < 8; offset++) {
     delayMicroseconds(bit9600Delay);
     val |= digitalRead(rx) << offset;
    }
    //wait for stop bit + extra
    delayMicroseconds(bit9600Delay);
    delayMicroseconds(bit9600Delay);
    return val;
  }
}

void loop()
{
    SWval = SWread();
    SWprint(toupper(SWval));
}

```

# Answer
As stated in the other answers, the `<<=` operator shifts the byte to the left; however, the number '1' after it specifies how far to shift it - so, `2 <<= 2` == 8. Possibly clearer in binary:

`00000001 <<= 1` == `00000010`

`00000010 <<= 1` == `00000100`

`00000001 <<= 2` == `00000100`
> 4 votes

# Answer
In simpler terms `mask <<= 1` is shorthand for `mask = mask << 1`

In general

```
variable operator= operand

```

is the augmented assignment operator which means

```
variable = variable operator operand

```
> 7 votes

# Answer
`<<` is the left bit-shift operator. That means it takes the binary contents of a number and moves everything left by a certain number of binary places (1 place in this case). `<<=` simply combines the left bit-shift with an assignment, so it takes the current value of `mask`, shifts it left, and then stores the result back in `mask`.

In this situation, the `mask` variable starts with a value of `1`. The second time round the loop, it will be `10` (binary). Next time, it will be `100`, and so on. Since `mask` is a byte (which is 8 bits), it will go all the way up to `10000000` and then stop. After that, the 1 effectively falls-off the left and `mask` ends up with a value of 0.

The purpose of this in the code you provided is to test each individual bit within the `data` parameter. It basically goes through from least- to most-significant and checks if each bit is 1 or 0. It will then pull an output pin HIGH or LOW (respectively) to match. This allows it to send the contents of the variable digitally to some other device.

Doing low-level binary (aka bit-wise) operations like this is very common in microcontroller programming. If you're not familiar with it then I'd definitely recommend looking up some tutorials online. It opens up a huge range of new possibilities for your projects.
> 4 votes

---
Tags: serial
---


# Question
Title: US-100 Ultrasound sensor doesn't work on Arduino mega 2560
Im using a Arduino Mega 2560, and I tried to connect a us-100 ultrasonic sensor for distance measurement.

I connected it as shown in the image

The code I used was:

```
const int trigger=6;
const int echo=7;
float distance;
void setup(){
Serial.begin(9600);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
}
void loop(){
// Trigger US-100 to start measurement
// Set up trigger
digitalWrite(trigger,LOW);
delayMicroseconds(5);
// Start Measurement
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
// Acquire and convert to mtrs
distance=pulseIn(echo,HIGH);
distance=distance*0.0001657;
// send result to UART
Serial.println(distance);
delay(50);
}

```

But It won't work, as in the only output i get is 0.00 cm as shown in the image

Can someone tell me if I'm doing something wrong(also, i tried putting two probes between the vcc and one of the gnd pins, and a resistance was shown.This should mean the sensor isn't broken.yes?)? this is my first time using arduino and I greatly appreciate help to fix this.

# Answer
Have you removed the "Serial Data Mode" shunt to put the device in "Pulse Width Mode"?

On the other hand, perhaps the "Serial Data Mode" would actually work better for your application?

Where I work, we have a coding style that strongly encourages all "magic numbers" to be documented with a link to the website it came from or a reference to the book and page it came from.

Would something like this work for you?:

```
void loop(){
    // Trigger US-100 to start measurement
    // at least 50 us high, then set it low,
    // as recommended by
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    digitalWrite(trigger,HIGH);
    delayMicroseconds(50);
    digitalWrite(trigger,LOW);
    // Acquire
    unsigned long echo_microseconds = pulseIn(echo,HIGH);
    // debugging
    serial.println( echo_microseconds );
    Serial.println(F(" microseconds"));
    // conversion factor from
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    unsigned long distance_mm = echo_microseconds * 34 / 100 / 2;
    Serial.print(distance_mm);
    Serial.println(F(" mm"));
    delay(50);
}

```

It might be easier to use the Ping library as described at Arduino-Info: UltraSonic Distance Measurement.

You might find the Arduino Forum: Measuring Distances with Ultrasonic Sensors thread educational.
> 0 votes

---
Tags: arduino-mega, sensors
---


# Question
Title: Has anyone used an Arduino to transfer software to an Apple IIe?
Yes, you read that right. An `Apple IIe`.

I have many retro computers and I was thinking that since the `Apple II` line of computers (especially the `IIe`) have pretty speedy serial ports that it should be somewhat simple to use an Arduino to send data to/from the Apple.

My issue is that all of my every-day computers are USB based with no RS232 serial. I guess I could boot up an old Linux laptop that has a serial port but that seems too cumbersome given my limited desk space. :-)

Anyway, I've Googled but I'm not finding anything.

Since most `Apple IIe` disk images are pretty small (\<144k or so) they should fit pretty easily into, say, an Arduino DUE that I have. Or better yet, using the DUE to mount as a USB device that could send over to the IIe would be great.

So, my question is, does anyone know of any site that explains how this could be done?

Thanks!

**EDIT**

OK, turns out it WAS pretty easy getting the Arduino DUE to send to the Apple IIe. I simply connected 3 wires from TX1/TR1/GND to the Apple IIe serial port (SSC).

Now, when I launch ADT Pro and start sending, the IIe is receiving garbage. Bunch of "9d9d9d9d" all over the place.

Here's my code:

```
// ADT.ino

int incomingByte = 0;

void setup() {

    Serial.begin(9600);
    Serial1.begin(9600);

}

void loop() {

    if(Serial.available() > 0) {

        while(Serial.available() > 0) {

            incomingByte = Serial.read();

        }

        Serial1.write(incomingByte);
        delay(100);
    }

}

```

The ADT Pro software is set to send the data over the USB port and it's obviously sending data to the IIe. I'm just wondering if the formatting is wrong or something.

# Answer
You need to adapt the levels. Arduino Due operates on 0 - 3.3 V. Apple IIe is either on 0 - 5 V or +/- 12 V (depends which port you are using). There are standard ICs to do the level adaptation.
> 2 votes

---
Tags: serial, arduino-due
---


# Question
Title: I2C LCD Serial Interface Board not displaying text (wrong pins?)
I have a 1602 LCD screen that works fine on its own. However I wanted to free some pins by using an I2C / IIC LCD controller I purchased separately.

While the controller seems to be communicating with my Arduino UNO on the right address, I cannot get text to display. By default (no code) it seems the LCD will have 1 line of 16 solid "squares". When using address 27 in my code, the LCD will change to 2 lines of 16 squares (see photo below). The code also calls for the backlight to flash 3 times, which works. However I cannot get anything but 2 lines of squares. (Full code is at the bottom of this question).

I'm using the LiquidCrystal\_I2C library by F Malpartida, which seems to be commonly used.
Is there a better library I should be using?

I'm wondering whether it's just the wrong pins being used in the code. All sketches I see online use the following pins:

```
//                    addr,en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Set the LCD I2C address

```

But all of the 1602 LCDs I see online have the same pins as mine, as you can see in my photo below:

These pins seem to be standard:

To further confuse me, the pins on the LCD board start with 1 on the left, yet the default code's pins seem to start with 0! So I tried changing the code's pins to the numbers on the LCD board. The LCD no longer changes to 2 lines of squares and no longer blinks the backlight. I then tried subtracting 1 from each pin (to start from 0), same result. I then tried used the default pins minus 1, same result. Thus the default pins are somehow more correct?! What am I doing wrong?

Has anyone else gotten one of these I2C controllers to work for them, and if so, how?

Full code:

```
/* YourDuino.com Example Software Sketch
 16 character 2 line I2C Display
 Backpack Interface labelled "YwRobot Arduino LCM1602 IIC V1"
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here:
// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
#include <LiquidCrystal_I2C.h>

/*-----( Declare objects )-----*/
// set the LCD address to 0x27 for a 20 chars 2 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);  // Used to type in characters
  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------
  for(int i = 0; i< 3; i++) {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.setCursor(0,0); //Start at character 4 on line 0
  lcd.print("Hello, world!");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("HI!YourDuino.com");
  delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
  lcd.clear();
  lcd.setCursor(0,0); //Start at character 0 on line 0
  lcd.print("Use Serial Mon");
  lcd.setCursor(0,1);
  lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  {
    // 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());
      }
    }
  }

}/* --(end main loop )-- */

```

# Answer
> 3 votes
First of all, it looks like these wires aren't properly connected:

>

I haven't disassembled a female jumper before, so that might not be the issue. However, it seems likely that this could be a cause.

Also, you **need** to adjust the contrast by turning that trimmer (the blue thing that looks kinda like it has a screw in it). LCDs will either display nothing, a washed out version of the text, or blue boxes if the contrast is not set correctly. This is probably the cause.

# Answer
> 3 votes
I bought the SainSmart 20x04 and I also had to change the address to `0x3F`. My backlight jumper was missing, that little header at the right of the I2C board provides the backlight power. Some code I found included this:

```
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);

```

# Answer
> -1 votes
Change this code:

```
LiquidCrystal_I2C lcd(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

```

To this:

```
LiquidCrystal_I2C lcd(0x26, 2, 1, 0, 4, 5, 6, 7, 8, POSITIVE);

```

(The argument before "POSITIVE" is changed from a 3 to an 8)

---
Tags: i2c, lcd
---


title: I2C RTC returning bad times - sometimes

text:
# Question
Title: I2C RTC returning bad times - sometimes
I have a TinyRTC I2C clock in one of my Arduino projects, and it works most of the time. But occasionally, it will report the time as 165 hours, 85 minutes and 25 seconds (165:85:25) for a couple of seconds, then go back to the correct time.

I think this has got something to do with a fairly complicated I2C bus that I'm running: it has 12 devices connected to it (the clock, an LCD and 10 BlinkM LED programmable lights).

Here's what I've tried to debug, to no avail:

* Replaced the RTC and battery
* Replaced I2C pullup resistors
* Redid the I2C wiring
* Checked current draw of my project (.2A) and made sure the power supply can handle that (it can)
* Used 3 different power supplies in case I was getting noise

I think this is something to do with the I2C bus... the clock works fine when nothing much else is happening on the bus, but as soon as there's lots of activity (LEDs being sent messages, or perhaps other things) it starts reporting the time as 165:85:25).

Any idea how I could (a) isolate the cause of this problem; (b) get right to implementing a solution?

# Answer
Such intermittent issue looks to me a hardware signal integrity problem, specifically around the I2C bus RTC chip. Did you experience any problem from any other device on the same I2C bus (e.g. when all the LEDs are on)? If not, then check on the noise level on RTC chip power and GND. Also, the I2C spec has limit on the bus capacitance load as max as 400 pF. When there are too many I2C device loads on the same bus, the bus may become vulnerable to the system noise.

Debug Suggestion: To narrow down if it is I2C load issue, add an I2C bus driver chip between the main Arduino board and your peripheral. For example, P82B96 from TI. See the spec here. http://www.ti.com/lit/ds/symlink/p82b96.pdf
> 1 votes

---
Tags: i2c, time
---


# Question
Title: Set Arduino digitalRead reference voltage
I wanted to know if the reference voltage for the `digitalRead()` function could be set to a particular voltage, either with an external reference or internally.

In the Arduino reference under the constants heading they have mentioned that they use 3V as reference for the boards I'm using (an Arduino Uno R3). But I want to change it to be a little lower.

Is it possible and if so how?

# Answer
> 6 votes
You could try not `digitalRead`, but `analogReadVoltage`. Analog Read Voltage

From Arduino examples:

```
/*
  ReadAnalogVoltage
  Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

 This example code is in the public domain.
 */

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}

```

# Answer
> 1 votes
for a 5 volt Arduino anything over 2.7V will be considered as a digital HIGH whereas anything below 0.4V will be a digital LOW.

---
Tags: arduino-uno, voltage-level
---


# Question
Title: How to access multiple SPI interfaces on Arduino
I have worked on SPI devices connected with an Arduino one at a time. How do I work with two different SPI devices at the same time?

# Answer
Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.

When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.

There are some devils in the detail using multiple slaves, and these are explained in more depth here, but in general, it's quite common and OK to use more than one SPI device as a slave.

This blog post will give you more information and is a good place to start reading.
> 24 votes

---
Tags: sd-card, spi
---


# Question
Title: Plugged in shield off by one, now all analogues read high
I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.

Now though A0-A5 are all reading high values (~900-1000 when I do `analogRead(A0)`), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.

The digital writes all work perfectly.

I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?

# Answer
> 2 votes
There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.

If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.

Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?

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


# Question
Title: RFID system for proximity detection with data logging
I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., \<= 1 meter). Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.

My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated. (Please keep in mind that I am not an engineer!)

I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system. For beta-testing, this device could be set in an enclosed case and attached to a belt. I presume it would require a fairly robust battery supply. The other person would be wearing an RFID tag that has a range of \<= 1 meter and would log the event. Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.

Here are a few other things to keep in mind:

1. The people using the hardware should not have to do anything other than simply wear the constructed devices.
2. The reader itself should be as small as possible.
3. My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).

Thanks in advance! Brian

# Answer
> 1 votes
Consider using two basic XXMhz transceivers:

```
-Master loops through used ID's and transmits them one at a time.
-If a belt receives an ID other than it's own, it remains quiet.
-If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
-For a receiver to hear the very quiet signal, it will need to be very close.
-The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
-If sufficient proximity is detected, the event is reported to the Master.
-If it receives no response, it informs the Master.
-Master proceeds to the next ID.

```

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)

So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.

If ID is only 7 bits, the "protocol" could be as simple as a bitmask:

```
Server = Send(ID &  (1 << 7)); //1XXXXXXX
  Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

```

Belts only reply to their ID if MSB is 1

This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data. http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html

```
Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

```

Neither is 100%, but both should work.

# Answer
> 0 votes
This is a cheapo 125khz reader from Seeed Studio (Shenzhen): http://www.seeedstudio.com/wiki/index.php?title=Electronic\_brick\_-\_125Khz\_RFID\_Card\_Reader

The range on it is very limited and I'm not suggesting you buy that specific one. Instead, just notice the pinout, +,-,TX,RX. You will find many, many readers with that same pinout. When a tag is detected, the reader blindly transmits the ID via UART (serial). You will also find many WiFi modules with similar TX/RX pins.

In your situation, the Arduino is actually wasteful since it's only purpose will be to mirror the reader's data from it's RX to it's TX. It's better to cut out the middle-man and just connect the (voltage-compatible) reader directly to the WiFi module to save power.

Many wireless modules are capable of automatically going low-power when there is nothing to do. Part of the receiver circuit will activate for transmitting, but since you are only transmitting sporadically from the belts, neither the receiver or transmitter needs to be powered constantly. I think you will be pleasantly surprised by the battery life.

---
Tags: rfid, datalogging
---


# Question
Title: Arduino mini requires uploading on every power up?
My Arduino mini is experiencing some really strange problem.

I'm using the BlinkWithoutDelay example sketch for testing:

```
const int ledPin =  13;
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
        ledState = HIGH;
    else
        ledState = LOW;

   // set the LED with the ledState of the variable:
   digitalWrite(ledPin, ledState);
  }
}

```

The program basically turns pin 13 on and off every 1000ms.

When I uploaded this sketch into the mini (via Arduino Uno board, sans Atmega chip), the scope reading of pin 13 shows nice square waves (1s pulsewidth, 2s period), as expected.

I then unplug the USB cable powering the mini through the Uno board, wait for a few seconds for the scope traces to settle (I only have an old analog one at hand), and then plug it back in to turn on the board. However, the pin output is different - I now get a train of three pulses (60ms wide, 60ms between pulses) at sporadic intervals.

Uploading the sketch then yields the desired square waves again.

What is going on here? I'm fairly sure the mini has nonvolatile memory and it's intact (otherwise the bootloader through which I upload the sketch would not work).

# Answer
> 1 votes
There was a defective bootloader that shipped on some Arduino devices which caused the symptom you describe. See:

http://forum.arduino.cc/index.php?topic=51172.0

http://forum.arduino.cc/index.php?topic=74090.0

If that's the case, your options are to re-write the bootloader yourself (if you have the capability) or return to the manufacturer.

---
Tags: bootloader
---


title: How do I write a debugger for Arduino?

text:
# Question
Title: How do I write a debugger for Arduino?
I want to write my own debugger.

I've found Visual Micro plugin for Visual Studio provides Arduino Debug.

So, does anyone have ideas how it works?

I just desire make the same plugin in Eclipse IDE.

# Answer
Assuming you have enough time and money to spend on this project. ($50 is a bargain for a debugger, believe me. About a decade ago I wrote an assembler/debugger suite for a very small niche market microcontroller, the Maxim Integrated MAX1464, using a combination of SciTe and Perl/Tk. Writing your own debugger is a great educational project, if you have the time and money to complete it.)

**Tools**

Assuming you already have all the standard Arduino debug tools, and just want to learn the process of making a debug tool.

Assuming you've used the standard Arduino debug tools before, and written enough programs (sorry, you Arduino guys call them "sketches" for some reason) so that you have some code you feel comfortable debugging on. Setting a breakpoint in a simple "blinking LED" program isn't very satisfying, better to set breakpoints in a test program that actually does something. You'll also want to have some branching logic pathways to test breakpoints, and some variables (counters perhaps) so you can test reading values through the debug interface.

Assuming you have a couple of spare Arduino boards, because very likely during development some bad debug commands may get sent. Ideally you should have a device programmer capable of restoring the Arduino bootloader image that normally resides in the Atmel AVR processor. Sending arbitrary commands to the debug interface could possibly erase or mess up the bootloader.

Assuming you have access to customary EE lab tools: DMM, oscilloscope, soldering iron, etc.

**Research**

Assuming you already know how to make an Eclipse IDE plugin... (if you don't, that would be a question to research on Google or StackOverflow.) I'm treating this the same as if you were writing a plain command-line debugger or a gdb driver.

I'm not really sure which debug protocol you need to implement. Sadly, `JTAG` doesn't seem to be supported by Arduino. The `ICSP` in-circuit system programming header might give debug access, though it would require attaching some hardware to the board that you're debugging. If I understand correctly, the Arduino IDE supports debugging through the USB port, which is a very attractive setup.

Assuming you plan to use Atmel's proprietary `DebugWIRE` protocol, which someone else has kindly attempted to reverse-engineer here: http://www.ruemohr.org/docs/debugwire.html Ideally you'd get the real documentation from Atmel. The hazard of a reverse-engineered protocol like this (aside from possible IP infringement) is that the protocol could change without notice. Not having direct access to the team that designed the microcontroller, means you have to rely on whatever documentation you can find and whatever else you can discover experimentally.

Assuming you can use the USB bridge chip's `DTR#` to drive (and possibly sense) the RESET pin, to access DebugWire. If that USB bridge chip is an FTDIchip.com device, you'll want to use the bit-banging mode to drive and sense DTR#. (In normal "RS232 mode" this pin is not bidirectional.) Go to the FTDIchip.com website to get the D2XX programmer's guide and example code.

Since DebugWire is a protocol that uses one wire for all signalling, both directions, timing is absolutely critical. **You must use an oscilloscope** to observe the DebugWire signals on the RESET pin, otherwise you're "flying blind".

That should be enough to get you started. Initially, you'll have to figure out how to discover an attached Arduino, enter debug mode, set a breakpoint, and reset the part back into free-running mode. The "blinking LED" test program is good enough to see some results for this early stage.

Cheers
> 4 votes

---
Tags: debugging
---


title: Serial.read() vs. Serial.readBytes()?

text:
# Question
Title: Serial.read() vs. Serial.readBytes()?
I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.

For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1. Basically I construct some byte arrays as instructions, send them over to the servo (with `Serial1.write()`), and then read back a reply. I've actually gotten it to work pretty well if I use `Serial1.readBytes()`, specifying the length of the buffer (number of bytes I'm expecting). I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).

However I don't understand the difference between `Serial.readBytes()` and `Serial.read()`. If I do `Serial.read()` just prior to `Serial.readBytes()`, it comes back with -1, meaning no bytes to read... but then `Serial.readBytes()` gives me the byte stream I was expecting from the buffer! What's going on here?

Similarly, `Serial.available()` seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with `Serial.readBytes()`. Additionally, I can do `Serial.readBytes()` after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.

I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless. Any clues about the difference in how these operate would be much appreciated!

# Answer
readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.

Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.

This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).

```
    #define TIMEOUT = 3000;
    loop {
        char inData[20];
        unsigned long timeout = millis() + TIMEOUT;
        uint8_t inIndex = 0;
        while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
            if (Serial1.available() > 0) {
                // read the incoming byte:
                inData[inIndex] = Serial.read();
                if ((c == '\n') || (c == '\r')) {
                    break;
                }
                Serial.write(inData[inIndex++]);
            }
        }
    }

```

Above code was quickly written and untested. But gets the idea across.
> 6 votes

---
Tags: serial, arduino-mega
---


title: WORDS in ATmega328 datasheet note

text:
# Question
Title: WORDS in ATmega328 datasheet note
I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.

It is the (8) note in pg.296-297 of this datasheet: what does WORDS mean in that context?

# Answer
The notation is being used to indicate that the 16-bit address (as formed by the central bytes of a Write Program Memory Page instruction) is the address of a program-memory *word*, rather than a program-memory *byte*.

The size of program memory is specified in bytes, but it often is addressed as words. For example, the PC (program counter) register contains word addresses.

For some instructions, when the Z register is used to address program memory, it contains a word number and a byte selector:

> The Z-register in the Register File is used to access the Program memory. This 16 bits register pair is used as a 16 bits pointer to the Program memory. The 15 most significant bits selects the word address in Program memory. Because of this, the word address is multiplied by two before it is put in the Z-register. ... The least significant bit of the Z Address Register selects either Low byte (0) or High byte(1) of the Program memory word. — AVR108: Setup and Use of the LPM Instruction, page 1

*Note:* Some of the low bits of the word address in a “Write Program memory page” serial programming instruction are treated as don't-cares. The number of don't-care bits depends on flash page size, which in Atmel AVR devices is 32, 64 or 128 words, depending on device series.

For example (as shown in Table 129 on page 304 of doc2467.pdf) the ATmega128 with 128-word (256-byte) flash pages has seven don't-care bits in the low byte of the address.

```
Table 129. SPI Serial Programming Instruction Set
                 -----------Instruction Format----------
 Instruction       Byte 1    Byte 2    Byte 3    Byte 4    Operation

Write Program    0100 1100 aaaa aaaa bxxx xxxx xxxx xxxx
Memory Page                                              Write Program Memory
                                                         Page at address a:b.

```
> 2 votes

# Answer
**See jwpat7's answer.**
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes. While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

A Byte is most usually used to refer to an 8 bit quantity.

A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.

In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.

However, the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "**Address Word**"is formed by the MSB + LSB combination.
> 3 votes

---
Tags: atmega328
---


# Question
Title: Make a PC graphical interface for Arduino - Any easy software?
What's the best/easiest software to make a PC-Arduino interface? Ideally, I need to create a .exe that shows up a simple graphic interface, where the user can display data acquired from sensors connected to the Arduino (eg. Voltage, current etc.) and from there he should be able to control Arduino outputs through graphical buttons/switches.

To say that I am not a programmer, so if there's some sort of 'graphical coding' or 'non coding' software to make such things it'd be great!

Thanks for your help!!!

UPDATE:

Image of how the user interface should look like:

# Answer
The "best" software for me is the free Visual Studio Express for Desktops.

Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components\>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.

To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:

```
XXXYYYZZ
Where:
XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
//Pin number does not have to match the MCU port/pin designations
//MCU will convert logical pin #'s 0-7 into the correct physical port+pin
//For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

00100100b = "Set pin 1 high"
01001000b = "Toggle pin 2"
10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

```

Additional commands can be created to tell the Arduino to reply with a specific variable or status.

```
bool isRegisterRead = false;
bool isMultiByte = false;
while (true)
 if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
  if (isMultiByte) //Second byte received
  {
    if (isRegisterRead)
    {
      //We need to read and send the value of the register at the address in byteReceived
      ReadAndSendRegisterValueAtAddress(byteReceived);
      isRegisterRead = false;
    }
    else DoSomethingWith(byteReceived);
    isMultiByte = false; //Start over
  }
  else //First or only byte received
  {
    //Consider using a ZZ bit to indicate more data instead of listing them explicitly
    if (byteReceived == 0x80) //A multi-byte "read register" command
    {
      isMultiByte = true; //Next byte received is money
      //For my example we need to set a flag somewhere to indicate that we are reading a register
      //isRegisterRead should be set to true by DoSomethingWith
    }
    //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
    DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
  }

```
> 3 votes

# Answer
Almost impossible to answer really. Questions with "best" are always going to yield opinions which probably won't apply to your situation. For example, I would do a C# desktop application because that's what I do, and nothing in that environment hinders communication with an Arduino. So, what's best for me is best because of "familiar and will work" and we can't decide what meets those criteria for you.

If you will update your question to describe more about your application, details about your interface, users, and what skills you have, then I will update this answer, but as it stands "the world is your oyster" because almost any programming environment capable of making an application will be able to interface with Arduino in some way.

For "graphical" programming look into LabView - I can think of a lot of reasons to not go that way though. http://www.ni.com/labview/

Here's a tutorial for interfacing a c# application with Arduino: http://www.codeproject.com/Articles/473828/Arduino-Csharp-and-Serial-Interface

The gist of it is this:

1. Some version of Visual Studio up and running - you can use the free version mentioned in Jon's answer (Express version for desktops).
2. A working Arduino connected to your computer with the USB.
3. Create a new Windows Forms Application and drop whatever controls you need onto the form
4. Write your Arduino-connecting code into the events of the controls

That is the basic method of creating Windows Forms apps regardless of what you're doing. You create forms with controls and your custom code goes into the events of those controls. If you read the tutorial it explains how that code works, but here's a sample... (In the tutorial, they are doing a WPF app, which is slightly different from Windows Forms in how the controls are defined, but the code is basically the same). This is an event of the serial port - you respond to the event by displaying the received data into a text box. Very simple!

```
void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) {
    string data = mySerialPort.ReadTo("\x03");
    myForm.myTextBox.Text = data;
}

```
> 2 votes

# Answer
3 votes for visual studio and a windows desktop, although I would chose WPF. Win32 (Winforms) is a slightly out of date architecture. WPF has a steeper learning curve, but worth it if you want to become proficient. If it is a one off application, don't bother, use winforms.

I'll add a couple of points. Debugging Arduino sucks. I am being kind. The Arduino IDE deploys on com port 1, and prints debugging messages on com port 1, so if you need to communicate un-interrupted by debugging and deployment, what do you use? Not com port 1 for sure. Look at software serial in the beginning and assign ports around its requirements.

Second, writing your own com stack is dumb, yet is done 99% of the time. Look at MQTT if ethernet is available, MQTT-SN if it is not, CmdMessenger or CommandSerial or something similar or spend days designing, writing, re-writing and debugging your own, your choice.
> 1 votes

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


# Question
Title: Uploading new sketch to Leonardo-type boards when you've changed the HID mode
I have Sparkfun Pro Micro (Leonardo compatible board). I got it because I plan to build my own array of controls for use in flight/racing sims.

My starting point is LeoJoy, and I didn't have any trouble getting this up and running. Installed just fine, and I have a programmable HID joystick available in windows. It seems to work by modifying the RAWHID code in the default libraries to spoof being a HID joystick. However, my board was now stuck in joystick mode, with no available COM ports for uploading new sketches.

Resetting the board (by grounding the RST pin), enables the COM port, but very, very briefly. Not enough time to send new sketches.

After about an hour of trying different timing, I finally did upload an empty sketch to the board before it went into Joystick mode. So I'm good for now, but I'm a bit worried that I'm going to have to repeat this every time I want to make a change to my program.

Am I doing something completely noobish here? Is this the correct way to program a board that has been forced to act as a joystick? Is there a better way?

Perhaps there's some code I can put into my sketch that will delay the change of USB behavior for a few seconds. That way, it will allow me to recompile and submit my sketches after a reset without having to rush the timing.

# Answer
From Sparkfun's page Pro Micro Hook-upGuide

When a Pro Micro is externally reset (by pulling the RST pin low), it’ll only briefly (\<750ms) start the bootloader before continuing on to the sketch. If you need the bootloader to run longer, resetting twice quickly will get the Pro Micro to enter bootloader mode for eight seconds.

Hope that helps! If not there are some other procedures you might want to look into.
> 0 votes

---
Tags: serial, arduino-leonardo
---


# Question
Title: Can an Arduino Micro receive commands from another microcontroller when hardwired together?
I plan to build functioning reaction wheels, controlled by an Arduino Micro. Ideally, I'd like to have the reaction wheels, and the micro, be a single unit which would receive external commands from another microcontroller.

I know you can link Arduino microcontrollers, and every time I've seen it done it has been with a RC module such as XBee. Is it possible to link units using something like the micro-usb on the Arduino Micro?

If this is possible, is it as simple as connecting the micro-usb ports on my microcontrollers, and then working out the programming?

# Answer
You cannot do this with the micro USB ports. You will need to use I/O pins. Either serial or I2C would be good options. It might be advisable to use I2C if you want to control multiple 'slave' microcontrollers as they can all sit on the same bus. Using the serial port would require multiple transmit and receive pins on the master controller, likely requiring software serial ports (high overhead). Also, if you don't use the serial port for comms, then you can use it for debugging.
> 4 votes

# Answer
It might be worth explaining WHY you can't "just connect the micro-usb ports". There are two issues here:

1. USB is not symmetric, and an Arduino micro is only designed to act as a client. One of your microcontrollers would need to have USB OTG support to act as a host.
2. Even though there are microcontrollers that do have USB OTG support, you'd still have a nontrivial hurdle writing the software for them (Pretty sure the Arduino USB code is client specific as well, though I'm not familiar with the details of the serial over USB protocol).

In short, your basic idea is not physically or technically impossible, but would be fairly difficult to execute, while there are much simpler solutions available.
> 2 votes

# Answer
Usually the RF links (xbee included) just replace a set of wires connecting two serial ports. You can very easily connect the serial ports on two arduino's and communicate between them without any special hardware in between. You will only need 4 wires (power, ground, transmit, receive).
> 1 votes

# Answer
You can use a USB **connector** (micro) (mounted on a custom PCB) for whatever you want and route the connector's pins to whichever Arduino pins you want. It will not be USB, but you could, at least, use USB cables for ease-of-connection.

This is *un-wise*, at best, because someone is, eventually, going to plug in a real USB cable.
> 0 votes

---
Tags: serial, i2c, usb, communication
---


title: Arduino over a Network

text:
# Question
Title: Arduino over a Network
I am new to arduino programming. I want to sense temperature and send it to a server in my college. I am using Arduino Uno R3 board which has ATmega 328P micro-controller. I am able to get serial output on my PC but is there a way in which I can send temperature data to the server in a packet format using Arduino Programmer and not using Ethernet Shield ? Please answer in a less complex way.

# Answer
Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:

arduino-\>serial (usb)-\>processing-\>internet

This way you create the internet packet in processing using the temperature information received through serial from arduino.

see also https://processing.org/
> 0 votes

# Answer
Use an Arduino Yún: it's a Leonardo coupled with a CPU running GNU/Linux (a flavour of OpenWRT).

Using the Bridge library, your sketch can delegate tasks to the linux side.

HttpClient example (Examples \> Bridge \> HttpClient) GETs a page from the Arduino web site, but the HttpClient class may POST whatever data to a server of choice.

There is also a nice example called SendDataToGoogleSpreadsheet (Examples \> Bridge \> Temboo \> SendDataToGoogleSpreadsheet): it accumulates sensor readings on a google spreadsheet. I've used something like that on a project of mine.
> 0 votes

---
Tags: ethernet
---


# Question
Title: Connecting a LSM9DS0 9DoF module to Arduino Uno
I got a bit confused by Sparkfun's hookup guide for this 9DoF breakout module.

It says the VDD-in on the breakout *"should \[get voltage\] regulated between 2.4V and 3.6V"*, yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.

Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?

# Answer
I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.

In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.
> 1 votes

---
Tags: arduino-uno, voltage-level
---


# Question
Title: Will a magnetometer give distorted values if there is a magnet near?
I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?

# Answer
> Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.

In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.

The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

* At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.
* Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of **about** 1 Tesla at a distance of 1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.
> 4 votes

# Answer
The IMU magnetometer is made to measure the magnetic filed of the earth, which magnitude is a few 10 - 60 uT (micro-Tesla). You cannot measure it near to a large magnet that may generate 1 T or more: the magnetometer will saturate.
> 1 votes

---
Tags: sensors
---


# Question
Title: arduino program got error expected //primary-expression before ')' token error: //expected ';' before '}' token E
```
#include "pulse-sensor-arduino.h"
#include "Arduino.h"
#define PulseSensorbegin

int pulsePin = 0;
int blinkPin = 13;
int fadePin = 5;
int fadeRate = 0;
volatile int BPM;
volatile int Signal;
volatile int IBI = 600;

volatile boolean QS = false;

void setup(){

  pinMode(blinkPin,OUTPUT);
  pinMode(fadePin,OUTPUT);
  Serial.begin(115200);

  PulseSensorbegin();

}

void loop() {

   sendDataToProcessing('S', Signal);
   if (QS == true)
   {
       fadeRate = 255;
       sendDataToProcessing('B',BPM);
       sendDataToProcessing('Q',IBI);
       QS = false;
   }

   ledFadeToBeat();

   delay(5000);
}

void ledFadeToBeat(){

    fadeRate -= 15;
    fadeRate = constrain(fadeRate,0,255);
    analogWrite(fadePin,fadeRate);
  }

void sendDataToProcessing(char symbol, int data ){

    Serial.print(symbol);
    Serial.println(data);
  }

```

/// my ccp program

```
#include "pulse-sensor-arduino.h"

volatile int rate[10];
volatile unsigned long sampleCounter = 0;
volatile unsigned long lastBeatTime = 0;
volatile int P =512;
volatile int T = 512;
volatile int thresh = 512;
volatile int amp = 100;
volatile boolean firstBeat = true;
volatile boolean secondBeat = false;
volatile boolean Pulse = false;
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;
volatile int PulseSensor::BPM;
volatile int PulseSensor::Signal;
volatile boolean PulseSensor::QS = false;
void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  TCCR1A = 0x00;
  TCCR1B = 0x0C;
  OCR1A = 0x7C;
  TIMSK1 = 0x02;
  sei();
}

ISR(TIMER1_COMPA_vect)

{
  cli();
  PulseSensor::Signal = analogRead(pulsePin);
  sampleCounter += 2;
  int N = sampleCounter - lastBeatTime;

  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3)
{
    if (PulseSensor::Signal < T){
      T = PulseSensor::Signal;
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P)
{
    P = PulseSensor::Signal;
  }

  if (N > 250){
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;
      PulseSensor::IBI = sampleCounter - lastBeatTime;
      lastBeatTime = sampleCounter;

      if(secondBeat){
        secondBeat = false;
        for(int i=0; i<=9; i++){
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){
        firstBeat = false;
        secondBeat = true;
        sei();
        return;
      }

      word runningTotal = 0;

      for(int i=0; i<=8; i++){
        rate[i] = rate[i+1];
        runningTotal += rate[i];
      }

      rate[9] = PulseSensor::IBI;
      runningTotal += rate[9];
      runningTotal /= 10;
      PulseSensor::BPM = 60000/runningTotal;
      PulseSensor::QS = true;
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){
    Pulse = false;
    amp = P - T;
    thresh = amp/2 + T;
    P = thresh;
    T = thresh;
  }

  if (N > 2500){
    thresh = 512;
    P = 512;
    T = 512;
    lastBeatTime = sampleCounter;
    firstBeat = true;
    secondBeat = false;
  }

  sei();
}

```

//my header programing

```
#ifndef PULSE_SENSOR_ARDUINO_H
#define PULSE_SENSOR_ARDUINO_H

#include "Arduino.h"

class PulseSensor
{
public:
  static void begin(int pulsePin);

  static volatile int BPM;
  static volatile int Signal;
  static volatile int IBI;
  static volatile boolean QS;
};

#endif

```

# Answer
> 4 votes
At the top of your program you have this:

```
#define PulseSensorbegin

```

which defines `PulseSensorbegin` as nothing

Then later you have:

```
PulseSensorbegin();

```

which the pre-processor turns into:

```
();

```

which is where the error is occurring.

---
Tags: programming, sensors, arduino-yun, interrupt, string
---


# Question
Title: Writing serial data, just once after read
I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.

I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.

```
int led = 13;
char incomingByte = 10;
long randNumber;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
 Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

//  delay(1000);               // wait for a second

   if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
              //  Serial.print("I received: ");

                randNumber = random(1, 2000);
                Serial.println('PL' + randNumber);
                  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);               // wait for a second
                  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW

}

}

```

# Answer
When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. `Serial.read()` only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.
> 5 votes

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


# Question
Title: What does the datasheet information for a switch mean?
I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps.

A project I'm working on now requires turning on an LED using a float switch like this one: Water Level Switch

The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.

# Answer
A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than 20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.
> 1 votes

# Answer
It says "*maximum* breakdown voltage: 250 V DC". That's maximum, not minimum. Above 250 V DC the arc which is created by an opening contact isn't guaranteed to extinguish. It's defined for DC voltage because then the arc remains; for AC the arc will extinguish automatically when the current crosses zero.
> 1 votes

---
Tags: sensors, power, voltage-level, resistor, electronics
---


title: Serial Data through Pin 13 LED

text:
# Question
Title: Serial Data through Pin 13 LED
I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.

I came across this link which seems useful, but I can't quite get it to read from Serial:

http://arduino.cc/en/Tutorial/BlinkWithoutDelay

Thanks in Advance

# Answer
If you are going to use an external LED, then using software to make the LED blink when the RX or TX line is busy is a waste of your CPU.

Instead, simply connect the LED to the RX or TX line using a transistor as a buffer to prevent the current draw from messing with the serial signal.

To borrow an image from this answer to a similar question:

You can try omitting the transistor buffer, but the serial waveform will be altered, possibly to the point where data becomes corrupted. The transistor prevents the current draw of the LED and resistor from loading down the RX or TX lines.
> 1 votes

---
Tags: serial, arduino-mega, led, pins
---


# Question
Title: How do i wire a switch to control Leds on a arduino nano
I am wiring some LED's with buttons to trigger them but i don't know if i have the wiring right?

Code

```
    /* switch
 *
 * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 * a minimum delay between toggles to debounce the circuit (i.e. to ignore
 * noise).
 *
 * David A. Mellis
 * 21 November 2006
 */

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

```

> note The code is not set to the pins yet.

# Answer
> 2 votes
The wiring is correct, but `inPin` in your code is set to `2`, which is `D4` on the Nano, while you have your signal wires going to `D7` and `D6` in your schematic.

Similarly, `outPin` is set to `13` in your code, which is `D9` on the Nano, but your schematic shows the LEDs connected to `D5` and `D4`.

I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.

---
Tags: led, arduino-nano, digital
---


# Question
Title: 6 + 1 motors connected to an arduino uno?
Is it possible to connect 6 dc motors and 2 dc servo motors to an Arduino Uno? I intend to control the Uno with a Raspberry pi connected through USB.

Assuming every motor to be bidirectional, how many L293 or L298 motor driver boards do I need? Is there any other better option than using multiple driver boards?

# Answer
TI is only one of the many manufacturers who make some really nice motor control chips. The DRV8835 is one such device: it will drive two motors at voltages up to 11 Vdc at currents up to 1.2 Amps each. Each channel requires two control lines: enable and direction.

Pololu sells this chip already mounted to a carrier board for a rational price.

You will need a total of (6 motors * 2 lines per motor) = 12 i/o lines PLUS two more lines to control your servos for a total of 14 i/o lines from your controller.
> 2 votes

# Answer
Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.

In addition, each servo will need one output pin (typically 9 and 10 for both servos).

Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!

If you can wire all 6 enable pins together, then **you will need "only" 15 pins**.

Also, note that if you want to **control the speed of the DC motors**, you will need PWM pins, but then **you won't get enough with a UNO**.

Regarding drivers ICs (**L293 or L298**), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so **you will need 3 of them overall**.
> 0 votes

---
Tags: arduino-uno, motor, pins, servo
---


# Question
Title: Using an Arduino to switching a grounded load powered by a 12 Volt supply
I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.

This is what I have tried so far.

The ***load must be between*** my ***mosfet*** and my car battery ***GND***.

# Answer
In your existing arrangement.

Swap to P Channel FET
Swap drain and source leads (right hand two).

This will work for up to 5V feed to LEDs.

To get 12v operation you will need to add a driver between the FET gate and the Arduino.
see circuit diagram below.

---

To operate with FET on the HIGH (V+) side when V+ is greater than the rduino's supply voltage, the FET must either

* Be P Channel with FET source to +12V and FET drain to load+ or
* An N Channel with gate drive above V+.

The gate drive to the FET must go to about +12V to turn it off.
The Arduino will only drive it to +5V.

As you are unlikely to want to provide an extra high side drive the P channel option is preferred. This could be eg:

* A "jellybean" bipolar transistor or small FET worth a few cents) and a few resistors, or a small N Channel MOSFET and one resistor

or

* An opto isolator.

---

**Transistor driver:**

Bipolar transistor NPN (BC337 / BC817 or similar)(ANYTHING NPN will work).
R1 = 10k resistor Arduino out to base.
R2 = 10k FET gate to +12.

If an N Channel MOSFET is used for Q1 then R1 is not needed.

This could be a 5LN01SP IF you can get them - no stock Digikey.These have a very low Vgsth (turn on voltage)

Otherwise you can use a 2n2222, VN2222, BS108 or similar logic-gate N channel MOSFET.
eg VN2222. Many variants of these are widely available and low cost.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

---
Tags: mosfet
---