# Question
Title: Atmega328 component library for Protel 99 SE
Any one know a **component library** for Arduino UNO (**Atmega328**, etc) for **Protel 99 SE** PCB design software?

# Answer
> 0 votes
Found it here with 94 chips.

The author states, "I have made a little library for Protel 99SE with schematic sybols of AVR chips."

http://www.avrfreaks.net/forum/avr-8bit-microcontrollers-protel-99-library

# Answer
> 1 votes
All arduino design schematics are available from the Arduino website, e.g. for the Uno. However, these are in EAGLE format, I don't know if it's possible to convert.

---
Tags: arduino-uno
---


# Question
Title: Is it possible to read VGA with an arduino
In this forum thread on arduino.cc http://forum.arduino.cc/index.php?topic=107375.0 they talk about it not being possible to get 800 x 600 video in color with the arduino.

My case is a bit different:

* I don't care about color, it can be black and white / grayscale.
* I don't need 800 x 600 just 640 x 480.
* I can do with something like 2-5 frames per second.
* I don't need it to be processed by the arduino, just transmitted through an ethernet shield.

In other words, it is possible to transmit simple video (just enough to handle eg. bios) remote?

# Answer
> 4 votes
Trying to *capture* analog video such as VGA and transmit it over Ethernet is going to be technically challenging, and of questionable wisdom (at least without compression). A conventional ATmega-based Arduino is just about the *worst* contemporary platform you could choose for this job - even aside from the VGA issue, it is a poor choice for Ethernet requiring an expensive add-on. But just for the sake of "can it be done" ....

If you can threshold your signal to a digital level (assuming a high contrast image) this probably can be done, crudely, but will be quite tricky. The display is likely to be very blurred horizontally - really, it would only be worth doing for bragging points.

The first thing to realize is that the standard VGA 640x480x60 mode has a pixel clock of 25.175 MHz, and most others will be even faster.

One approach would be to try to write a program which samples a digital pin (directly, no Arduino abstractions) to memory as fast as possible. This would not capture every pixel, but rather something like every 10th. You would then have to send these over the network before you fill up your available memory.

The tricky part is that you then have to go back, and scan another frame of video with a slight offset, so that by getting every 10th pixel again, you effectively get the pixel adjacent to the first. And then you do it again, and again, until you have collectively transmitted the entire screen, which hopefully hasn't changed much as you did it.

It's going to be tricky as you will have to work your delays from the sync signals, and you really want a delay which is a fraction of ATmega's clock - which won't happen without external circuitry (programmable delay buffer, etc)

The whole project would be a lot more feasible on an 80+ MHz ARM Cortex part, as you could then use a counter/timer to generate pixel-or-less-adjustable starting delays relative to the sync pulse. An FPGA would likely be an even better choice.

# Answer
> 1 votes
Well, it's very possible, but actually you'll stress the arduino. You can use it perfectly but the problem is, it takes a lot of time of Arduino. The reason is actually simple: Horizontal syncronization takes each 32uS of arduino, so the code is interrupted a lot, and if you use other codes the screen may flick. But i have a solution for you. I found software libraries: http://forum.arduino.cc/index.php?topic=102181.0 or: http://labdegaragem.com/profiles/blogs/gerando-sinal-vga-colorido-com-arduino-completo

The last link is in portuguese but you can always ask me anything.

OK, what people do is to use for example 2 arduinos to aliviate de stress, you can buy a arduino bare metal chip and put it in a protoboard to reduce costs. Buuut, ther's another very very easy way to work with vga in arduino. Using a isolated hardware: http://www.hobbytronics.co.uk/serial-vga

You just need to send serial commands to the vga driver and it will do whatever you want. It comes with a library so you can use in arduino. It's perfect, aliviates the arduino, so you can use your ethernet communication and the price is great (for you, here in Brazil the fees kill a lot of children every day :-( ).

---
Tags: arduino-uno, ethernet, display
---


# Question
Title: Arduino UNO + CC3000 Wifi Shield, Reading webpage data
I'm new so I might be making a stupid mistake, but I'm declaring:

char dollars;

at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.

The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.

here is the important part of my code:

```
unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      dollars = www.read();
      lastRead = millis();
    }
  }

  www.close();
  Serial.println(dollars);

```

while the www.read is repeating each of the returned characters it works fine `Serial.print(c);` but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?

I'm planning to show that number from the web page onto my 4 digit screen at the end.

# Answer
Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or \[53, 53, 13, 10\] in bytes.
You need to parse the characters, like Serial.parseInt() does.

You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.
> 1 votes

---
Tags: arduino-uno, serial, wifi, variables
---


# Question
Title: What's the difference between different Ethernet Shields?
I am working on a project with Arduino and I need an Ethernet shield. but after searching in some electronics shops I found there isn't only one but a lot. I don't know which one is better and what are the differences.

Arduino Ethernet with PoE module

Ethernet Pro

Ethernet Shield for Arduino - W5200

Arduino Ethernet Rev3 Without PoE Module

Ethernet Shield W5100 For Arduino

in DFRobot Online Shop.

# Answer
Clearly the 'best' one is the one that meets your requirements (or is the most expensive - that's always the best, right?).

You say you need an ethernet shield - can you explain why? Without that information, it's almost impossible to tell you which is the most suitable.

If you are looking at IoT applications, it may be that an Ethernet shield isn't the 'best' thing for you. If you just want access to the local IP network, you could use any of those. If you want the 'best' library of functions to support your application, that may affect which module you use.

For me, I think the best module is the cheapest one that gives me connectivity: http://www.aliexpress.com/item/Hot-Sale-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-51-AVR-STM32-LPC/32254842414.html

The W5100 is also a good choice, but only if it is under $7
> 2 votes

# Answer
What one that is the best is highly subjective.

Though my **personal** experience is that arduinos original is the one with the best support. Where you can find alot of documentation about the other ones, you might need to do some legwork updating the code to the latest version of the arduino ide or use an older ide.

Be aware that some Arduinos has integrated ethernet, and others are SHIELDS, you recognize the arduinos with ethernet by the power-connector, and the shields by the distinct name containing "Shield", though shields require an arduino to work. The arduino with integrated ethernet does not.

Also be aware that not all shields fits arduinos boxes if you want to encase it. And of cause, buying arduinos original products, cost a bit more - but you support the arduino foundation, and further development of the products.
> 2 votes

---
Tags: shields, ethernet
---


# Question
Title: How to access 315mhz signals from household devices, with an arduino 315mhz kit?
Background:

I am looking into automation and I have realized that many of the devices I have around my house transmit 315mhz to their specific controllers. I know this from reading the labels on the back that say 315mhz

Question:

Is there a way I can use a 315mhz receiver with an arduino to view the signals and log the data based on what happens and mimic certain actions with the transmitter? In other words can I program the reciever to display every bit passed through 315mhz that is in range?

I know the virtual wire library parses the data before I receive it, but I don't know to what extent? If I just dedicate the arduino to watch that pin and print results will that tell me what is being sent?

Thanks Very Much,

Joel

# Answer
**The Short Answer:**

In theory it is possible to do what you are asking. There are examples of using an Arduino to send and receive messages at 315 MHz. Such as this example.

Although these devices might not even be compatible with the ones you are using. They may be modulating their signal differently or framing their data differently or at different baud rates or encoding bits differently or a number of other fundamental differences that would make them incompatible.

**The Long Not Quite An Answer:**

There is more to the problem than just being able to get bits at 315 MHz.

For one you would need to know how the bits are encoded. See some of the answers on this post.

Even if it was a simple high low stream of even width bits. You also need to know what baud rate the bits are being transmitted at so you can sync with it. (Consider 4800 vs 9600 baud, slow I know but just an example. You just got a bit stream, was it 1010 at 4800 baud or 11001100 sent at twice the speed of 9600.)

Not to mention that the lowest level of data is probably not just a stream of bits, but is probably framed in some way and grouped into a byte/bytes. Or has a leader to help lock onto the signal.

Even once you are getting reliable data you would need to know the data structure. Is the data arranged in packets? Do they have a packet header? Does the header contain these packet destination address? Where in the header is this data? How is the data apart from the header structured? What does it mean?.

Knowing the answers to these questions defines, or is defined by, the protocol that is being used by the transmitter (as others are saying in comments.) But these are only a few simple questions that **start** to define a protocol. Often this information is difficult to come by. Often in the case of proprietary protocols it is very very difficult.
> 3 votes

---
Tags: sensors, rf
---


title: Connect multiple RFID-RC522 cards?

text:
# Question
Title: Connect multiple RFID-RC522 cards?
I have a project that requires 4 different RFID-RC522 readers. The RFID-RC522 has the following pins:

* SDA
* SCK
* MOSI
* MISO
* IRQ
* GND
* RST
* 3.3V

I have read that the SDA pin is used for selecting the active device, So I'm thinking that these devices can share data pins. Is it possible to connect multiple RFID-RC522 readers to the same 3.3V, RST, GND, IRQ, MISO, MOSI and SCK pins if you use a different pin for each SDA? If so, this would save me a lot of pins. So far, I have only seen direction on how to connect one RFID-RC522 to an Arduino.

I'm using the MFRC522 library. It appears to only support one reader because it only allows one SS pin to be identified in the constructor, and offers no way to change it later. An I missing something or do I need another library?

# Answer
> 1 votes
Connect everyone to the MOSI / MISO / SCK and ground, then define every SDA all the way around. and set respectively high low depending on where you want to write.

How ever im not sure if you need to set high or low if you want to read. But since you got multiple you can play around with that your self. Feel free to add to this question with the result for future googlers.

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

#define RST_PIN           7          // Configurable, see typical pin layout above
#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

....

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

....

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card

```

---
Tags: rfid
---


# Question
Title: Are there any products based on Arduino that are sold by companies?
Ok, Arduino is a good technology but is it used professionally? Is the quality good enough to be used for professional purposes?

# Answer
In theory, an Arduino board *could* be used in some low-end professional products (i.e. where the performance and memory limitations aren't an issue). The build quality of the official boards is certainly good enough. The only issue they would potentially have is making suitably robust connections -- i.e. anything plugged into a female header would have the potential to get shaken loose.

In practice though, using an Arduino board would only make sense for extremely small-scale projects, where only a few units will be produced, and where there will be a minimum of external circuitry.

A commercial project would normally have a custom circuit board designed. That allows them to economise on space and features, eliminating unnecessary costs. Even if it only saves a small amount per board, it can make a big difference if you're doing mass-production.

With that said, a professional product could certainly use an AVR microcontroller or similar at its heart (much like the Arduino boards). Atmel was producing chips long before Arduino was around, and their products are well known and widely used. The choice really depends on the needs of the individual project.
> 7 votes

# Answer
Yes, you can also use an Arduino for professional usage. The Arduino is actually just a prototyping device and easy to use for people at home/school. I suppose there might be products on the market which were developed using an Arduino. But the most important thing is the Atmel MCU inside the Arduino which can be used for anything. But, if you wanna know if the ATmega328P-PU which is used in the Arduino Uno is a common MCU used by professionals? The answer would be no. Everything has to be smaller and better so it'll be more likely to find the same MCU like the Arduino Leonardo, Mega etc etc.

Examples where professionals might use an Arduino for as base (The end product will only contain the MCU of the Arduino):

* Kid toys like an Simon Says Game, Line following toy cars etc etc.
* Small industrial products like an automated tape dispenser.
* AVR programmers.
* Card readers.
> 6 votes

# Answer
Yes, I work for an engineering design house and we use Arduino frequently to prototype ideas for clients. It significantly speeds up the time to get a proof-of-concept device in the hands of the client and their potential investors.

We have found though that there is significant work to get from an Arduino-based prototype to a commercially-ready product. Essentially you have to start again and design a completely custom printed circuit board, which is a relatively expensive exercise.

We are now developing a platform that is compatible with the Arduino IDE, but uses surface-mount modules rather than the Arduino shield system, allowing it to be manufactured in an automated surface-mount facility. Check it out if you are interested at duinopro.cc. We are in development stages at the moment, but already have hardware and are mainly working on our website, and designing new modules.
> 2 votes

---
Tags: build
---


# Question
Title: Why is Serial.print working when nobody receives the data?
I have a kind of theoretical question. Let's have an Arduino Uno connected through USB that does a lot of Serial.print-ing. Then I disconnect it and I don't see anything on the Serial monitor, but the Arduino is still working. I can judge by the blinking lamps and so on.

Now I see that all printing goes through HardwareSerial::write from the Arduino core. There is this statement:

```
  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  // ???: return 0 here instead?
  while (i == _tx_buffer->tail)
    ;

```

It means that if the output buffer is full, the Serial.print will hang there eternally. However this doesn't happen. I guess somebody is consuming the data and to be more precise in ISR(USART\_UDRE\_vect). It seems as the only place where within interrupt \_tx\_buffer-\>tail can be changed. Otherwise the code would loop endlessly in HardwareSerial::write. This interrupt USART\_UDRE\_vect should be raised only when the Data Register is empty.

My question is - who is consuming the sent data? Is that done by some USART\_to\_USB drivers? Or am I missing some part of the picture?

Regards, Boyan

# Answer
atmega 328p datasheet, section 20.6.3:

> The Data Register Empty (UDREn) Flag indicates whether the transmit buffer is ready to receive new data. This bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the Shift Register
>
> ...
>
> When interrupt-driven data transmission is used, the Data Register Empty interrupt routine must either write new data to UDRn in order to clear UDREn or disable the Data Register Empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates.

the USART Data Register Empty vector is run when the hardware for USART serial has taken the byte in the register and sent it, not when a receiving device has polled and "taken" it. Once copied into the shift register and sent out of the chip nothing knows if there was another device to "hear" it or not. Some systems may have hardware flow control and wait for a CTS (clear to send) signal on a different wire, but the arduino does not.

You may also notice that if interrupts are not currently enabled (preventing USART\_UDRE\_vect from ever occuring) the HardwareSerial::write routine will manually poll the correct condition and run the interrupt handler when appropriate to cycle data through and prevent a deadlock.
> 1 votes

# Answer
The USB-UART bridge is, if it can. And if it can't, no one cares. A UART is *asynchronous*, hence it doesn't care if anyone consumes it; as long as it has sent the data, that's all it cares about. There can be additional checks to see if the other side is able to *receive* data, but that is not implemented on the Uno.
> 2 votes

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


title: Fog machine Arduino integration

text:
# Question
Title: Fog machine Arduino integration
I want to control my fog machine with an Arduino. Has a simple button that is used to activate the machine. I want to press this button using an Arduino digital output pin, but the fog machine is operating on its own electrical circuit. How do I use the Arduino to activate this machine?

I a few other machines with buttons that I want to wire into an Arduino, so is there a generic solution?

# Answer
You can interface with the fog machine's button by:

1. Use a Relay (this will isolate the fog machine's circuit from your Arduino's)
2. Use a Servo to physically press the button on the fog machine

I believe those would be the simplest and most generic.
> 2 votes

# Answer
Please do not upvote this answer.
This is an expansion of @Krol's answer. Krol may incorporate this material in his answer if he wishes.

The image below shows a typical relay module which is able to be driven by logic level / GPIO signals from typical microcontrollers.
The relays have 5V coils and there are optocouplers and drive transistors between the input and the relay.
Inputs are active LOW - ground to turn on.

These are available by mail from China for under $2/relay (under $1/relay if you buy 10 modules with several relays in).

They are **NOTIONALLY** opto-isolated as well as having relay isolation between input and contacts. **BUT** the PCB layout and relay design is such that mains to input clearances are poor. They will **PROBABLY NOT** kill you or your controller but they may - as is the case with much other items manufactured afar off at ludicrously low prices.

I have found the seller/manufacturer whose logo appears on that photo to be a reliable supplier of well made products. (Being well made does not overcome "dangerous design" as above.

Note that the above warning applies to most buffered relays you can buy on the hobbyist market and also top consumer products that have not been put through formal testing (UL etc). This relay board would fail UL testing - as would most others.
> 2 votes

---
Tags: button, relay, transistor
---


# Question
Title: How can I send data to many IC's without using tons of shift registers?
I'm building an audio circuit that will play `VGM` files (Video Game Music).

I have it working with two different "vintage" IC's such as the `SN76489` and the `AY-3-8912`.

Currently, my design is using an `Arduino Micro` and two shift registers for the data buses and direct pins for the control pins on the audio IC's.

On average, an audio IC has `8 pins` for the data bus and `4 pins` for the control or address bus. This varies per IC. Some might be 3, some 4, some 6, etc.

Bottom line, even with the 20 IO pins on the Arduino, I will quickly run out of pins. I thought about serializing many shift registers and basically pass 64 or 128 bit numbers to spread out to the multiple IC's but this sounds ugly.

I'd like to be able to support maybe 6 IC's which could be 60-80 pins.

I also have an `Arduino DUE` which has many more IO pins. But then I have to deal with the 3.3v limit and I only have 4 level shifters (16 pins).

Any suggestions on how to handle this?

Thanks.

# Answer
There are other ways,but for a brute force many pin driver solution:

Back at the beginning of time when steam driven IC's were all the vogue there was the awesome **MM5450.** 40 pin DIP. 34 on/off outputs. 3 pin control. Or the really keen could do it with 1\` pin control and some basic RC timing. I was. I did.

Its day has passed. but, fortunately. neither Micrel or Digikey know this.

**MM5450 datasheet**
**In stock Digikey $5.46/1**

It's a very benign beat to drive once you get to know it. There is no reset (inless you buy bare dies) so you have to start off getting it synchronised - it's not hard, just not quite usual. Works well.

For single GPIO pin control the pin acts as data out and clock with some RC timing.
Fot ICs with clock/data/load you can do all 3 with RC timing on one pin.

**And there is a 44 pin PLCC pkg version available.**

---

AND!

SN74LS673 16 bit SR, 24 pins http://www.ti.com/product/sn74ls673

ICM7243 http://www.ebay.com/itm/ICM7243BIPL-HARRIS-40-Pin-DIP-LED-DISPLAY-DRIVER-ICM7243-7243A-/390402848376

And others http://www.ebay.tv/sch/i.html?\_sop=7&\_nkw=led+driver+ic&\_frs=1
> 1 votes

---
Tags: pins, audio, arduino-micro, shift-register, atmega32u4
---


# Question
Title: Is there a thermal sensor with a distance of 10 meters for Arduino
I am looking for a thermal sensor with a distance of 10 meters . In my plan , I would like to recognize objects based on the heat. for example car.

# Answer
How about this one at £20?

The range depends on what lens you put in front of it - this has to be plastic as IR doesn't penetrate glass, but you can set your own range, like a focus adjustment. Commercial IR remote thermometers generally have aiming dots (laser) so you can see the optimum range - there's a fixed lens.

The actual sensor won't have a defined range, because of this.
> 3 votes

---
Tags: sensors
---


title: Arduino, relays and building code

text:
# Question
Title: Arduino, relays and building code
I want to install several Arduino controlled relays which are use to turn on/off some lights, a fog machine and some door locks in a building. What do I need to do to insure that the power relays don't violate building code?

Do components need to be put in a box or can they be mounted to a 2x4? Are there requirements regarding the points were the bear wire is screwed into the relay?

I am assuming that if anyone as ever wired an Arduino into a garage door opener, these questions may have come up.

# Answer
**Disclaimer:** IANAL nor US regulations expert.

There are a few standard certifications that will essentially guarantee that a part will meet US regulatory requirements. Usually more of the form "your building burned down and you have no insurance because ..." rather than prosecuting you for non compliance.

Relays with UL rating bought via a reputable US supplier will usually quality.
eg if Digikey sell it it is PROBABLY Kosher.
Also if made by reputable manufacturers the same applies, as long as its genuine. eg (1 of many) Omron - they don't make no junk largely and even their junk is certified :-).

**HOWEVER** if you are building something using such parts the whole unit will need to be certified. For small volume applications it may be easier and cheaper to buy comething COTS (commercial off the shelf) which has the relevant certifications. That said,be sure these are legitimate.

## As a guide:

**US standards** a useful introduction

**Extensive international standards summary**

**Wikipedia on UL**

**MET Labs strut their stuff** comparison with UL.

**Intertek test labs bow in**

**Useful - Understanding electrical certification**

**Possibly useful templates**
> 1 votes

---
Tags: relay
---


title: Tv remote connection to an Arduino

text:
# Question
Title: Tv remote connection to an Arduino
I have a tv remote that I want to connect to an Arduino so that I can send a series of commands to the TV using the remote. I would like to open the remote and solder transistors or a Transistor Array in place of the buttons. I have never done this before, so what do I need to be aware of? I think that I will need to power the remote using the Arduino's power supply, but I am a bit foggy on the details.

# Answer
> 3 votes
If you're just running lines to the buttons, you won't need to power the remote from the arduino. You could just let it keep the internal batteries. But it would be possible to wire it up for power as well.

As a learning project, you could just take it apart and see if you can access the button contacts. See if the contacts are split. If so, shorting one side to the other should count as a button press. But the details have nothing to do with an arduino. They would depend on your specific remote and how it's constructed.

If your purpose is really to control the TV (rather than learning about the remote and fiddling with it), it will be much easier (and probably cheaper) to blast the IR without involving the remote at all. A single IR transmitter and a library would work in most cases. As an example: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html

P.S. By coincidence, Adafruit just posted an updated guide to IR library use on Arduino. https://learn.adafruit.com/using-an-infrared-library/overview

# Answer
> 3 votes
Using an IR library as mentioned in a previous answer is likely to be about the best approach. However, if you decide to use electronic switches to jumper across the remote's switch contacts, consider using CMOS analog switch chips for the purpose. If each button on the remote connects one contact to a common net, inexpensive chips like 74HC4051 and CD74HCT4067 would serve for 8 or 16 buttons each, respectively.

I don't have a reference for an affordable many-SPST-contacts CMOS switch. Inexpensive chips with a few such contacts are available. The 74HC4053, for example, contains three SPDT CMOS switches. Handling a dozen buttons would use four 4053 chips. A CD4007 probably could provide three SPST switches also.

*Edit:* The figure above shows pinouts of CD4051/52/53 devices. To use a CD4053 as three separate switches, connect V- and GND to Arduino ground, V+ to +5V or +3.3V, and each of COMA,B,C to one circuit contact to be switched. With NCA, NCB, NCC connected to the other contacts of circuits A, B, C, raise ADDA, B, or C and drop INH to close circuit A, B, or C.

If your remote has dozens of buttons, it's likely that they are arranged in rows and columns for multiplexed scanning. In this case, follow the printed circuit tracks to identify which buttons attach to which rows and which columns. Suppose there are eight or fewer of one or the other; eg, suppose there are 5 columns and 8 rows. In this case, you would hook up 5 CD4051 chips: connect V- and GND to Arduino ground, V+ to +5V or +3.3V, and the COM of each 4051 to a different column line. Connect NO0–7 to row lines 0 to 7.

To close circuit *j* in column *k*, put *j* in binary on ADDA,B,C of all 4051s and drop INH on 4051 #*k*. (Either use one DIO line per INH, or use a DM74LS138 or MM74HC138 (etc.) and put *k* in binary on the A,B,C select lines of the '138.)

---
Tags: power, ir, transistor
---


title: Arduino interruption (on pin change)

text:
# Question
Title: Arduino interruption (on pin change)
I use the interrupt function to fill an array with values received from `digitalRead()`.

```
void setup() {
    Serial.begin(115200);
    attachInterrupt(0, test_func, CHANGE);
}

void test_func() {
    if (digitalRead(pin) == HIGH) {
        test_array[x] = 1;
    } else if(digitalRead(pin) == LOW) {
        test_array[x] = 0;
    }
    x = x + 1;
}

```

That problem is that when I print `test_array` there are values like: `111` or `000`.

As I understand it, if I use the `CHANGE` option in the `attachInterrupt()` function, then the data sequence should always be `0101010101` without repeating.

The data changes quite fast since it comes from a radio module.

# Answer
> 29 votes
**As a sort of prologue** to this overly long answer...

This question got me deeply captivated with the problem of interrupt latency, to the point of losing sleep in counting cycles instead of sheep. I am writing this response more for sharing my findings than for just answering the question: most of this material may actually not be at a level suitable for a proper answer. I hope it will be useful, however, for readers that land here in search of solutions for latency problems. The first few sections are expected to be useful to a wide audience, including the original poster. Then, it gets hairy along the way.

Clayton Mills already explained in his answer that there is some latency in responding to interrupts. Here I will focus on quantifying the latency (which is *huge* when using the Arduino libraries), and on the means to minimize it. Most of what follows is specific to the hardware of the Arduino Uno and similar boards.

# Minimizing the interrupt latency on the Arduino

(or how to get from 99 down to 5 cycles)

I will use the original question as a working example, and restate the problem in terms of interrupt latency. We have some external event that triggers an interrupt (here: INT0 on pin change). We need to take some action when the interrupt is triggered (here: read a digital input). The problem is: there is some delay between the interrupt being triggered and our taking the appropriate action. We call this delay "*interrupt latency*". A long latency is detrimental in many situations. In this particular example, the input signal may change during the delay, in which case we get a faulty reading. There is nothing we can do to avoid the delay: it is intrinsic to the way interrupts work. We can, however, try to make it as short as possible, which should hopefully minimize the bad consequences.

The first obvious thing we can do is take the time-critical action, inside the interrupt handler, as soon as possible. This means calling `digitalRead()` once (and only once) at the very beginning of the handler. Here is the zeroth version of the program upon which we will build:

```
#define INT_NUMBER 0
#define PIN_NUMBER 2    // interrupt 0 is on pin 2
#define MAX_COUNT  200

volatile uint8_t count_edges;  // count of signal edges
volatile uint8_t count_high;   // count of high levels

/* Interrupt handler. */
void read_pin()
{
    int pin_state = digitalRead(PIN_NUMBER);  // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (pin_state == HIGH) count_high++;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(INT_NUMBER, read_pin, CHANGE);
}

void loop()
{
    /* Wait for the interrupt handler to count MAX_COUNT edges. */
    while (count_edges < MAX_COUNT) { /* wait */ }

    /* Report result. */
    Serial.print("Counted ");
    Serial.print(count_high);
    Serial.print(" HIGH levels for ");
    Serial.print(count_edges);
    Serial.println(" edges");

    /* Count again. */
    count_high = 0;
    count_edges = 0;  // do this last to avoid race condition
}

```

I tested this program, and the subsequent versions, by sending it trains of pulses of varying widths. There is enough spacing between the pulses to ensure that no edge is missed: even if the falling edge is received before the previous interrupt is done, the second interrupt request will be put on hold and eventually serviced. If a pulse is shorter than the interrupt latency, the program reads 0 on both edges. The reported number of HIGH levels is then the percentage of correctly read pulses.

## What happens when the interrupt is triggered?

Before trying to improve the code above, we will take a look at the events that unfold right after the interrupt is triggered. The hardware part of the story is told by the Atmel documentation. The software part, by disassembling the binary.

Most of the time, the incoming interrupt is serviced right away. It may happen, however, that the MCU (meaning "microcontroller") is in the middle of some time-critical task, where interrupt servicing is disabled. This is typically the case when it is already servicing another interrupt. When this happens, the incoming interrupt request is put on hold and serviced only when that time-critical section is done. This situation is hard to avoid completely, because there are quite a few of those critical sections in the Arduino core library (which I will call "*libcore*" in the following). Fortunately, these sections are short and run only every so often. Thus, most of the time, our interrupt request will be serviced right away. In the following, I will assume that we do not care about those few instances when this is not the case.

Then, our request is serviced immediately. This still involves a lot of stuff that can take quite a while. First, there is a hardwired sequence. The MCU will finish executing the current instruction. Fortunately, most instructions are single-cycle, but some can take up to four cycles. Then, the MCU clears an internal flag that disables further servicing of interrupts. This is intended to prevent nested interrupts. Then, the PC is saved into the stack. The stack is an area of RAM reserved for this kind of temporary storage. The PC (meaning "*Program Counter*") is an internal register holding the address of the next instruction the MCU is about to execute. This is what allows the MCU to know what to do next, and saving it is essential because it will have to be restored in order for the main program to resume from where it was interrupted. The PC is then loaded with a hardwired address specific to the request received, and this is the end of the hardwired sequence, the rest being software-controlled.

The MCU now executes the instruction from that hardwired address. This instruction is called an "*interrupt vector*", and is generally a "jump" instruction that will bring us to a special routine called an ISR ("*Interrupt Service Routine*"). In this case, the ISR is called "\__vector\_1", a.k.a. "INT0\_vect", which is a misnomer because it is an ISR, not a vector. This particular ISR comes from libcore. Like any ISR, it starts with a *prologue* that saves a bunch of internal CPU registers on the stack. This will allow it to use those registers and, when it is done, restore them to their previous values in order not to disturb the main program. Then, it will look for the interrupt handler that was registered with `attachInterrupt()`, and it will call that handler, which is our `read_pin()` function above. Our function will then call `digitalRead()` from libcore. `digitalRead()` will look into some tables in order to map the Arduino port number to the hardware I/O port it has to read and the associated bit number to test. It will also check whether there is a PWM channel on that pin that would need to be disabled. It will then read the I/O port... and we are done. Well, we are not really done servicing the interrupt, but the time-critical task (reading the I/O port) is done, and it is all that matters when we are looking at latency.

Here is a short summary of all the above, together with the associated delays in CPU cycles:

1. hardwired sequence: finish current instruction, prevent nested interrupts, save PC, load address of vector (≥ 4 cycles)
2. execute interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save registers (32 cycles)
4. ISR main body: locate and call user-registered function (13 cycles)
5. read\_pin: call digitalRead (5 cycles)
6. digitalRead: find the relevant port and bit to test (41 cycles)
7. digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the hardwired sequence. This gives us a total latency of 99 cycles, or about 6.2 µs with a 16 MHz clock. In the following, I will explore some tricks that can be used to lower this latency. They come roughly in increasing order of complexity, but they all need us to somehow dig into the internals of the MCU.

## Use direct port access

The obvious first target for shortening the latency is `digitalRead()`. This function provides a nice abstraction to the MCU hardware, but it is too inefficient for time-critical work. Getting rid of this one is actually trivial: we just have to replace it with `digitalReadFast()`, from the digitalwritefast library. This cuts the latency almost by half at the cost of a small download!

Well, that was too easy to be any fun, I will rather show you how to do it the hard way. The purpose is to get us started into low-level stuff. The method is called "*direct port access*" and is nicely documented on the Arduino reference at the page on Port Registers. At this point, it is a good idea to download and take a look at the ATmega328P datasheet. This 650-page document may seem somewhat daunting at first look. It is, however, well organised into sections specific to each of the MCU peripherals and features. And we only need to check the sections relevant to what we are doing. In this case, it is the section named *I/O ports*. Here is a summary of what we learn from those readings:

* The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the AVR chip.
* We get the whole port D at once by reading a special MCU register called "PIND".
* We then check bit number 2 by doing a *bitwise logical and* (the C ‘&’ operator) with `1 << 2`.

So, here is our modified interrupt handler:

```
#define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
#define PIN_BIT    2

/* Interrupt handler. */
void read_pin()
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

```

Now, our handler will read the I/O register as soon as it is called. The latency is 53 CPU cycles. This simple trick saved us 46 cycles!

## Write your own ISR

The next target for cycle-trimming is the INT0\_vect ISR. This ISR is needed for providing the functionality of `attachInterrupt()`: we can change interrupt handlers at any time during program execution. However, although nice to have, this is not really useful for our purpose. Thus, instead of having the libcore's ISR locate and call our interrupt handler, we will save a few cycles by *replacing* the ISR by our handler.

This is not as hard as it sounds. ISRs can be written like normal functions, we just have to be aware of their specific names, and define them using a special `ISR()` macro from avr-libc. At this point it would be good to have a look at the avr-libc's documentation on interrupts, and at the datasheet section named *External Interrupts*. Here is the short summary:

* We have to write a bit in a special hardware register called EICRA (*External Interrupt Control Register A*) in order to configure the interrupt to be triggered on any change of the pin value. This will be done in `setup()`.
* We have to write a bit in another hardware register called EIMSK (*External Interrupt MaSK register*) in order to enable the INT0 interrupt. This will also be done in `setup()`.
* We have to define the ISR with the syntax `ISR(INT0_vect) { ... }`.

Here is the code for the ISR and `setup()`, everything else is unchanged:

```
/* Interrupt service routine for INT0. */
ISR(INT0_vect)
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

void setup()
{
    Serial.begin(9600);
    EICRA = 1 << ISC00;  // sense any change on the INT0 pin
    EIMSK = 1 << INT0;   // enable INT0 interrupt
}

```

This comes with a free bonus: since this ISR is simpler than the one it replaces, it needs less registers to do its job, then the register-saving prologue is shorter. Now we are down to a latency of 20 cycles. Not bad considering that we started close to 100!

At this point I would say we are done. Mission accomplished. What follows is only for those who are not afraid of getting their hands dirty with some AVR assembly. Otherwise you can stop reading here, and thank-you for getting so far.

## Write a naked ISR

Still here? Good! For proceeding further, it would be helpful to have at least some very basic idea of how assembly works, and to take a look at the Inline Assembler Cookbook from the avr-libc documentation. At this point, our interrupt entry sequence looks like this:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save regs (12 cycles)
4. first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into the prologue. The idea is the following: reading the PIND register will clobber one CPU register, thus we need to save at least one register before doing that, but the other registers can wait. We then need to write a custom prologue that reads the I/O port right after saving the first register. You have already seen in the avr-libc interrupt documentation (you have read it, right?) that an ISR can be made *naked*, in which case the compiler will emit no prologue or epilogue, allowing us to write our own custom version.

The problem with this approach is that we will probably end up writing the whole ISR in assembly. Not a big deal, but I would rather have the compiler write those boring prologues and epilogues for me. So, here is the dirty trick: we will split the ISR in two parts:

* the first part will be a short assembly fragment that will
    + save a single register to the stack
    + read PIND into that register
    + store that value into a global variable
    + restore the register from the stack
    + jump to the second part
* the second part will be regular C code with compiler-generated prologue and epilogue

Our previous INT0 ISR is then replaced by this:

```
volatile uint8_t sampled_pin;    // this is now a global variable

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    push r0                \n"  // save register r0
    "    in r0, %[pin]          \n"  // read PIND into r0
    "    sts sampled_pin, r0    \n"  // store r0 in a global
    "    pop r0                 \n"  // restore previous r0
    "    rjmp INT0_vect_part_2  \n"  // go to part 2
    :: [pin] "I" (_SFR_IO_ADDR(PIND)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

```

Here we are using the ISR() macro to have the compiler instrument `INT0_vect_part_2` with the required prologue and epilogue. The compiler will complain that "‘INT0\_vect\_part\_2’ appears to be a misspelled signal handler", but the warning can be safely ignored. Now the ISR has a single 2-cycle instruction before the actual port read, and the total latency is only 10 cycles.

## Use the GPIOR0 register

What if we could have a register reserved for this specific job? Then, we would not need save anything before reading the port. We can actually ask the compiler to bind a global variable to a register. This, however, would require us to recompile the whole Arduino core and libc in order to make sure the register is always reserved. Not really convenient. On the other hand, the ATmega328P happens to have three registers that are not used by the compiler nor any library, and are available for storing whatever we want. They are called GPIOR0, GPIOR1 and GPIOR2 (*General Purpose I/O Registers*). Although they are mapped in the I/O address space of the MCU, these are actually *not* I/O registers: they are just plain memory, like three bytes of RAM that somehow got lost in a bus and ended up in the wrong address space. These are not as capable as the internal CPU registers, and we cannot copy PIND into one of these with the `in` instruction. GPIOR0 is interesting, though, in that it is *bit-addressable*, just like PIND. This will allow us to transfer the information without clobbering any internal CPU register.

Here is the trick: we will make sure that GPIOR0 is initially zero (it is actually cleared by hardware at boot time), then we will use the `sbic` (Skip next instruction if some Bit in some I/o register is Clear) and the `sbi` (Set to 1 some Bit in some I/o register) instructions as follows:

```
sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

```

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted to read from PIND. The sbic instruction takes 1 or 2 cycles to execute depending on whether the condition is false or true. Obviously, the PIND bit is accessed on the first cycle. In this new version of the code, the global variable `sampled_pin` is not useful anymore, since it is basically replaced by GPIOR0:

```
/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    sbic %[pin], %[bit]    \n"
    "    sbi %[gpio], 0         \n"
    "    rjmp INT0_vect_part_2  \n"
    :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
       [bit]  "I" (PIN_BIT),
       [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

```

It should be noted that GPIOR0 has to always be reset in the ISR.

Now, the sampling of the PIND I/O register is the very first thing done inside the ISR. Total latency is 8 cycles. This is about the best we can do before getting stained with terribly sinful kludges. This is again a good opportunity to stop reading...

## Put the time-critical code in the vector table

For those still here, here is our current situation:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
3. ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could shorten the latency at this point is by *replacing the interrupt vector itself* by our code. Be warned that this should be immensely distasteful to anyone who values clean software design. But it is possible, and I will show you how.

The layout of the ATmega328P vector table can be found in the datasheet, section *Interrupts*, subsection *Interrupt Vectors in ATmega328 and ATmega328P*. Or by disassembling any program for this chip. Here is how it looks like. I am using avr-gcc and avr-libc's conventions (\__init is vector 0, addresses are in bytes) which are different from Atmel's.

```
address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

```

Each vector has a 4-byte slot, filled with a single `jmp` instruction. This is a 32-bit instruction, unlike most AVR instructions which are 16-bit. But a 32-bit slot is too small to hold the first part of our ISR: we can fit the `sbic` and `sbi` instructions, but not the `rjmp`. If we do that, the vector table ends up looking like this:

```
address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ sbic PIND, 2    │ the first part...
 0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

```

When INT0 fires, PIND will be read, the relevant bit will be copied into GPIOR0, and then the execution will fall through to the next vector. Then, the ISR for INT1 will be called, instead of the ISR for INT0. This is creepy, but since we are not using INT1 anyway, we will just "hijack" its vector for servicing INT0.

Now, we just have to write our own custom vector table to override the default one. It turns out it is not so easy. The default vector table is provided by the avr-libc distribution, in an object file called crtm328p.o that is automatically linked with any program we build. Unlike library code, object-file code is not meant to be overridden: trying to do that will give a linker error about the table being defined twice. This means we have to replace the whole crtm328p.o with our custom version. One option is to download the full avr-libc source code, do our custom modifications in gcrt1.S, then build this as a custom libc.

Here I went for a lighter, alternative approach. I wrote a custom crt.S, which is a simplified version of the original from avr-libc. It lacks a few rarely used features, like the ability to define a "catch all" ISR, or to be able to terminate the program (i.e. freeze the Arduino) by calling `exit()`. Here is the code. I trimmed the repetitive part of the vector table in order to minimize scrolling:

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

.weak __heap_end
.set  __heap_end, 0

.macro vector name
    .weak \name
    .set \name, __vectors
    jmp \name
.endm

.section .vectors
__vectors:
    jmp __init
    sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
    sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
    vector __vector_2
    vector __vector_3
    [...and so forth until...]
    vector __vector_25

.section .init2
__init:
    clr r1
    out _SFR_IO_ADDR(SREG), r1
    ldi r28, lo8(RAMEND)
    ldi r29, hi8(RAMEND)
    out _SFR_IO_ADDR(SPL), r28
    out _SFR_IO_ADDR(SPH), r29

.section .init9
    jmp main

```

It can be compiled with the following command line:

```
avr-gcc -c -mmcu=atmega328p silly-crt.S

```

The sketch is identical to the previous one except that there is no INT0\_vect, and INT0\_vect\_part\_2 is replaced by INT1\_vect:

```
/* Interrupt service routine for INT1 hijacked to service INT0. */
ISR(INT1_vect)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

```

To compile the sketch, we need a custom compile command. If you have followed so far, you probably know how to compile from the command line. You have to explicitly request silly-crt.o to be linked to your program, and add the `-nostartfiles` option to avoid linking in the original crtm328p.o.

Now, the reading of the I/O port is the very first instruction executed after the interrupt triggers. I tested this version by sending it short pulses from another Arduino, and it can catch (although not reliably) the high level of pulses as short as 5 cycles. There is nothing more we can do to shorten the interrupt latency on this hardware.

# Answer
> 6 votes
The interrupt is being set to fire on a change, and your test\_func is set as the Interrupt Service Routine (ISR), called to service that interrupt. The ISR then prints the value of the input.

At first glance you would expect the output to be as you have said, and alternating set of high lows, as it only gets to the ISR on a change.

But what we're missing is that there is a certain amount of time that it takes for the CPU to service an interrupt and branch to the ISR. During this time the voltage on the pin may have changed again. Particularly if the pin is not stabilised by hardware de-bouncing or similar. Because the interrupt is already flagged and hasn't been serviced yet, this extra change (or many of them, because a pins level can change very quickly relative to the clock speed if it has low parasitic capacitance) will be missed.

So in essence without some form of de-bouncing, we have no guarantee that when the input changes, and the interrupt gets marked for servicing, that the input will still be at the same value when we get to reading its value in the ISR.

As a generic example the ATmega328 Datasheet used on the Arduino Uno details interrupt times in section 6.7.1 - "Interrupt Response Time". It states for this microcontroller the minimum time to branch to an ISR for servicing is 4 clock cycles, but can be more (extra if executing multi-cycle instruction at interrupt or 8 + sleep wake time if the MCU is in sleep.)

As @EdgarBonet mentioned in comments, the pin could also similarly change during ISR execution. Because the ISR reads from the pin twice, it would not add anything to the test\_array if it encountered a LOW on the first read and a HIGH on the second. But x would still increment, leaving that slot in the array unchanged (possibly as uninitialised data depending on what was done to the array earlier).

His one line ISR of `test_array[x++] = digitalRead(pin);` is a perfect solution to this.

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


title: Arduino Based Solid State Drive

text:
# Question
Title: Arduino Based Solid State Drive
I've searched high and low for something to get me on the right track, it's making me think it might not be possible.

Basically, I want to create a cheap SSD using Arduino (or another microcontroller if it is too weak). I know I would have to implement the SATA protocol on the device and an OS driver for the disk drive. Assuming I could jump those two hurdles, what else would bar me from implementing a rudimentary SSD? I'm not even talking about full production quality, just a SATA wire coming from a mother board plugged into a socket on a breadboard. Do I need flash storage or would I need another kind of chip to handle the data needs?

# Answer
The good news is that SATA drivers are fairly generic so you don't have to write the OS side. The bad news is everything else.

*just a SATA wire coming from a mother board plugged into a socket on a breadboard*

Let me stop you there. The minimum data rate for SATA is sufficiently high that you need a PCB. If you try and do this with wires or breadboards it will simply not get through; it will be lost to parasitic capacitance.

(Many years ago as a student I tried to do something vaguely similar with a wire-wrap board. At just 20MHz you could see a clean signal go in one side and a noisy unreadable mess come out the other side. Actually seeing it on a scope drove home the importance of shielding.)

*Do I need flash storage or would I need another kind of chip to handle the data needs*

Where would you put the data otherwise? It might be an entertaining first step to create a read-only drive with constant contents, but it's not very useful.

You need a chip with a SATA interface. This will almost certainly be an ARM and almost certainly *not* in DIP. I can't remember at the moment whether SATA master and slave "PHY" interfaces are different or whether it's all defined in software, someone else can answer that.
> 4 votes

---
Tags: system-design
---


# Question
Title: ISR executes even though an interrupt is not triggered
I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.

```
typedef void (*funcptr)(void);
TPrioQueue *queue = NULL;

void int1ISR() {
  if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
    enq(queue, (void*) int1task, 1);
}

```

Next, I execute the function in loop() by:

```
typedef void (*funcptr)(void);

void loop(){
  funcptr func = (funcptr) deq(queue);
  if (func != NULL)
    (*func)(); // Stuck in a loop
}

```

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?

When I remove the line below, the ISR works properly.

```
enq(queue, (void*) int1task, 1)

```

The relevant sections of the code:

```
int debounce(unsigned long *debTimer) {
  unsigned long tmp = *debTimer;
  unsigned long currTime = millis();

  if ((currTime-tmp) > 500){
    *debTimer = currTime;
    return 1;
  }
  else
    return 0;
}

// Flashes LED at pin 6 five times at 2 Hz
void int1task(){
  for(int i=0; i<5; i++){
    digitalWrite(6, HIGH);
    delay(250);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void setup() {
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

```

Code I used for the queue

Here is the schematic I am using:

# Answer
> 2 votes
After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the `enq` and `deq` functions, which is a **must-have** if you use any of these functions from **within an ISR**.

I would suggest the simplest changes to these functions as follows:

```
void enq(TPrioQueue *queue, void *item, int priority)
{
    TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

    if(newEntry != NULL)
    {
        newEntry->item=item;
        newEntry->prio=priority;
        newEntry->prev=NULL;
        newEntry->next=NULL;

        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        if(queue->head==NULL)
            queue->head=newEntry;
        else
        {
            // Find insertion point.

            // First special case: Item at head has lower priority
            if(queue->head->prio > newEntry->prio)
            {
                // Insert item at the start of the queue.
                newEntry->next=queue->head;
                queue->head->prev=newEntry;
                queue->head=newEntry;
            }
            else
            {
                // Find your insertion point
                TPrioQEntry *trav= queue->head;

                while(trav->next!=NULL && trav->prio < newEntry->prio)
                    trav=trav->next;

                newEntry->prev=trav;
                newEntry->next=trav->next;
                if(trav->next != NULL)
                    trav->next->prev=newEntry;

                trav->next=newEntry;
            }
        }

        queue->itemCount++;
        // Protect against concurrent accesses stops here
        SREG = sreg;
    }
}

void *deq(TPrioQueue *queue)
{
    // Protect against concurrent accesses starting here
    uint8_t sreg = SREG;
    cli();
    // Return NULL if queue is empty
    if(queue->head == NULL)
    {
        // Protect against concurrent accesses stops here
        SREG = sreg;
        return NULL;
    }

    void *ret=queue->head->item;
    TPrioQEntry *tmp=queue->head;

    if(queue->head->next!=NULL)
        queue->head->next->prev=NULL;

    queue->head=queue->head->next;
    free(tmp);

    queue->itemCount--;

    // Protect against concurrent accesses stops here
    SREG = sreg;

    return ret;
}

```

# Answer
> 1 votes
Although you did not clearly mention nor show your wiring, it is possible the problem comes from here.

Barring **real concurrency issues** with your queue implementation, which I already mentioned in another answer, for which fixes have to be implemented anyway, there are two potential wiring problems in your circuit:

1. You use **INT1** interrupt; that means you must connect your button to **PIN 3** for a UNO, any other pin won't work.
2. You did not specify `pinMode(3, INPUT_PULLUP)` in your `setup()`, which means **you MUST use an external pullup resistor** to force a `HIGH` value, and connect the other pin of the button to `GND` (or conversely: put a pulldown resistor and wire the other pin to `5V`); otherwise, while the button is left unpressed, you will have a **floating input**, which means its value will vary randomly between HIGH and LOW, triggering your `int1ISR` many times when you don't expect it.

The simplest way to solve point 2 (floating input) is to use internal pullup resistors:

```
void setup() {
  pinMode(3, INPUT_PULLUP);
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

```

and connect one button pin to Arduino PIN 3, and the other button pin to `GND`.

That will remove floating input and its consequences.

# Answer
> 0 votes
ISRs have flags, typically an enable flag and a pending flag.

The enable flag needs to be set true for the interrupt to occur at all.

The pending flag is set when the interrupt event occurs.

Within the interrupt function, the pending flag must be cleared,

otherwise the the interrupt function will immediately be executed again (and again and again and ...)

---
Tags: arduino-uno, interrupt, c, isr, pointer
---


# Question
Title: Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level
I have some code that generates random numbers on the Arduino, it then sends these random numbers firstly, using `Serial.print(float data,int lenght)` and as a floating point number using the following function

```
void send_float (float arg)
{
  // get access to the float as a byte-array:
  byte * data = (byte *) &arg;

  // write the data to the serial
  Serial.write (data, sizeof (arg));
  Serial.println();
}

```

I then receive this data using python, take the absolute difference of the two values, discard any differences less than the length with which I send the string and output the rest to the screen.

I observe two things, a) Fluctuations of the order with which I send the data (ie. if I send to 6 decimal places then I see fluctuations of ~1e-6), this is reasonable and b) I see fluctuations of absolute value 1e-8 or lower **independent** of what accuracy I send the string.

Even if I send the string to 11 decimal places, when I compare against the float I see fluctuations up to but not above 1e-8.

Why? This doesn't make any sense. My full code is actually the answer to an old unanswered stack exchange question

# Answer
> 1 votes
This is a somewhat dumb question but, in case anyone else searches it as pointed out:

> The precision of a float is around 7.2 decimal digits. en.wikipedia.org/wiki/Single-precision\_floating-point\_format – BrettAM

So in python the number goes float -\> double -\> decmial, whereas on the arduino the number goes float -\> decimal. The additional step of the double in the case of python causes the discrepancies. But anything after the 7th decimal place is nonesense anyway.

---
Tags: serial, python, float
---


# Question
Title: Powering Arduino Uno R3 with battery packs
I am using Arduino Uno R3 with MPU 6050 for a personal project. MPU 6050 is being powered by the 3.3V supply pin in the Arduino board.

In order to make the sensor mobile, I ordered this battery, which has one power output of 5V 1Amp that I plan on plugging into the Uno's USB Power/Data Outlet.

I know that when plugged into the computer via the same USB port, around 5V 500 mA is supplied. I was wondering if someone could tell me, **whether the 1A battery that I ordered would burn my board or not**.

**Also, is there a built in fuse inside this board?**

# Answer
> 4 votes
Power sources like batteries and wall warts are **voltage sources**: they will deliver a fixed voltage, more or less. The current that they supply will be determined by the load you attach to them.

The "Amps" listed on a power supply is not how much current it **will** put out, it is the **maximum** current that the manufacturer has decided it **can** put out safely, without acting funny or overheating. So when you read that the USB port on a computer supplies 5V and 500mA, that means that it will supply 5V and **up to** 500mA. If you draw more than a 500mA current from your USB port, you would exceed the max current rating of the USB port. USB ports usually have an emergency shut-off mechanism built in, so they would just turn off if you drew more than 500mA out of them. I wouldn't try it though :). Your battery seems to have pretty similar safety features: "Super protection: overshoot, over-discharge, short circuit, over voltage, leakage, and many other protective functions".

If you had a 5V 20 Amp power supply, it will act the same as the USB port power supply, except it will be able to handle putting out much more current. As long as you don't exceed a voltage source's max current rating, **the amount of current that a voltage source puts out depends on how much current the load draws, not on the voltage source.** For example, a resistor will draw a current in Amps equal to the voltage supplied to it divided by the resistance (I=V/R), via Ohm's Law. For microcontrollers, you can often find their current draw on their datasheet: your MPU 6050 with the Gyro + Accel running has an operating current of 3.8mA when you give it ~3.3V. An Arduino Uno draws about 80mA by itself, though I don't think this includes the 3.3V power regulator on the 3V3 pin. So you're looking at somewhere a little over 84mA (=0.084A) in total. Your battery can supply 2.5A or 1A depending on which of its ports you use, so you are nowhere near exceeding the battery's max current rating, which is a good thing.

There are no fuses built in to the Arduino Uno R3. If you exceed its maximum current limitations, you will mess it up. There's a ruggedino available with more safety features if you're worried about frying your arduino. But as long as you're careful you should be fine with a standard R3.

# Answer
> 1 votes
The battery will be fine; the 1A rating is just a maximum, if your device only wants up to 500mA then it's got spare capacity, is all.

The battery appears to have in-built short protection etc, so better than a fuse..

---
Tags: arduino-uno, power
---


# Question
Title: Can I mix 22awg and 26awg hookup wire in the same circuit?
I'm still fairly new to Arduino projects, and am only just now getting into building circuits where I want to cut and place my own hookup wire instead of using the precut jumper wires. I inherited some supplies from a friend who abandoned the hobby, and about half of the wire he gave me is 22awg and the other half is 26awg. All of it is solid core copper. Is it ok to mix wire gauges like this in the same circuit/project?

# Answer
> 1 votes
Assuming you won't ever put more current through it than the 26AWG wire can handle, you'll be safe.

---
Tags: arduino-uno, wires
---


# Question
Title: External access to Yun - request not recognised as HTML
I am trying to access my Yun externally.

My router recognises traffic on Port XXXXX and forwards it to my Arduino Yun.

I have the below code working internally and now trying to adapt this to work for external (adapted from http://arduino.cc/en/Tutorial/TemperatureWebPanel).

To access the Arduino Yun over the network I type:

```
http://XXX.XXX.XXX.XXX:XXXXX/arduino/on

```

When using this script locally, i.e. `myArduinoName.local/arduino/on`, the onboard light turns on (and off if URL changed accordingly).

Adapting this working code, I have changed to "`noListenOnLocalhost`" and put in my port number (XXXXX).

The code is reached (see below for the response).

```
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

// Listen on default port 5555, the webserver on the Yun
// will forward there all the HTTP requests for us.
YunServer server(XXXXX);
String startString;
long hits = 0;

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

  // Bridge startup
  pinMode(13,OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(13, HIGH);

  Bridge.begin();
  Console.begin();

  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  //server.listenOnLocalhost();
  server.noListenOnLocalhost();
  server.begin();

}

void loop() {
  // Get clients coming from server
  YunClient client = server.accept();

  client.println("hello");

  // There is a new client?
  if (client) {
    // read the command
    String command = client.readString();

    command.trim();        //kill whitespace

    client.println(command); // why does this return a full GET request instead of "on"?

    if (command == "on") {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);
    }

    if (command == "off") {
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
    }

    // Close connection and free resources.
    client.stop();
    hits++;
  }

  delay(50); // Poll every 50ms
}

```

The response I get is (I have replaced my IP and port with X's):

> hello
>
> GET /arduino/off HTTP/1.1 Host: XXX.XXX.XXX.XXX:XXXXX Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

I expected

> hello
>
> on

So it would seem that because I'm using a different port (other than 80 or 5555) the response is no longer being interpreted as an HTTP request.

I have also tried to edit the uhttpd file via SSH to provide a specific address and port for both my external IP address and my fixed internal IP address.

Then tried to restart the device and also a uhttpd restart i.e.:

```
/etc/init.d/uhttpd restart

```

I have attempted to access the URL using my mobile phone (i.e. not on the same network).

Any ideas why my request is not being treated as HTTP?

# Answer
It works!

The changes to the uhttpd must have done the trick to listen for http traffic on a given IP/port (other than 0.0.0.0:80).

Instead of supplying a port number for the server in the code, I would surmise that the change to the config takes care of it so this, so the port number in code is no longer needed:

YunServer server(XXXXX);

should be changed back to

YunServer server;
> 1 votes

---
Tags: wifi, arduino-yun, remote-control, h-bridge
---


title: Arduino weird bluetooth module

text:
# Question
Title: Arduino weird bluetooth module
Recently I bought a BT module from eBay which was very cheap. I didn't really noticed the image and I just bought it. When it came I couldn't find any holes to solder the headers. Also the specific module is pretty rare and I couldn't find anything.

Here is an image:

How do I wire up this chip?

# Answer
> 2 votes
From the picture you posted, i was able to google and find something called a BC04-B Bluetooth serial module. It looks almost exactly like yours, and I found a diagram on how to hook it up.

I also believe that these are the serial commands you can use with it...

# Answer
> 2 votes
These Bluetooth modules are typically mounted onto another substrate, either the product board or a small PCB backplane which provides the pinouts and any additional circuitry like the pairing LED, and power- & signal-level management. They are readily available as HC-05 (master/slave) or HC-06 (slave only) with signals brought to through-holes or pins at the edge of the backplane.

---
Tags: arduino-uno, bluetooth
---


title: Arduino and ESP8266 Web server

text:
# Question
Title: Arduino and ESP8266 Web server
First things first, if there was an ESP8266 StackExchange, I would post this there.

I am setting up a web server that will programmaticly be controlled from an external Python script, and I am currently able to send this server data using this script, but I don't receive an HTTP response back when I do, so the external script crashes.

I have googled around and not found much on this, so the question is How do I, From the Arduino, using an ESP8266 send an HTML response code?

# Answer
> 7 votes
After countless Trial/error attempts, I was able to put together the proper sequence.

```
AT+CIPSEND=0,40  \\Set this for your current connection ID and payload length.
HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n
AT+CIPCLOSE=0  \\Set this for your current connection ID

```

Send these commands with the arduino, and it should exit successfully. You can also flush out the HTTP line with any other information you would like to include, as defined in the rfc2616 (HTTP/1.1) standard

---
Tags: networking, esp8266
---


title: Do Water sensors Rust?

text:
# Question
Title: Do Water sensors Rust?
I'm new to Arduino and still learning the basics. I tried reading water level by using this sensor I left it in the water for about 5 minutes then I noticed it changing color (some parts darker than other)like the water is still over it . So my question is do Water sensors really rust ? or is it my own imagination?

# Answer
> 3 votes
The color change you observed is probably caused a galvanic reaction between metals in the sensor and other metals that are present, such as the tank, piping, or dissolved metals in the water. Do not modify the parallel strips of metal on the sensor. This will render the sensor useless. To reduce the effects of galvanic corrosion, you can: 1) Reduce the current passing through the sensor. To do this, sample the sensor less frequently. For, example, sample it once every second. 2) If possible, remove sources of metal from the water. For example, replace metal pipes with PVC, and replace screws with plastic zip-ties. 3) Move the sensor further away from sources of metal. 4) Place a grounded sacrificial zinc in the water, close any other metal sources. If the water is circulating, place the zinc near the inflow opening. 5) Remove stray or electrical currents from the water. Connect the "-" pin (GND) and the water to the same ground.

# Answer
> 4 votes
Most metals will tarnish, rust, or corrode when left in water, especially in the presence of an electric current. To be safe, a water sensor should either be gold-plated or made of a conductive, insoluble, non-metallic substance.

# Answer
> 1 votes
I have that same sensor, and found a couple things to help with this issue. The first thing that I did with min was tin the contacts with solder (All 10 'sensor contacts' all the way down) and also, using the GPIO, only power it on about 1 second before I read it, and turn it off immediately after. By reducing the amount of time current is running through it, you reduce the tarnish, and the solder i tined everything with is less likely to corrode than the raw contacts.

---
Tags: sensors, hardware
---


# Question
Title: Can you query the current serial port's speed?
Is there some code I can use to find out what the a chosen serial port's speed is running at ?

# Answer
> 7 votes
There is not a top level, easy to use way. Sorry. It is probably easier to just store your chosen baud rate in a variable when you setup the serial port.

Anyway, What you can try to do for the AVR-based, hardware UARTs is undo what `Serial.begin` does to set up a particular baud rate, but its a bit of a pain. This is the code for setting the baud rate:

```
  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

```

You can find the results of this by reading the right UCSRA, UBRRH, and UBRRL registers. On an uno those are the correct register names, on an mega its UCSR0A, UBRR0H, UBRR0L for Serial, UCRS1A ... for serial1 and so on. Non-avr boards (and `Serial` on a leonardo) will be totally different.

There will be a single state for those three registers on an AVR hardware serial port for a particular board (and frequency of that board) at each baud rate. You can try and make an equation to get the original baud rate out, but I recommend just comparing the direct values with a lookup of some kind because the integer arithmetic rounding errors will make it a huge mess.

For example, on my mega UBBR0H, UBBR0L, and UCSR0A are 0, 207, 2 at 9600 baud, but they are 0, 51, 2 at 38400 baud and 0, 16, 0 at 57600 baud.

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


title: Read data from SD

text:
# Question
Title: Read data from SD
I have logged some data in my sdcard/FAT32 (format). I can read and display them on the serial monitor but additionally I want to use these data as float.

Here is my code:

```
       byte index = 0;

       Tfile = SD.open("DATALOG.TXT",FILE_READ);

       while (Tfile.available()) {

         x[index++] = Tfile.read();
         x[index] = '\0'; // NULL terminate the array
       }

```

Printing the data using:

```
   Serial.print(fileContents);

```

I receive the following float values that are correct:

```
   .63
   15.63
   16.60
   16.60
   16.60
   16.60
   etc

```

Now I want to work with values so i need to store them on a double index:

```
    double dtemp[320];
    for(index = 0, i=0; index < 320; index++, i++) {
       dtemp[i] =  fileContents[index];
       Serial.println(dtemp[i]); }

```

but i receive fault values:

```
      46.00
      54.00
      51.00
      13.00
      10.00
      49.00
      53.00
      etc

```

Any comment is welcomed !

Thank you in advance !

# Answer
You have to *parse* the character array in order to convert it to floats. There is no fast way to do this: since the Arduino has no FPU, *anything* involving floats is slow.

Unless you really have to, I would not recommend slurping the whole file into RAM. You will save memory by parsing the file on the fly. This should be as simple as calling the `parseFloat()` method of the `File` object:

```
double dtemp[320];
int i;
for (i = 0; Tfile.avalable() && i < 320; i++) {
    dtemp[i] = Tfile.parseFloat();
    Serial.println(dtemp[i]);
}
if (i < 320)
    Serial.println("WARNING: Premature end of file.");

```
> 2 votes

---
Tags: serial, sd-card, float
---


# Question
Title: /dev/cu port resource always busy on OS X 10.10
Is there any reason why is my `/dev/cu` port always busy? How can I fix that?

It happened on both Uno clone and Spark Core.

The problem is, I'm having issues doing serial communication. Where (as a programmer) I'm seeing something like dropped packets with `/dev/tty` port. I did a quick test running it on Win 7 (a loaner PC), it works fine...

The code for now is extremely simple. It waits for a command, and write a response.

```
String str = String(30);

void setup()
{
    Serial.begin(9600);
    str = "";
}

void loop()
{
    if (Serial.available() > 0) {
        char inChar = Serial.read();
        if ((inChar == '\n') || (inChar == '\r') || (inChar == 'z')) {
            str.trim();
            if(str == "READ") {
                String x = String(random(27, 45)) + "," + String(random(45, 300)) + "," + String(random(35, 250));
                Serial.println(x);
            }
            str = "";
        }
        else {
            if (str.length() < 30) {
                str += inChar;
            }
            else {
                str = "";
                str += inChar;
            }
        }
    }
}

```

# Answer
> 0 votes
Finally figured it out. I need to call Serial.flush().

> Waits for the transmission of outgoing serial data to complete.

---
Tags: arduino-uno, serial, mac-os
---


# Question
Title: How to connect two Arduino without shields?
I'm planning an Arduino system that consists of several Arduino boards. The maximum distance between the boards is about 50 meters. I want to send basic data between these, like short strings or integers. I know I could send data through ethernet cables but that requires an ethernet shield or the Arduino Ethernet board that doubles the costs. Is there a low budget way I could connect the boards using only the most basic boards (like Uno) and some other components but not a full shield?

# Answer
For long distance wired communication, look at RS-485.

> Since it uses a differential balanced line over twisted pair (like RS-422), it can span relatively large distances (up to 4,000 feet (1,200 m)). A rule of thumb is that the speed in bit/s multiplied by the length in meters should not exceed 108. Thus a 50 meter cable should not signal faster than 2 Mbit/s

You can use the MAX485 chip. It's pretty easy to work with but there's a good library as well:

https://github.com/Protoneer/RS485-Arduino-Library
> 10 votes

# Answer
There are two categories i can think of to classify comminucation features of the Arduino boards:

**Between 2 devices:**

* Serial: Easy to use and only requires 2 data lines.
* OneWire: Harder to use and slow, but uses only one data line

**Between more than 2 devices**

* I2C: You can have up to 128 devices on a network, individually addressable, but requires a master device, uses 2 data lines. this is know also as Wire.
* SPI: difficult to use, but very fast and easy device selection. uses a lot of data lines (3 + num of devices)
* OneWire: using addressed oneWire is even slower than regular oneWire, still only one data line
* SoftwareSerial: You can have several devices connected by different Serial lines, but it is slower.
* CAN: only available on the Due, and addressable

There are other methods available, but these listed only require a minimum of external hardware.

For distance ratings, see http://forum.arduino.cc/index.php?topic=82937.0 and http://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html

These data rates are directly controlled in Serial and can be tweaked in many others.
> 7 votes

# Answer
Freakduino makes some Arduino boards with built in wireless. Their long range wireless is 900 MHz and their shorter range is 2.4GHz. I think they are actually XBee radios and for programming you would use a library called chibiArduino, which is available (and documented) on the Freakduino website. When communicating wirelessly with another radio you can use Broadcast or specify a radio by it's ID which is a value you need to set in the EEPROM of the Freakduino.

Taken directly from the Freakduino site:

> The addition of an integrated wireless radio based on the IEEE 802.15.4 protocol (same radio protocol as the XBee) allows for wireless control of devices or wireless sensor data collection. Optional battery circuitry was added so that it could function as a true wireless node without any external power cables. The board is also designed to fit a ruggedized enclosure so that the design can be transported safely or deployed in an actual usage scenario without worrying about damaging the circuitry.
>
> This 900 MHz radio is a personal favorite of mine. I use it all the time because 900 MHz offers much better range compared to 2.4 GHz. The radio can output up to 10 mW of transmit power which can get a surprising amount of range. With direct line of sight, a few hundred meters would not be surprising. If additional range is needed, the modulation mode can also be changed from OQPSK to BPSK. This results in additional range at the expense of data rate, with the max going from 250 kbps to 40 kbps in standard mode.
> 5 votes

# Answer
Like you said, Ethernet shields are expensive, but you don't have to use the shield. Check out the enc28j60 for wired networking, or the ESP8266 if you would prefer wireless. Both are about $4USD. I am using the ESP8266 now and have about 8 devices talking to each other and a Raspberry Pi. It is a really great little chip! I cannot speak personally to the ENC28j60, as they are still sitting in the package on my desk.
> 0 votes

# Answer
You could use a Ethernet breakout board ($2 at Sparkfun). This lets you use the Ethernet cables but you don't have to use a full TCP/IP protocol, instead you can just hook up data pins to the breakout board, use the Ethernet to connect them, and then have them talk using serial. I use this quite a bit to place one wire sensors further from the Arduino for a strong yet cheap connection.
> 0 votes

---
Tags: arduino-uno, networking, system-design
---


title: How to program ATTiny85 running 3.3V

text:
# Question
Title: How to program ATTiny85 running 3.3V
I have a working project built around ATTiny85 on a breadboard running at 5V. Now I want to move this prototype on a PCB where it will be powered from batteries. All components used are capable of running 3.3V so I want to run the ATTiny85 at 3.3V as well.

I don't have a programmer so I use ArduinoISP to program the ATTiny. If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

# Answer
> Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Yes. But if there are *any* components on the board that *can't* run at 5V then you must provide some way of protecting them from the excessive voltage.

> If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

There are no fuses required to change the actual operating voltage of the device. There is the BOD threshold, but you can still operate the device at a higher voltage without issue regardless.
> 8 votes

# Answer
Most ideal would be to use a buffer chip (like there is on the AVR Pocket Programmer).

But in your case you could get away with just placing some resistors (1k or something) on the ISP lines. This is because if the chip is powered by 3v and you put a 5v signal on one of the pins it's clamping diodes will redirect the higher voltage to VCC, raising VCC to 5v. In your case the 5v is not necessarily a problem. But if you circuit is using e.g. 100mA, that means 100mA will go through the clamping diode. It's not designed for that.
> 0 votes

---
Tags: programming, voltage-level, attiny
---


# Question
Title: STEPPER MOTOR CONTROLLER Using LEONARDO PRO MICRO
I want to Use LEONARDO PRO MICRO and A4988 Stepper Motor DRIVER to control Nema 17 Stepper Motor.

Please let me know how to hookup these together.

Please give me a circuit for this type of assembly with Arduino code.

# Answer
> 2 votes
You can simply make a google search;

Here is some code to get you started

```
// Declaration of variables
#define Step 7     // Pin that transmits the "step" order to the board
#define Dir  6     // Pin that indicates the direction of the rotation
int vit  =   10 ;   // Speed of the rotation (smaller means faster rotation)
int sens =   1  ;  // Rotation direction (0 or 1)

void setup()
{
  pinMode( Step  , OUTPUT );
  pinMode( Dir   , OUTPUT );
}
void loop()
{
    digitalWrite( Dir   , sens);
    digitalWrite( Step  , LOW);
    // Fabrication d'un "Pas"
    digitalWrite( Step, HIGH );
    delay(vit);
    digitalWrite( Step, LOW );
    delay(vit);
}

```

Just a google search and I got on \[this site\]\[2\] which had the code I gave you. I think you can also find some libraries that can do the work for you.

in case that you need to wait less than a millisecond, `millis()` won't be useful for you; instead, use `delayMicroseconds()` which will make you wait a thousandth (at minimum) of a millisecond.

**EDIT**

For what you asked you have to first get the voltage:

```
float voltage = analogRead ( 0 )  * (3.0 / 1023.0);

```

You just have to adapt your speed relatively to the voltage. To do this, I suggest you the map function directly from Arduino site.

Be careful just because whatever you are doing, analogRead takes **100 microseconds** to get the voltage, so if you need to go very fast you can't. I suggest you to work with a different type of communication, like Serial, SPI or I2c.

---
Tags: motor, arduino-leonardo, arduino-pro-micro
---


# Question
Title: Problems with (somewhat) large boolean arrays
I am writing a simple Conway's Game of Life implementation just to get to grips with the "Nokia 3310" LCD and I am having problems with boolean arrays. I am using an (unofficial) Arduino Pro Micro 5V/16MHz

Here's the code that is causing me trouble:

```
boolean buffer[84][48];

void setup(){
  for(int i = 0; i < 84; i++){
    for(int j = 0; j < 48; j++){
      buffer[i][j] = true;
    }
  }
}

void loop(){}

```

When I upload this to the Arduino, it seemingly freezes up with the RX led on and its COM port stops working. If I want to upload any other sketch, I have to manually pull the RST pin LOW (since the Pro Micro doesn't have a reset button).

I've been playing around with the code and found out that the source of problems is this line:

```
buffer[i][j] = true;

```

It also doesn't matter if I use `true` or `false`.

I have tried debugging with Serial to the computer, but the Serial communication doesn't work at all, so I tried using an LED to find out where the problem is. I don't have any "regular" LEDs on me, so I had to try with an Adafruit NeoPixel. The outcome was quite interesting. When I comment out the problematic line, everything runs just fine, the led goes red for 500ms then it blinks white every time the problematic line would run and then it goes green and stays that way. With the problematic line in place, the LED won't do anything, even turn red, which I put much earlier in the code than the source of the problem.

Does anybody have any insights that might be useful? (Also, I really hope it is not some stupid typo, I swear I read it through about twenty times)

# Answer
According to http://arduino.cc/en/pmwiki.php?n=Reference/BooleanVariables, "Each boolean variable occupies one byte of memory." Meaning you are trying to use 4032 Bytes of RAM with your array which I assume you do not have (whatever this unofficial Arduino is -- it's likely to be less than that: the ATmega328 of the Arduino Mini has 2 kB of SRAM, the ATmega32u4 of the Micro has 2.5 kB).

You could try with a quarter of the field size for a start and see if that makes your problems go away.
> 3 votes

# Answer
Well, if each boolean takes a full byte, as fuenfundachtzig says, then you might try some bitwise hacking to fit 8 bools per byte on your own. Maybe something like this:

```
unsigned int16 buffer[84][3];  //16 bits * 3 = 48 bits, per the original example

void init_buffer()
{
    for(int i = 0; i < 84; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            buffer[i][j] = 0xFFFF;  //all TRUE: each F is hexadecimal for 0b1111 in binary
        }
    }
}

bool get_buffer(unsigned int8 i, unsigned int8 j)
{
    unsigned int16 k = 0;
    while(j >= 16)
    {
        j -= 16;  //I can do this because i and j are passed by value and are therefore separate copies inside this function
        k++;
    }
    //now k is the array index and j is the bit position inside that element
    if(buffer[i][k] & (1 << j))  //(bitwise AND with 1 shifted left by j positions, so we only care about that bit)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
    //or, if your compiler supports it, you might replace the if/else with:
    return (buffer[i][k] & (1 << j));
}

```

As for the stylistic differences between my example and yours:

* I like to completely specify my datatypes if I can. Don't rely on the compiler to do what you expect because it may have options to that effect that are set differently than you think.
* I like to use brackets for everything, even single statements, and make them obvious. That way, there's no confusion later or additional bugs because a second statement was added to what used to be a bracketless single without adding the brackets.
    + The only exception to that is when I'm writing a series of almost-identical if's and I put both the if and the action on the same line, all aligned so that the subtle differences line up and become obvious.
> 2 votes

---
Tags: arduino-pro-micro
---


title: 7 segment LEDs on wood face

text:
# Question
Title: 7 segment LEDs on wood face
I'm not sure this is right place for this question, but does anyone have any idea how a 7 segment display is projected or embedded in wood for products like this?

Full product info at http://www.amazon.com/Cube-Wood-LED-Alarm-Clock/dp/B00D6DI0LE

Another example:

From: http://www.selectism.com/2013/11/27/a-wooden-led-alarm-clock-and-wireless-bluetooth-speaker-from-gogroove/

# Answer
This is done by carefully placing a layer of wood veneer over the 7-segment displays. The veneer is thin enough to let the light pass through. I wouldn't be surprised if some manufacturers use brighter than normal LEDs to make the display easier to see. Here is a video detailing an example.

It is also possible to simply drill out the wood to make it very thin where the 7-segment displays go. Here is an example of drilling the solid wood to be very thin.
> 10 votes

---
Tags: led, display
---


# Question
Title: Multiple shields on one Arduino/Linker base shield
I'm using an Arduino Uno R3 along with an Ethernet shield as well as the linker base shield for interfacing with three linker modules, light, temperature and some LEDs as I believed this would be simpler than using a breadboard and look neater. Are there any problems I'm likely to run into regarding compatibility or power consumption? It's a prototype for a hydroponic garden automation system. As a secondary, are there any c02 sensors under $60 available on the market?

# Answer
I would recommend looking up the power consumption specs on the datasheets for each shield. Then determine whether the current used by all of the shields exceeds the limits for any given pin and for the board as a whole. I highly recommend the following article: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/
> 2 votes

---
Tags: arduino-uno, sensors, power, ethernet
---


title: Build arduino with windows command line

text:
# Question
Title: Build arduino with windows command line
Can someone explain, step by step, along with all software I must use for using Windows command prompt to build an Arduino sketch (.ino file )?

I've followed these steps but I can't.

# Answer
> 4 votes
The command line interface of the Arduino IDE is described in this document

https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

For example, this command will compile and upload the Blink example to my Arduino Leonardo

```
./arduino --upload --board arduino:avr:leonardo --port /dev/ttyACM0 --verbose examples/01.Basics/Blink/Blink.ino

```

Foot note: with IDE 1.6.0, there is an experimental version of the IDE for recent MacOSXs. It doesn't yet support the command line. If you need the command line on Mac, use the recommended version. This will be fixed with 1.6.1

---
Tags: arduino-uno, led, arduino-ide, compile
---


# Question
Title: Can ZigBee API and ZigBee AT work together in the same network?
I'm currently trying to make 3 arduinos talking to each other with ZigBee, and it's kinda working. But I currently use AT mode on the Bees and it's a little bit harsh when I have to switch the destination address in the Coordinator of the network (1 Coordinator and 2 Routers)

Can I put the Coordinator in API mode (to make it easier to switch addresses with xbee-api for Arduino) but still be able to communicate with the AT routers and be able to send/receive data from them?

Thanks for your answer :)

# Answer
> 0 votes
My question has been answered on Stack Overflow, if you ask

https://stackoverflow.com/questions/28765288/can-zigbee-api-and-zigbee-at-modules-work-together-in-the-same-network

---
Tags: arduino-uno, xbee
---