title: How can I use a 'Global' class object?

text:
# Question
Title: How can I use a 'Global' class object?
I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged. Here is the pseudocode code to describe my question:

```
//all of the code below are in the same ino file.
class Animal{
public:
  bool alive = false;
  Animal (bool liveStatus){
    alive = liveStatus;
  }
}

Animal dog(false);
Animal cat(false);
Animal lion(false);
Animal animalArray(dog,cat,lion);

void setup(){

  for (int i=0;i<3;i++){
    Animal current_animal = animalArray[i];
    current_animal.alive = true;
  }
  //here when I print each animal's alive flag is 'true'
}

void loop(){
  for (int i=0;i<3;i++){
         // here the alive flag of each animal is still false  , they should be all true!!
  }

}

```

It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .

Thanks for helping me ..

# Answer
> 1 votes
Your problem here is that `Animal current_animal = animalArray[i];` is making a whole new Animal object that starts as a copy of `animalArray[i];`, but after that the two are no longer associated. Then when you call `current_animal.alive = true;`, you are not actually changing the animal in `animalArray[i]` anymore.

The simplest way to fix this is to make `current_animal` a reference to the object you pick out of the array, although a pointer would work the same way. With this code:

```
Animal& current_animal = animalArray[i];
current_animal.alive = true;

```

`current_animal` becomes a reference to `animalArray[i]`, instead of a copy. Then operating on `current_animal` changes the same data that is stored in `animalArray[i]` like you intend.

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


title: LCD Display hangs the computer

text:
# Question
Title: LCD Display hangs the computer
I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.

When I tried this I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.

When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.

I'm on OS X Yosemite. Why this can be happening and how can I fix?

Note: Computer is hanging as soon as the Arduino usb cable connected.

# Answer
Sometimes my system hangs in the way you describe ("hanging as soon as the Arduino usb cable connected") if I mistakenly connect the +ve and -ve supply lines to an i2c device the wrong way round.
> 0 votes

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


# Question
Title: Problems splitting a string to get authentication and command
Good afternoon,

In a nutshell I'm having some difficulty with splitting and returning part of a string.

Essentially I'm working on the code for transmitting a password (24 character string) and command (string) in a single packet. However, the 'get\_command' function is only returning the first character of the string (T) as opposed to the whole string (T1) and I'm not sure why. Any help would be greatly appreciated. Thanks in advance.

The entire sketch is below so you should be able to just drop it in and compile.

```
char *received_data = "KkV3vKvLgC4PdBZRs5kkKM86T1";
char *password = "KkV3vKvLgC4PdBZRs5kkKM86";

int authenticate_transmission(char *data) {
    if(strncmp(data, password, 24)) {
        Serial.println("no match");
        return false;
    } else {
        Serial.println("match");
        return true;
    }
}

char *get_command(char *data) {
    char command[3];
    strncpy(command, data + 24, 3);
    // Fine here
    Serial.println(command);
    return command;
}

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

void loop() {
    // test received data - message is T1 at the end.
    if (authenticate_transmission(received_data)) {
        char *command = get_command(received_data);
        // But just prints out first char when returned from a function
        Serial.println(*command);
    }
    delay(10000);
}

```

# Answer
The `command` array created inside `get_command()` is local data. That means it's only available while that function is being executed.

However, you're returning a pointer to it. That means when you're trying to use `command` afterwards from inside `loop()`, you're trying to refer to data which has been deallocated. By that point, it's getting used for something else.

There are various solutions to this. A fairly simple approach would be to have the caller allocate the `command` array, passing a pointer to it into `get_command()`. For example:

```
void get_command(char *data, char *command) {
    strncpy(command, data + 24, 3);
}

```

From `loop()`, you would call it like this:

```
char command[3];
get_command(received_data, command);

```

The `command` array is still local data in this case. However, it's local to the `loop()` function (or wherever else you put that code). That means it will still be available when `get_command()` is called.
> 1 votes

# Answer
The direct issue is you have a dereference operator (`*`) in the loop that you don't need:

```
Serial.println(*command);

```

This causes it to pass **only the first character** to `Serial.println()` instead of the pointer to the memory location. That's the first issue.

Like Peter mentioned, the string gets deallocated when returned from the `get_command()` function. It's undefined behavior, but it's luck that it worked the way it did.
> 1 votes

---
Tags: arduino-uno, c, string
---


title: Micro not detected, can't reset

text:
# Question
Title: Micro not detected, can't reset
I just picked up a new Arduino Micro for a project, but the first time I tried to upload to it, things went terribly wrong. The USB cable was loose, so the power light kept blinking on and off. When I did get it stable, I accidentally had 'Uno' selected under 'Tools-\>Board'. I think this was the source of the problem.

I'm aware that the solution for these kinds of problems is to try to upload some simple code while in bootloader mode, but pressing reset shortly after pressing the Upload button. But this board doesn't even respond when I press reset. I have tried it with both the on-board button and with an externally button linking RS to ground.

Furthermore, the board doesn't show up in my Device Manager, not even as an "Unknown Device". The device managed doesn't even refresh when I plug it in.

I know the connection is okay because the power light is on. And I know it's not a driver issue or an issue with the port, because I have no trouble getting a different Micro recognized.

The only thing I haven't tried is burning the bootloader through ICSP, since I don't have the right cable. Is there anything else I can try, or is this just bricked?

Thanks, everyone

# Answer
> 1 votes
This is probably way to late, but with newer editions of the Micro you have to "double-press" the reset (input).

I have had some experiences today where playing with low-power modes that shuts down the usb interface, and the only way I got it back was activating the reset input twice fast, and then uploading a new scetch (this time with a 10sec delay before any usb-chaning stuff takes place!)

Richard

---
Tags: bootloader, reset
---


title: Arduino uploading to the wrong port

text:
# Question
Title: Arduino uploading to the wrong port
I purchased a half dozen fake Arduinos hoping to build a bunch of projects without paying a fortune. I have all the drivers installed, and the port shows up in the Arduino IDE. The problem is when I try and upload the code I get the following error:

> can't open device "/dev/cu.wch": No such file or directory

I played around a little and tried running:

```
sudo ln -s cu.wch\ ch341\ USB\=\>RS232\ 1a1220  cu.wch

```

After running this a new port shows up called `cu.wch`, and if I select that it works.

The issue is the Arduino's port is `cu.wch ch341 USB=>RS232 1a1220`, but for some reason the IDE is trying to write to `cu.wch`. By linking the folders I can fix this but since it is a hack every time I restart my computer I have to rerun the command. Is there a way I can either rename the Arduino port or permanently link the folder?

*I am using OSX 10.10 and Arduino IDE v1.6.3*

# Answer
> 1 votes
I would guess the problem is the IDE not properly handling device names containing spaces. Consider your symlink a workaround rather than a hack - unless you want to repair the IDE itself.

# Answer
> -1 votes
You must download the CH431 drivers to your computer and restart. This will solve your problem. Google these drivers, you should be able to find them. If not, let me know and I can send you a link to my drive.

---
Tags: arduino-ide, uploading, mac-os
---


# Question
Title: How to call URL with Arduino Ethernet shield?
I'm working on Arduino and Ethernet shield.

I need to call a URL. How can do it? (This URL is HTTP API to send an SMS to my phone).

1. url: http://api.clickatell.com/http/sendmsg?user=mohammed.atha&password=\********&api\_id=3539384&to=\********&text=hello

# Answer
You need to use the **EthernetClient**. link

The exemple using your API call is:

```
if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
}

```

Full example from Arduino.cc docs:

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}

```
> 2 votes

---
Tags: arduino-uno, arduino-mega, shields, ethernet
---


# Question
Title: Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS
I am using an Arduino UNO that is connected to an Arduino GSM shield (http://www.arduino.cc/en/Main/ArduinoGSMShield).

Now, I want to connect the SparkFun Venus GPS module to this combination. (\*unfortunately due to my rep I can only post two links)

The Venus GPS works fine with the Arduino UNO by itself, but I am having some trouble getting the GPS module to communicate with the Arduino when the GSM shield is stacked on top.

The GPS powers on and begins blinking (which means it has a lock), but the serial monitor is not showing any information.

Coming from the programming side of things, I really don't understand much about electronics, so please pardon me if I am missing something basic here.

Based on what I've managed to figure out so far, I think it has something to do with the shield requiring 5V operating voltage and the Venus operating at 3.3V.

I think that when the GSM shield is plugged in, its expecting a 5V input, but the Venus GPS is only capable of sending a 3.3V signal. Furthermore, any other 5V sensors that I am currently using don't have any problems communicating with the UNO through the GSM shield.

So, I actually have two questions:

1. Is this assumption correct or could something else be the cause of my issue?
2. If this is correct, could I use something like this logic level converter (https://solarbotics.com/product/50550/) to step up the Venus GPS input signal?

Thank you in advance for any help and guidance you are able to provide.

# Answer
> 1 votes
I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield.

The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS. It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield.

---
Tags: gsm, gps
---


# Question
Title: Powering arduino uno from Car's reverse light?
I am making a reverse sensing alarm system. I am using a HC-SR04, arduino UNo and a piezo buzzer. The programming was a success however i will like this circuit to be powered when the reverse gear is shifted into place. So I am thinking to power the V in of the UNO with the 10V from the reverse bulb socket receives. However I think the amperage sent to this bulb is too much for my UNO. What should I do ? and Does anyone have any other recommendations to power the UNO in such a scenario?

# Answer
Power the Arduino in parallel with the bulb. Take the V+ wire running to the reverse light and the frame ground. The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame. Or you can just splice the light bulbs ground wire. When powering the circuit in parallel you do not have to worry about the amperage draw of the light. By a barrel jack connector like this connector from spark fun you can buy these cheaper elsewhere just a 2.1mm barrel jack connector. Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack.

As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug. If everything works don't scramble to fix it, but be aware it exists.
> 2 votes

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


# Question
Title: Not sure if programmer or ATMega is burned
some time ago i tried doing this with my original arduino uno r3. I guess i had to plug the power cables in wrong order(i think it's called reversing polarity) because my arduino stoped working. It turns on (the power diode is on) but i cannot upload any sketch on it. I'm thinking about changing the ATMega chip but, before i do that i want to be certain that it's the chip issue ,not the programmer. I have another arduino uno, and i heard that i can upload sketch with it to another uno. So my idea is, if i do this i will be able to say whether it's the programmer or the chip issue. The only problem is that i don't know how to do this and i wasn't able to find any reasonable tutorials online. Please tell me what to do. Many Thanks, Jan

# Answer
> 0 votes
The Arduino IDE ships with a built in `ArduinoISP` sketch, and there is a very detailed tutorial with wiring diagrams etc on the Arduino site.

---
Tags: arduino-uno, programming, power, motor
---


# Question
Title: Android Studio project for Redbearlab BLE Shield apps
To interact with its BLE shield, Redbearlab published sample Android apps in the Play Store. The sources for the apps are available on GitHub. How can I build them in Android Studio?

# Answer
It was much simpler than expected to put together the Android Studio projects. They are on GitHub now.

Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.
> 0 votes

---
Tags: shields, bluetooth
---


# Question
Title: What are the advantages of "Arduino compatible" boards
There are countless boards called "Arduino compatible board". Some of them have specialized hardware features such as WiFi, SD card readers etc., but most of them seem like plain Arduino copies to me.

Sure, they are a bit cheaper, but for me the price difference doesn't make me favor the money I'd safe over the potential issues I have yet to discover.

**Question:** What are the benefits (or disadvantages) of Arduino compatible boards *(the ones without the "extras")* in general? Do you know an Arduino compatible board that you would recommend for some extraordinary features?

# Answer
> 2 votes
Arduino compatible means that you would be able to use the boards directly with the Arduino IDE and you can use most of the libraries and examples that come for the official Arduino Boards.

The official Arduino boards comes with a standard set of features that are infinitely expandable, but sometimes you have constraints for a project and you need a board that you can easily adapt to a project, the compatible boards come handy in those place. For example, you can use Ardupilot to control UAV's and has a lot of sensors on it with a very small form factor but you can still code it with the Arduino IDE, you can use Femtoduino (which is an arduino board the size of a coin) for very small projects.

Another simple reason for using the compatible boards is that a lot times they are cheaper than the official Arduino Boards (see Sparkfun Redboard)

You should be able to use any Arduino compatible boards without any problems but it would be better to go with a reputable supplier rather than a supplier in China to ensure that you get a good board that works without any problems.

# Answer
> 4 votes
While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - **see here - Logo** and here **Trademark** and here **What makes an Arduino board an Arduino?** and FAQ

As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim.

---

As karan notes, some Chinese sourced Arduino compatibles "have issues".
however, I have had no problems at all with Arduino compatibles manufactured and supplied by **this Chinese supplier**. As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices - usually in batches of 10. As you will see - Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!
Uno compatible **here** is $3.80 in 10s. The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers.

NB: (1) I have NO commercial connection with this company except as a very happy customer.
(2) I'd expect you to have no problems with these or other products from them but I of course have no responsibility for what they sell.

---
Tags: hardware
---


# Question
Title: Can I use custom ethernet shield with standard libraries?
I would like to make a custom ethernet card that uses the enc28j60 like this: DIY Ethernet card

but first I would like to know if I can use the standard libraries which can be used with the ethernet card which is in the market like this: ENC28J60 ethernet module

# Answer
The libraries don't care whether or not you're using a shield, only that you're using a device they support and that you've wired it up how they expect (or that you've modified the library to use the actual wiring you're using). So find a library that supports the ENC28J60 and knock yourself out.
> 1 votes

---
Tags: library, ethernet
---


# Question
Title: Is it possible to program Arduino UNO with USB/TTL adapter withouth connection Vcc
For some strange reason my Arduino UNO clone board occasionally cause my Mac to reset, when I connect the usb cable. Possibly a power problem in Arduino or the USB hub.

Is it possible to program Arduino UNO with USB/TTL adaptor withouth conncecting the Vcc and GND pins (RX/TX and DTR only.)

# Answer
> Is it possible to program Arduino UNO with USB/TTL adaptor without connecting the Vcc and GND pins (RX/TX and DTR only.)

No.
As a minimum you need to add ground as well - even if the Mac is battery powered. Serial port signals are ground referenced so removing the ground would prevent operation.

Operation is possible without deriving Vcc from the USB port, but you will then need to derive Vcc from some other source.

If connecting ground alone causes your Mac to reset you have a serious system problem which may damage your Mac and which possibly may be dangerous to you.

Presumably you are NOT using an external power supply for the UNO.
In case you are: If the power supply for the UNO is AC mains powered it should be connected to the same mains outlet as the Mac. If the programmer powerpack is intended to be grounded but is not powered from a grounded socket AND using a 3 wire mains lead (ie with a ground pin and wire) then it s possible in some cases for the programmer to float at half mains voltage with a high impedance capacitive connection to mains. This is not **usually** dangerous to people but can cause minor nuisance shocks. It can destroy equipment (ask me how I know :-( .)
If you have a DMM (digital multimeter) set it to an AC voltage range greater than your local mains voltage and measure the AC voltage from a known ground (such as a water tap in most cases) and the programmer power supply (either wire or jack terminal). If you measure a voltage of about 50VAC with 100 VAC mains or about 115 VAC with 230 VAC mains then the power supply MUST be operated with a 3 wire mains cord and grounded power socket OR a ground lead from mains ground to power supply output ground.

If the Mac is battery powered and you have reset problems then something is wrong with connections or signal levels. You may be feeding voltage back onto the USB lines or loading the too heavily or ... ?
> 2 votes

# Answer
If you power the board with an external source of electricity (e.g. a battery), it's possible. But as it can force your Mac to reset, it will possibly damage your battery.
> 1 votes

# Answer
It's possible the reboot isn't a hardware issue, short circuiting, but some kind of operating system issue such as a faulty driver, or conflicts... Best to have a look at the Console after a reboot to see if there are any notes here, or try the same Arduino on another Mac or PC.
> 1 votes

# Answer
It is a bit of work, but it is possible to use a couple of optoisolators to build a circuit that will electrically isolate the MCU from the serial adapter.

You should still figure out why your computer resets though, as it may not be related to the Arduino at all (e.g. maybe the cable is bad).
> 1 votes

---
Tags: arduino-uno, programmer
---


title: Ask for available ip on ethernet shield

text:
# Question
Title: Ask for available ip on ethernet shield
Is there any way so an ethernet shield to ask the router for an available ip address? For example to ask for an ip an the router to return 192.168.1.2 if it is available. I am asking it because if we set the ip programmatically and it is attached to another device we gonna have problem.

# Answer
Using the DHCP (Dynamic Host Configuration Protocol) you can obtain an IP address dynamically from a DHCP server (which a router usually also is), without having to hardcode it into the firmware of the Arduino, thus enabling it to work on different networks.

There is also a library for that: http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter. It's an extension of the official Arduino Ethernet library, written for the Arduino Ethernet Shield, but you'll likely find implementations of DHCP in many Ethernet libraries (I am using the EtherCard library) because it's an important feature to be able to connect to a network without a statically assigned IP and "only" requires UDP (on top of IP).

For e.g. the Ethernet library you call the `begin` function either with only the MAC address of your device or with MAC and IP address:

```
Ethernet.begin(mac);
Ethernet.begin(mac, ip);

```

In the first case it will use DHCP to obtain an IP address dynamically, in the second case it will use the static IP address you provide. Be warned that the second case, due to the needed implementation of DHCP, will increase the size of the compiled binary significantly.
> 0 votes

---
Tags: ethernet
---


# Question
Title: Converting live vocals to discrete signals
I would like to augment a live music performance by displaying an specific LED for any given musical note.

**For vocals:** Rather than attempt to process the audio using the Arduino board, I'd like to use something like an auto-tune box to do the heavy lifting.

**For digital instruments:** Would like to drive the Arduino board with some kind of digital signal (for example midi)

I'm having trouble finding out which (if any) consumer audio device can provide the pre-processing. Are there any comparable projects or insights?

# Answer
Confusing question. You list vocals and Digital Instruments, then you ask which audio device provided pre-processing?

There are the auto tunes boxes you mentioned. Since you know about them I don't see how you would be asking about them.

A digital instrument might output midi, and midi is just a simple serial protocol, so there is no device needed.

So what is your question actually?

An auto-tune box does work that would be best suited to a laptop or desktop computer. It first must determine the intended pitch than apply a formant filter to shift the incoming signal to a correct pitch. It requires the use of heavy fast math, Fast Fourier Transforms, FFT. The smaller boxes you see doing this are actually specialized computers. Do not confuse their size with their power.

Google 'digital tuner software' to get an idea of what goes on. I do not know of a device that specifically output the 'corrected' midi for an auto-tune, but at that point it would be fairly trivial so it would not surprise me if many did it. For sure the many guitar to Midi converts do just that, but a good one is several thousand dollars.
> 1 votes

---
Tags: audio, midi
---


title: Atmega168 breaking out of ISR

text:
# Question
Title: Atmega168 breaking out of ISR
I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART\_receive() on the atmel gets stuck at: `while ( !(UCSR0A & (1<<RXC0)) );`

Is there any way I can break out of this? The code is posted below:

```
unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

```

The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.

```
ISR(USART_RX_vect)
{
    len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0"
    UART_flag = 1;
}

```

The the buffer is set up in main()

```
unsigned char uart_string[20];

```

# Answer
First of all, you shouldn't share a *simple* variable between ISRs and the main loop: `unsigned char uart_string[20];` should be `volatile unsigned char uart_string[20];`. Moreover, you must define it out of any scope.

Also, using possibly blocking loop in an ISR is strongly not recommended. In fact, whenever your microcontroller enter an ISR, everything else is stopped: thus, an ISR should last as short as possible. Plus, the `USART_RX_vect` triggers whenever a *single* character is received: this means that you'll have to wait for the next one. Thus, you mustn't use ISR like that: I would just use a global volatile variable to monitor the amount of received characters. Then, in the main loop, I would analyze the input characters whenever this counter is greater or equal than 2 . Finally, in your ISR, you try to read four input characters: '/0' is only one character, in the ASCII table it's called NULL, so you should only read up to three characters.
> 2 votes

# Answer
As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.

The interrupt fires when *a character* has been received, so that is all your program should count on finding. You can if you really want to *poll* the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened **and you definitely should not be *waiting* for it in the ISR**. Rather, if the ultimate consuming code needs multiple characters, then *that* should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.

Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.
> 1 votes

# Answer
I think I may have a very simple solution. Completely overlooked this while I was messing with the timers. I took the hint from a I2C routine in some threads in the the forum here.

This works with empty strings as well as large strings with garbage values. It doesn't seem to hold the system anymore, so it works for my purpose.

Anything I should add here?

```
int count_for_break = 0;
while ( !(UCSR0A & (1<<RXC0)) )     // wait for another char - Waits for 200 cycles.
        {
            count_for_break++;
            if(count_for_break > 200)
                break;
        }
//then reset the counter upon break or char receive.

```
> 0 votes

# Answer
I would suggest using code like this:

```
//Above your program, global variable.
char uartRXbuffer[100];//Adjust size!
int  uartRXbufferIndex = 0;
//bool uartRXmessage = false;

ISR(USART_RXC_vect){
   uartRXbuffer[uartRXbufferIndex++] = UDR;//read UART register into buffer. And increase index by 1.
   if(uartRXbufferIndex > sizeof(uartRXbuffer){
      //uartRXmessage = true;
      uartRXbufferIndex = 0;
   }//else if(uartRXbuffer[uartRXbufferIndex-1] == "\n"){
   //   uartRXmessage = true;
   //}
}

void loop(){
   HandleBuffer();
}

void HandleBuffer(){
   //Do something with your buffer values.
   //if(uartRXmessage){
      if(strstr(uartRXbuffer,"Command1")){
        //Code for when "Command1" is found in your buffer.
      }
   //}
//uartRXmessage = false;
}

```

I havent tested this code, but the idea is correct I believe. You can un-comment the uartRXmessage stuff if you only want to handle the buffer when there is an end-of-line character or when the buffer is full. Alternatively you can implement a ring buffer.
> 0 votes

---
Tags: atmega328, uart, isr, atmel-studio
---


title: connecting GSM 900A module to arduino

text:
# Question
Title: connecting GSM 900A module to arduino
I am trying to connect my arduino uno to GSM 900A with the help of this tutorial https://elementztechblog.wordpress.com/2014/10/10/interfacing-sim900a-gsm-modem-with-arduino/ but the calling is not being carried out.

The serial output is as following:

```
Calling through GSM Modem
Called
ÿÿÿÿ

```

and the code is

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()

{

  Serial.begin(9600);
  Serial.println("Calling through GSM Modem");

  mySerial.begin(9600);
  delay(2000);
  mySerial.println("ATD99abc19965;");
  mySerial.println("ATH");
  Serial.println("Called ");
}

void loop()
{

  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
}

```

# Answer
You're really missing multiple parts here...

Check out this tutorial: http://tronixstuff.com/2014/01/08/tutorial-arduino-and-sim900-gsm-modules/

* First of all, did you power up the SIM900A using its PWRKEY pin?
* And can you send and receive AT commands?

How do you know that you have a valid GSM connection? Did you try `AT+CREG?` and `AT+CPIN?`

* Do you understand the AT commands you send?

You send `ATD` (with `abc` in the number?) and after that you *immediately* send ATH. Thus you would hang up directly after calling, and probably wouldn't even get to the actual calling part.

---

```
#include <SoftwareSerial.h>

SoftwareSerial sim900Serial(10, 11); // RX, TX

void setup()
{
   Serial.begin(9600);
   Serial.println("Calling through GSM Modem");
   sim900Serial.begin(9600);
   delay(2000);
   sim900Serial.println("ATD99abc19965;");
   delay(10000);
   sim900Serial.println("ATH");
   Serial.println("Call ended ");
}

void loop() {
   if (mySerial.available()){
      Serial.write(mySerial.read());
   }
}

```

Also, your code isn't very well formatted. Compare the code above with yours.
> 1 votes

---
Tags: gsm
---


title: Arduino serial informations

text:
# Question
Title: Arduino serial informations
Is it possible to change serial information of arduinos board ? For example I have an arduino uno with this serial informations :

```
{
      comName: '/dev/cu.usbmodem1411',
      manufacturer: 'Arduino (www.arduino.cc)',
      serialNumber: '75430333137351804230',
      pnpId: '',
      locationId: '0x14100000',
      vendorId: '0x2341',
      productId: '0x0043'
}

```

I want to modify for example the manufacturer to be able to automatically detect the device whatever the comName is. I don't want to detect arduino board I want to detect arduino board modify by me without make a serial connection.

# Answer
> 1 votes
Once you have purchased a USB vendor ID you can edit the firmware within the Arduino installation at `hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/` with your vendor ID, chosen product ID, and other USB parameters as you wish and then rebuild the firmware and upload it to the ATmega16U2 on the board via ISP.

If you do not wish to purchase a vendor ID for the time being then you can use 0x6666, the prototype vendor ID, in the meantime, but you are not allowed to make products using that vendor ID available to the public.

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


# Question
Title: Arduino R/C compatible transmitter and reciever
I want to make a RC buggy or something down those lines (using Legos of course) and I'm confused while looking what transmitter/receiver to use. Would like a simple classic remote and any compatible receiver for the Arduino. Found such a remote: http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html But this seems way overkill for what I want to do. Any links or suggestions would be appreciated. Hope the question isn't too broad for stack exchange.

# Answer
> 0 votes
If you want to involve an Arduino on the receiver, you may want to choose a transmitter which is compatible with a 2.4 GHz chipset that is both available, and for which you can find Arduino code. The NRF24L01+ and Beken compatibles are probably the most available, and a lot of RC toys use something compatible, though getting firmware right to interact with them can be tricky. Beware that there are some other chips in wide use too, which can be harder to source a module for.

You can use an off-the-shelf multi-channel receiver, but that will tend to output each channel on a distinct PWM pin, which is annoying if you want to capture the data into an Arduino.

You might want to spend some time looking on rcgroups and in various hobby drone sites - the latter folks have a similar problem, as they want to collect all the control channels and mediate them through a custom flight computer (which in the early days was sometimes Arduino-compatible).

You can also make your own transmitter - perhaps by retrofitting an NRF24L01+ module and miniature Arduino equivalent into the casing of an older 5/72/75 MHz set - or the IR transmitter from a toy helicopter.

# Answer
> 0 votes
It depends on the number of channels you need, but you could go to HobbyKing, they offer RC remotes for down to 20$

---
Tags: arduino-mega, remote-control
---


# Question
Title: How I could make a bus connection in a prototype shield?
I am a programmer but pretty new to electronics , I recently bought a prototyping shield like the picture :

In my view there is no bus connections here . I have lots components need connect to solder into a single board , and some ports like GND and VCC , SDA and SCL need connect via buses , how could I make solder such a bus connection by using this shield?

Should I just continuously solder through the holes I want to form a bus?

Thanks..!

# Answer
I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.

A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.

https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ%2beHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0
> 1 votes

---
Tags: arduino-uno, arduino-mega, shields
---


# Question
Title: How to drive motors and use an ultrasonic sensor simultaneously?
I have a L298 motor driver, which I coded with an Arduino Nano. The code is very simple at the moment:

```
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  Motors_FWD_PWM_Initialize();

  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  MotorsOff();
}
void loop()
{
  demoTwo();
  delay(1000);
}

void Motors_FWD_PWM_Initialize()
{
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void MotorsOff()
{
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

```

Currently I have two questions:

**Q1:** I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.

**Q2:** Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.

# Answer
For the first question, you could simply implement an **interrupt routine** to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.

You can achieve this by setting timer1. There is a library here for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.

The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.

http://playground.arduino.cc/code/timer1
> 1 votes

---
Tags: sensors, motor
---


title: MOSFET to dim LED backlight

text:
# Question
Title: MOSFET to dim LED backlight
I have built the following to dim the brightness of the LED backlight of a display: I am using a BS170 MOSFET (the diode is no extra part but included in the MOSFET, according to the datasheet). The BL pin is the supply of the LED backlight. (I have left out all other pins.)

Unfortunately, it does not work. Even if I set the PWM pin to 255, the backlight does not light (actually it's completely off). If I short BL and Vcc, it lights up as it should.

Also, the voltage readings confuse me: I measure 3.3 V on the gate and drain against ground, 1.5 V on source against ground (= the voltage across the backlight) but only 1 V if I measure drain against source.

So my questions are:

1. Shouldn't this add up to 3.3 V?
2. More importantly, why do I get only 1.5 V at BL?
3. Most importantly, what do I need to change? Different MOSFET? No MOSFET?

The primary aim of controlling the backlight is to be able to switch in off completely, thus reducing power consumption. (Being able to dim it is only a plus.)

## EDIT

I should have added details about the display. It's one of those:

I haven't found a datasheet / specs for exactly this model. Most datasheets I found refer to a different version that is not 5 V compatible. A very similar model is described here.

Concerning my question I haven't found information on how much current the backlight would draw. Therefore I didn't want to drive it directly from the PWM pin. (Actually I could just measure it...)

# Answer
**Summary:** It looks as though you can just drive BL directly with the PWM-output.
What happens when you do?

---

**Details:**

(1) As shown, even if the circuit did what you wanted, all you would be doing is providing a rail to rail (0V to 3.3V ) signal to the BL pin. You can do this by connecting PWM-out to BL directly.
Does this work?

If the LCD and Arduino used differing power supplies the MOSFET may be useful.

(2) To use circuit almost as-is you need a PChannel FET. Swap Drain and Source and it will provide PWM to the BL pin. When BL is high the FET is off. When BL is low the FET is on. The FET used must turn on with about 3V between gate and source.

(3) To use the N Channel BS170 you must drive the gate +ve above the source by an amount that is enough to just turn it one "plus a little more". This is called Vth (Vthreshold). The BS170 has Vth ~= 1.8V at low currents. Vth varies somewhat between samples. When you connect the gate to +3.3V the FET tried to turn on but as the source rises it reduced Vgs until it reaches about Vth. Raising the source above this level reduced Vgs to below Vth so the FET is not turned on.
ie this is what a=accounts for the 1.5V that you see as 3.3V - 1.8V = 1.5V.

To use the BS170,
connect the source to ground,
connect drain via a say 1k resistor to +3.3V,
connect drain to BL,
drive gate with PWM.

BUT why does not just driving BL with PWM do what you want?
A data sheet for the display would be useful.
> 2 votes

# Answer
Since you are switching on the high side, you need a P-channel mosfet, not an N-channel like the BS170. (Or you need a higher voltage on the Gate to reach the VGS(th)).

I have a similar display, but mine will light up if BL is connected to ground. For these kind of displays you'd use a N-channel mosfet.
> 0 votes

---
Tags: power, led, pins, pwm, mosfet
---


# Question
Title: HC-06 Bluetooth RX & TX voltage (3v3 || 5v)
I acquired a HC-06 Bluetooth module, and understand that the voltage on the pins must be 3v3 and therefore requires the use of a voltage divider to lower the Arduino's 5v to 3v3 like this.

But the page where I purchased the product says the following:

> interface level 3.3V, you can directly connect a variety of SCM (51, AVR, PIC, ARM, MSP430, etc.), 5V microcontroller can also be directly connected, it can not pass without MAX232 MAX232!

Does this mean I can connect without using a voltage divider?

What does "it can not pass without MAX232 MAX232!" mean?

# Answer
> 1 votes
Some chips that run on 3.3v have 5v tolerant inputs. But it doesn't look like the BC417 does (looking at the datasheet).

So just add the voltage divider.

# Answer
> 1 votes
About the MAX232, I have a Dwengo (similar to Arduino) and to use the HC06 I have to disconnect the serial port(=RS232) else I short circuit my HC06.

After some googling, MAX232 is simply the name of that chip which is required to convert your TX/RX from your bluetooth module to something usable by Arduino.

Source: http://en.m.wikipedia.org/wiki/MAX232

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


title: Arduino uno r3 not powering up

text:
# Question
Title: Arduino uno r3 not powering up
i bought two arduino uno r3 card (not original) one is working perfectly: the other is not powering up (no led is lit), i did some measuring and i found that two usb connector pins on the board are shorted, how can i proceed to repair it taking in account that it works from time to time ! thank you More images:

# Answer
> 1 votes
It looks as though there may be material between at least one USB pin and the ground layer. This may be flux of solder 'splash'.

If visual inspection shows that this may be the case I would try **carefully** scratching with a sharp poibt (eg scriber) along at least the green arc on the image below. Be careful not to break intended conduction paths (eg as shown in black).

# Answer
> 0 votes
Since it's intermittent I'd try two things:

Easy: Briefly reheat each pin of the USB connector and it's pad, the goal being to make sure the solder joints are solid. Clean away any solder bridging the pads. Of course you can only reach the back side of the board, but this is an easy first step.

More thorough: If the first step didn't get it working, then try desoldering the USB connector, using a solder pump and desoldering braid to remove as much of the solder as possible from all four pins before you try to actually remove the part. Work slowly giving it time to cool between steps so you don't overheat anything. When the part is removed, inspect the top of the board and clean up any solder bridges. Inspect the bottom of the USB connector where it touches the board and clean it, too, if necessary. Then solder it onto the board again using as little solder as necessary to make solid connections.

---
Tags: arduino-uno
---


# Question
Title: Making a composite waveform using a single TIMER interrupt
I'm writing software for a laser tag gun, which under the system we use needs the output waveform to be a carrier wave of 57600Hz with a signal wave of 1800HZ for about 50ms

Using the Tone library (https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation) and a transistor AND gate, I've had this working using two timers, however I really want to shrink it down to one timer so that I can use the other for sound (using the TMRPCM library which only needs timer1).

I've modified the Tone library cut down to what I need, with the following methods:

```
void TagTone::beginPulse(uint8_t tonePin)
{
    _pin = tonePin;
    _timer = 2;

    // 8 bit timer
    TCCR2A = 0;
    TCCR2B = 0;
    bitWrite(TCCR2A, WGM21, 1);
    bitWrite(TCCR2B, CS20, 1);
    timer2_pin_port = portOutputRegister(digitalPinToPort(_pin));
    timer2_pin_mask = digitalPinToBitMask(_pin);

    int duration = 50; //50 milliseconds
    uint8_t prescalarbits = 0b001;
    int32_t signal_toggle_count = 0;

    // Note: may need prescaler reimplemented if using 16Mhz, fine on current 8Mhz
    ocr = F_CPU / (CARRIER_FREQUENCY * 2) - 1;
    prescalarbits = 0b001;

    TCCR2B = (TCCR2B & 0b11111000) | prescalarbits;

    toggle_count = 2 * CARRIER_FREQUENCY * duration / 1000; // how many times the carrier toggles before pulse ends

    // want to AND with 1800 Hz signal

    // as duration now set to 50: toggle_count for carrier = 5760
    // equivalent toggle count for signal = 180
    signal_toggle_count = 2* SIGNAL_FREQUENCY * duration / 1000;

    // want to flip signal state every 32 carrier pulses
    signal_cycle_count = 32; //toggle_count / signal_toggle_count;
}

// duration (in milliseconds).

void TagTone::playPulse()
{

    OCR2A = ocr;
    timer2_signal_toggle_count = signal_cycle_count;
    timer2_toggle_count = toggle_count;
    bitWrite(TIMSK2, OCIE2A, 1);

}

ISR(TIMER2_COMPA_vect)
{
    if(timer2_toggle_count  < 0)
    {
        *timer2_pin_port ^= timer2_pin_mask & signal_state; // flip

        if (timer2_signal_toggle_count > 0)
        {
          timer2_signal_toggle_count--;
        }
        else
        {
            signal_state ^= signal_state;
            timer2_toggle_count -= timer2_signal_toggle_count;
            timer2_signal_toggle_count = signal_cycle_count;
        }
    }
    else
    {
        TIMSK2 &= ~(1 << OCIE2A);                 // disable the interrupt
        *timer2_pin_port &= ~(timer2_pin_mask);   // keep pin low after stop
    }
}

```

What I hope this is doing is 32 toggles at the carrier speed (ie 16 full cycles of 57600Hz), followed by 32 'silent' toggles where nothing happens, followed by another 32 at carrier speed, etc. I should then be able to fire using:

```
digitalWrite(signalPin, HIGH);
carrierTone.playPulse();
delay(60);
digitalWrite(signalPin, LOW);

```

But that doesn't set off the sensor, whereas the simple code below works.

```
carrierTone.play(57600, 50);
signalTone.play(1800, 50);

```

# Answer
> 0 votes
Woo, solved it. My ISR code was completely wrong. Works using:

```
ISR(TIMER2_COMPA_vect)
{
  if (timer2_signal_toggle_count != 0)
  {
    // toggle the pin
    if(signal_state == 1)
        *timer2_pin_port ^= timer2_pin_mask;

    if (timer2_toggle_count > 0)
      timer2_toggle_count--;
    else
    {
        TIMSK2 &= ~(1 << OCIE2A);                 // disable the interrupt
        *timer2_pin_port &= ~(timer2_pin_mask);   // keep pin low after stop
    }
     timer2_signal_toggle_count --;
  }
  else
  {
    timer2_signal_toggle_count = signal_cycle_count;
    timer2_toggle_count --;
    if(signal_state == 1)
    {
        signal_state = 0;
        *timer2_pin_port &= ~(timer2_pin_mask);
        //*timer2_pin_port ^= timer2_pin_mask;
    }
    else
    {
        signal_state = 1;
        *timer2_pin_port ^= timer2_pin_mask;
    }
  }
}

```

I was trying to just AND the signal state into the original pin state, which was completely the wrong thing to do.

---
Tags: interrupt, signal-processing, isr, frequency
---


# Question
Title: How to convert a String number Into a int value?
I want to convert a string into a int value. in my real code, I receive a string "Slider 255" the number after slider changes from 0 to 255, so I want a int value to be equal to that number. This is a small example of the code:

```
#include <Servo.h>
Servo myServo;

int val = 0;
String s = "";
void setup() {

  Serial.begin(9600);
  myServo.attach(9);
}

void loop() {
  while(BT.available() >0){
  s =  Serial.read(); // which wiil be a number between 0 and 255
  // So I want val to be = to ehatever the string is. So far I have try this but it doesn´t work.
  // first attempt # 1
  val = s:
  myServo.write(val);

  // Second attempt # 2
  Serial.println(s)
  val = Serial.read();
   myServo.write(val);
  }
}

```

# Answer
> 4 votes
The easiest way is to use the parseInt method available to Serial like this

```
int val = Serial.parseInt()

```

But, you will have to be sure that the non-number part of the message ("Slider") has already been dealt with.

You could also put the data into an arduino String Object and use it's toInt method, or put it in a C style string and use the atoi method.

---
Tags: arduino-uno, c++, robotics, processing-lang
---


title: Transistor for DC motor and 9v

text:
# Question
Title: Transistor for DC motor and 9v
I have this schematic for a DC motor in my arduino, now I want to add 9v battery.

But I've seen that people use TIP120 transistor, I have BC548B, can I just put the 9v with that transistor?

# Answer
There are many circuits using the TIP120 NPN transistor because it is a darlington transistor. This is used because its max voltage is `60V` and the max current is `5A`, this means you can control a variety of external high current devices with low voltage circuitry because of the darlington arrangement.

You can use the BC548B with your motor(low current) and a 9V battery as it does handle `30V`, **but it is limited to `100mA`**, which is fine for tiny low current motors. But these are actually Amplifier transistors, so there main design area is not for inductive loads.

I recommend the TIP120 as this will ensure that you don't trash a transistor with current spikes as you could easily go over the 100mA spec of the BC548.
> 1 votes

# Answer
Firstly, I see no external power supply in your schematic.
Secondly, you certainly CANNOT use a BC548 for controlling a motor.
MOSFETS are the best.
> 1 votes

---
Tags: arduino-uno, motor, transistor
---


title: #ifdef / #include CPP issue

text:
# Question
Title: #ifdef / #include CPP issue
I'm developing a sketch which I need to run on an Uno (for debug) and a Gemma (as the target). Adafruit has their own Wire library (TinyWireM) which I was planning on using on the Gemma. Thus, I was trying to use #if's to automatically include the correct library for the given target board. However, it appears that the TinyWireM include files is always included even if the **AVR\_ATtiny85** macro symbol is undefined (I get many undefined symbols reported inside the Arduino\libraries\TinyWireM-master\USI\_TWI\_Master.cpp file). If I comment out the TinyWireM.h include statement (inside the #if define statement), then it compiles fine. Code example below.

So why isn't this include statement being skipped? I'm at a loss. Anyone have any thoughts?

Thx all.

Mike

```
#undef __AVR_ATtiny85__        // Debug only - making sure not defined.

#if defined (__AVR_ATtiny85__)
  #include <TinyWireM.h>    // Seems this file is still being included and
                          // must comment out this line when compiling
                          // code for an UNO.  This should not be necessary
                          // given __AVR_ATtiny85__ is not defined.
#else
  #include <Wire.h>         // This is the Wire library for the Uno.
#endif

void setup() { }

void loop() { }

```

# Answer
The problem isn't your code. There is a 2012 bug report on this issue in Google Code.

Once you start getting bitten by the non-standard behavior of the Arduino IDE, you've outgrown it and the only real remedy is to move up to real tools that work as you'd expect. A few of the choices include:

* Eclipse is a good choice; it can take a little patience and searching to get it set up right, but once you do it's a solid development environment you can stay with for a long time. It runs everywhere Java does.
* Atmel Studio is well thought of. It's proprietary, not free \[?\], and only for windows.
* Apple's Xcode can be configured to use the avr-gcc toolset. (Even thought it's right here on my system, I'm happy with Eclipse and haven't tried it).
* Likewise, you can use Microsoft Visual Studio (the linked article is just one of many).
* Command line: You can get down and dirty with your favorite editor, the gcc toolset for AVR, and bang away at your keyboard. Not sexy, but you'll learn everything that's going on between your code the board.
> 3 votes

# Answer
The Arduino IDE does its own non-standard preprocessing before the C++ preprocessor/compiler is invoked. One of the main purposes for this is to detect `#include` directives which refer to libraries so it can link them properly.

My guess would be that part of this procedure ends up moving all `#include` lines to the start of the file. In the code you've posted, that means I think it's being moved outside the whole `#if`/`#else` structure.

In most cases, you can avoid the Arduino IDE trickery by moving things into a separate header or source file. Unfortunately though, doing that means it may not link the libraries properly. As such, the easiest solution may be to switch to a 3rd party IDE which has Arduino support (e.g. Eclipse).
> 2 votes

---
Tags: i2c, arduino-ide, ide
---


title: New UNO, BLINK not working

text:
# Question
Title: New UNO, BLINK not working
Finally got around to playing with my uno today for the first time. ( It's a branded sunfounder UNO R3)

First project. Simple blink. Using arduino 1.6.3, Windows 8.1 It is hooked up correctly.

```
void setup() {
   // initialize digital pin 13 as an output.
   pinMode(9, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(10000);              // wait for a second
   digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
   delay(10000);              // wait for a second
}

```

What I get is a fast blinking LED. I've tried multiple values and it doesn't change. No error on upload. I've commented out everything except the digitalWrite(9, HIGH); and I get a fast blink.

I tried:

```
void loop() {
   digitalWrite(9, LOW);
   delay(5000);
   digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
}

```

And I get nothing, it doesn't even turn on.

Same if I remove the first digitalWrite();

So, I'm already a little lost here. I did a but of google searching tried adding a serial 9600 line, and a few other things. Nada.

# Answer
> 0 votes
Defective board. Thanks to @br1an for the milli idea. New board in the way, not a clone.

# Answer
> 0 votes
*Added as new answer because comments limit was reached* Doesn't really matter which programmer you set because in this instance you're not actually burning the bootloader just setting the fuses (to those already stored in boards.txt for the Uno) but 'Using Arduino as ISP' is the nearest to what you're doing

---
Tags: arduino-uno
---


title: Electret microphone amplification

text:
# Question
Title: Electret microphone amplification
I've got an electret microphone and I understand that I need quite some amplification to get it to be read by an Arduino (0-5V input). So I seeked the web, but answers are as different as people on the street. Some use Op-Amps, some only a transistor cicruit or the like. This guy is using 2 amps before and after his filters Video, LM386 and this guy claims, that exactly this amp isn't good for the job: recommends NOT using LM386.

I really only want to have a threshold switch, so I need no filters whatsoever and not a super duper amplification. What is the simplest solution, with which I can read a voltage with the arduino? With a transistor alone (seems easiest to me so far) - how can I know how much it amplifies (or as I understand it modifies the "other voltage" to look the same)?

I found many different schematics using various op-amps, but regarding them I don't really need another tutorial, but rather a rule of thumb for a "readable" amplification. Is 100 times enough? I found circuits with 1000 times amplification, so I'm really wondering which one works fine.

However the really simple thing would be this: video at 17sec. At second 17 and 50 or so, they show an extremly basic circuit, which would be exactly what would work best for me... However the question is, if this is enough amplification for the ADC in an arduino.

If I can't get a satisfying answer I think I'll build both and see how they compare/work for me.

# Answer
> 0 votes
I've built

This circuit without C4 and everything after R4 (no rectifier, not a single diode used). R4 has to be switched for 100kOhms, since this gives a 100x amplification. I guess this is simple enough for most people. Thanks for the hints.

The following code can be used to detect claps/noises. It is restricted to a double-clap with silence in between. Parameters can be easily tuned. This works quite well for me, even when I play noise/TV/music to the speaker directly it triggers rarely, or not at all!

```
// CLAP switch using an electret microphone
// switches ie. a relais or led with a certain
// clap-melody

// sound parameters
const int THRESHOLD = 20;
const int VAL_MEAN = 507;

// trigger characteristics
const int CLAPS_TO_TRIGGER = 2; // number of claps
const int DEBOUNCE_TIME = 150; // ms to ignore double-clapping
const int SILENCE_T = 40; // ms between claps, otherwise reset
const int MELODY_INTERVAL = 800; // ms max time for the claps
const int PAUSE_TIME = 2000; // wait after switch, or noise

// pin-layout
const int analogPin = 0;
const int OUTPUT_PIN = 13;

int output_state = LOW;
uint32_t pause_t = 0;
uint32_t debounce_t = 0;
uint32_t start_time = 0; // timestamp of first clap-start
uint8_t claps = 0;
int sensorVal = 0;
int amp = 0;

void setup() {
  Serial.begin(115200);
  pinMode(OUTPUT_PIN,OUTPUT);
}

void loop() {
  sensorVal = analogRead(analogPin);
  amp = abs(sensorVal-VAL_MEAN);

  // Serial.print(F("sensed: ")); Serial.println(sensorVal);
  // Serial.print(F("amp: ")); Serial.println(amp);

  // at the end of an interval check the number of claps
  if (millis()-start_time > MELODY_INTERVAL & claps != 0) {
    if (claps == CLAPS_TO_TRIGGER & millis()-pause_t > PAUSE_TIME) {
      output_state = !output_state;
      pause_t = millis();
      digitalWrite(OUTPUT_PIN,output_state);
      Serial.print(F("Triggered "));
      Serial.println(output_state);
    }
    if (claps>CLAPS_TO_TRIGGER) { Serial.print(F("- too many")); }
    reset();
  }

  // noise/clap detected
  if (amp > THRESHOLD &\
      millis()-debounce_t > DEBOUNCE_TIME &\
      millis()-pause_t > PAUSE_TIME) {
    // there has to be silence between claps
    if (millis()-debounce_t < SILENCE_T+DEBOUNCE_TIME) {
      claps = 0;
      debounce_t = millis();
      Serial.print(F("reset - silence interrupted"));
      Serial.print(F(" amp "));Serial.println(amp);
    } else {
      claps++;
      debounce_t = millis();
      Serial.print(F("claps "));Serial.print(claps);
      Serial.print(F(" amp "));Serial.println(amp);
      if (claps == 1) { start_time = debounce_t; }
    }
  }
  delay(1);
}

void reset() {
  // time has expired
  start_time = 0;
  claps = 0;
  debounce_t = 0;
  Serial.println(F("reset"));
}

```

# Answer
> 1 votes
For the most basic circuit you must bias your microphone since it is electret with a 10k pull up resitor. If you do not want to build a complex circuit you could use a breakout board such as this one. To build your own see here. It is used as a VU meter which is basically the same idea. Also, make sure you observe polarity(pin with traces touching metal packaging is negative).

# Answer
> 1 votes
You can use Maxim MAX4466 op-amp which works very well with Arduino. There is a breakout available for the same for arduino at Adafruit here. The chip has a select-able gain from 25x-125x. This amplifies works very well to get a nice waveform for audible noise. There are a couple of libraries available for the waveform that you record and can translate it to frequencies. You can also use it to distort or change the voice. Here is a schematic of the circuit if you want to make one yourself.

---
Tags: audio
---


# Question
Title: AVR Timer1 OCR1A controls TIMER1_COMPB_vect interrupt!
I was struggling with timer interrupts in my project. I couldn't make it work properly. So I decided writing a simple code and I saw a very interesting case.

```
ISR(TIMER1_COMPB_vect)
{
        PORTB ^= (1 << PORTB5);
}

int main(void)
{
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    OCR1A = 10000;
    OCR1B = 100;

    TCCR1B |= (1 << WGM12);

    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);

    TIMSK1 |= (1 << OCIE1A);
    TIMSK1 |= (1 << OCIE1B);
    DDRB= 0xFF;

    #define F_CPU 16000000
    sei();
    while (1)
    {

    }
}

```

Here is my code. When I change OCR1B value, nothing happens, but if I change OCR1A value then blinking gets faster. Is there a logical explanation for this?

# Answer
> 2 votes
By setting WGM12, you set the time to CTC mode. In this mode the timer will restart when it reaches that value set to OCR1A. So the lower the value, the faster it restarts, so the higher the frequency.

The OCR1B value only changes where in this cycle the interrupt occurs. It will however still only be called once per timer1 overflow.

---
Tags: interrupt, timers, avr
---


title: What connects to Arduino Solar Shield?

text:
# Question
Title: What connects to Arduino Solar Shield?
I see there is an Arduino EnergyShield available, and am wondering what (specific) **solar** shield/panels/attachments can be used to power it. Thoughts?

Bonus points if someone can explain how long the solar unit would take to charge the Energy Shield if the Arduino was on but idling (low-to-nonexistent power output).

# Answer
First, panels that you can use...

There are a few at Adafruit (here, here or here)

You just want to check that the barrel jack and plug are the same size. I couldn't find dimensions in the documentation for the energy shield so you may need to dig a little deeper or just swap it for one that you know will work.

Also, the question about how long it will take also depends. First, if we assume that the arduino is not running we can get ~500mA from the second solar panel listed. If we can get all of that into the battery, it would take (1200mAH/500mA) about 2.4 hours to fully charge the battery. It looks like you have to make some adjustments on the shield to get the most out of your solar panel. And of course, you'll want to adjust those calculations based on the panel that you end up getting.

Now, if we assume the Arduino is running and consuming about 25mA you will have to subtract that 25mA from the 500mA that the solar panel is providing. So, in general...

\**

> (Battery Capacity)/(Solar Panel Current - Arduino Current) = Charge Time.

\**

And you have a lot of control over the solar panel current and the arduino current based on the exact arduino that you use, etc, etc.

There is also probably some loss regulating the solar panel voltage from 5-6V down to charge the battery (which is probably at 3.7V). I also don't know if the charging circuitry will limit the amount of current going to the battery.

Take Away: There's a lot of stuff to consider when trying to answer this question. I think your best bet would be to get a panel that fits and dump the fuel gauge values out to the console every few minutes.
> 1 votes

---
Tags: shields, battery, solar
---


title: Arduino: ARM, MCU, SoC and RTOS

text:
# Question
Title: Arduino: ARM, MCU, SoC and RTOS
I'm trying to understand the relationship between embedded RTOSes, SoCs and chip architectures. Specifically, I have a hobby project that would involve me writing a real-time, embedded application for the embox RTOS, and use Arduino hardware for my proof of concept/prototype. Then, budget permitting, I'd like to port that app to run on another, non-Arduino ARM-based system.

My *understanding* is that ARM is the chip architecture (a conceptual design, really), and that Arduino simply implements this design, and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

My *understanding* is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Is my understanding of: ARM, Arduino, MCU, SoC and embox/RTOS correct? If not, please clarify/correct me! If so, what sort of considerations *would* have to be made when porting my app to another ARM system in the future?

# Answer
> My understanding is that ARM is the chip architecture (a conceptual design, really),

ARM is the CPU core architecture used in the Atmel SAM3X MCU family. The MCU is the CPU plus all of the facilities (PWM, ADC, DAC, DMA, etc.) that are implemented in order to allow the CPU to interact with external circuitry.

> and that Arduino simply implements this design,

Most appropriately, "Arduino" is the IDE and the software libraries that come along with it, plus the specifications and connector layout of the various pieces of Arduino hardware.

> and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

"SoC" is exactly what it says on the tin: it's an entire system on a single chip. The Due is not a SoC, since it's a full board. The BCM2835 found on the RPi is a SoC. The SAM3X is a MCU, since it still requires more than just connectors to become a full "system".

> My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Provided that embox runs on the new system and that your application can be compiled for it.
> 2 votes

---
Tags: arduino-due
---


title: Xbee power issue

text:
# Question
Title: Xbee power issue
I want to power xbee s2 module through atmel 328p digital output pin. And I am powering atmel 328p IC using 3.7 li-ion cell 5500 mAh. In sleep mode atmel consume current in micro Amp but xbee consuming around 40 mA. I want to reduce it. I tried xbee in power down mode but its not working for me. Is der any way to switch xbee automatically with as atmel sleep & wake-up. Circuit works properly when I power xbee through 3.7 v li-ion cell but consume power continuously.

# Answer
> 1 votes
The best solution would be to determine why your Xbee is not being switched into power down mode.

But, if you wish to turn the Xbee power off using the Arduino then there are many ways of doing this. One method is shown on the diagram below {**from here**}. This requires two transistors and three resistors. Almost any small transistors would work. Good choices if buying new components would be BC337 / BC817 for T1 and BC327 / BC807 for T2. The first part number in each pair is a through hole part and the second number is the equivalent surface mount part. If buying these try to get the -40 suffix versions, although in this case any version would work OK.

This circuit was drawn for use with a PIC processor controlling a 12V supply, but the Arduino works equally well controlling a 3.7V LiIon supply. The load is shown as a light bulb - that's where you'd connect the XBee.

Input low turns 1 off which turns T2 off. To enable/disable the XBee you have to raise / lower the input pin.

# Answer
> 0 votes
I would use a sleep mode, e.g. PIN sleep, in order to reduce the power consumption of the Xbee. At the hardware level, the XBee uses pin 9 as a control pin. This pin can be used to sleep the radio: setting it to 3,3V (“high” or “asserted”) causes the radio to sleep; setting it to 0V (“low” or “deasserted”) wakes the radio up. You can find some useful hints on the following websites http://citizen-sensing.org/2013/08/xbee-sleeping/ or https://www.digi.com/wiki/developer/index.php/Designing\_a\_Sleeping\_XBee\_Sensor or here http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index.

---
Tags: power, xbee
---


# Question
Title: Arduino Attiny 85 IR library compiler error
I'm about to ask a question for the most common problem which everyone has with `attiny85` and the IR library. I will try to make this question as simple as possible.

## Few things about the lib and the chip

First of all the lib https://github.com/shirriff/Arduino-IRremote works great on the `UNO` and it's the best out there.

The `Attiny85` is the smallest chip you can get able to run Arduino code. It has alot of limitations but it worth it!

## The common problem

`Attiny85` uses different timers from the normal Attiny and Atmega chips which makes it impossible to run the standard libraries. There are some fixes for some libs. For example the `IR Remote` has a version which **ALMOST** works with the chip and it can be found over here: http://gammon.com.au/Arduino/IRremote\_Attiny.zip

However the problem lies in the core. The first time i used the patched `IR` i had the `MIT High Low Media Group` versino 1 of the core files which bearly worked but it was the first released so...

After reading this guide:http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS I used an updated core which can be found here: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

## And the final problem

Even with the updated core i still got *only 1* last error.

```
Compiling 'Shit' for 'ATtiny85 @ 8 MHz  (internal oscillator; BOD disabled)'
IRremoteInt.h:101: error: 'RAWBUF' was not declared in this scope
Error compiling

```

Does anyone know how to fix it?

## Links

1. MIT high-low group first version: http://highlowtech.org/?p=1229
2. Tutorial for the chip and the IR: http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS
3. The IR original lib: https://github.com/shirriff/Arduino-IRremote
4. Updated core: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

**Just in case you wanna know i'm using the Atmel Studio 6 with the Visual Micro plugin instead of the crappy-arduino-IDE**

# Answer
`RAWBUF` is defined in IRremote.h. Make sure you include that header before including IRremoteInt.h.
> 1 votes

---
Tags: library, attiny, avr, ir, atmel-studio
---


title: How to get string parts from string?

text:
# Question
Title: How to get string parts from string?
I have this method:

```
void getWeatherData() {
    String resp = "";

    Process p;
    p.begin("python2.7");
    p.addParameter("/root/weather.py");
    p.run();

    while (p.available() > 0) {
        char c = p.read();
        resp = resp + c;
    }

    Serial.print(resp);
    Serial.flush();
}

```

In the serial monitor, I see the string `70.7|45|1030.29|06:05|20:04|04 May 2015 22:24`. The delimiter here is the pipe. Now, the parts I take a send them to methods that puts the values on the TFT screen.

However, I fail to understand how to split this long string into individual parts.

Can somebody help?

Thanks

EC

# Answer
> 0 votes
I used to have my own String class with a member method called Chomp which did exactly what you are requiring. The body was something similar to this untested code:

```
String chomp(String& pSrc, char pMatch)
{
    int matchPos = pSrc.indexOf(pMatch);    // Find the first occurrence of the separator
    if (matchPos < 0)   // Separator was not found.
    {
        String ret = pSrc;  // Return the remainder of the source string.
        pSrc = "";          // Clear the source string
        return ret;
    }

    String ret = pSrc.substring(0, matchPos - 1);   // "Chomp" the start of the string up to the separator into the return value
    pSrc.remove(0, matchPos);                       // Remove everything up to and including the separator.
    return ret;
}

```

Hopefully the above code should be pretty understandable and fixable if there are any errors. Our version worked on a "this" pointer rather than passing in the source string, so we would have something like:

```
String sourceCoords = "12,47,292,85";
int x1 = sourceCoords.chomp(",").toInt();
int y1 = sourceCoords.chomp(",").toInt();
int x2 = sourceCoords.chomp(",").toInt();
int y2 = sourceCoords.chomp(",").toInt();

```

Hope this is of some use.

---
Tags: arduino-yun, string
---


title: MQTT vs Tinkerkit sensor Shield

text:
# Question
Title: MQTT vs Tinkerkit sensor Shield
I'm working with this http://knolleary.net/arduino-client-for-mqtt/. I'm using Arduino Uno + Ethernet shield + Tinkerkit Shield. But, if i have only Arduino Uno + Ethernet Shield, i can connect my arduino with MQTT and make publish/subscribe, but, when i put the tinkerkit shield, i lost the connection and i cannot connect any more. Any idea? Tinkerkit sensor shield is incompatible with mqtt?

Thanks.

# Answer
I think your problem is in wiring. Ethernet shield is using SPI communication, it requires pins: `SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK)`. Those pins must be left for the Ethernet shield. Information is from Arduino Uno description.

Does your Arduino communicates with you after you plug-in Tinkerkit? If not, maybe you have a short in Tinkerkit shield.
> 0 votes

---
Tags: arduino-uno, ethernet, communication
---


# Question
Title: How do I use the additional serial ports on an Arduino UNO R3 clone?
I bought this Arduino clone over eBay. It seems to have an extra SPI and serial ports. How do I use these?

# Answer
> 4 votes
UNO means ATmega328. It has always only one serial and one I2C port regardless of how many connectors (or solder pads) it is hooked to. They are just parallel outputs to ATmega pins: `D0 - TX
D1 - RX
A5 - SCL
A4 - SDA`

Extra pads are just for user convenience, for easier wiring.

# Answer
> 4 votes
Those are not additional I2C and UART ports, those are additional connectors connected to the normal peripherals. They are used in exactly the same manner as the normal connector.

---
Tags: serial, clones, arduino-uno-smd
---


# Question
Title: Programmed device causes issues between computer and ISP
I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...

http://digistump.com/wiki/digispark/tutorials/programming

The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...

https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf

I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer.

Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.

After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.

Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

# Answer
With the Tiny AVR programmer, the `D+` and `D-` lines are connected to there own input pins on the ATtiny84, see below:

This means that the pins from the target chip do not interfere with the function of these.

Whereas the digistump board has the outputs of the USB connected to pin `3` and `4`, these pins are also connected to pin `3` and `4` of the target, as you know,

This means that as soon as you have your outputs active on `3` and `4` these interrupt the function of the USB lines.

By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines.

This is actual done on the SPI buses as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:

The **R** is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.

Another method to use instead of the resistor would be to cut the traces on the ***target board*** for pins `3` and `4`, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.

> Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as

1. the PC can't issue it,
2. the programmer won't know to do that on its own.
> 1 votes

---
Tags: attiny, isp
---


# Question
Title: How can i use a TFT Screen shield along with other sensors and transmitters
I want to use Arduino as described in this instructable:

http://www.instructables.com/id/Uber-Home-Automation-w-Arduino-Pi/

But i thought i would give it a little twist by adding a TFT monitor to some devices. I have bought and got the following tft shield to work: http://www.banggood.com/UNO-R3-ATmega328P-Board-2\_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html

But now it strikes me: How can i combine the screen on an arduino where i also have a sensor and a radio transmitter?

# Answer
> 1 votes
You need another layer! A breadboard shield - from the same source if you like - would seem the obvious answer.
Alternatively, take flying leads from the pins you are using to the screen & mount it elswhere, then connect the sensors.
LCD's use quite a few pins, you'll probably need to be creative with an Uno. I have one on a Mega, & have been there with the same problem!

---
Tags: lcd
---


title: IR not working on Attiny85

text:
# Question
Title: IR not working on Attiny85
After countless attemps on making this thing work i'm not sure what the hell is going on. First of all you can't use the normal IR library because Attiny85 is crap and due to timer isses it wont work. So basicaly you need just the specific part which gets the data from the remote and thats all. This is what i did but i failed badly again.

This time i used the simplest possible code which works perfectly on the Arduino UNO but it wont do anything on the Attiny85

## The code

```
int irPin     = 4;
int tipPin    = 3;
int start_bit = 2200;    //Start bit threshold (Microseconds)
int bin_1     = 1000;    //Binary 1 threshold (Microseconds)
int bin_0     = 400;     //Binary 0 threshold (Microseconds)

boolean state = 0x0;

void setup() {
   pinMode(tipPin, OUTPUT);
   pinMode(irPin, INPUT);
   //Serial.begin(9600);
   //Serial.println("IR/Serial Initialized: ");
}

void loop() {
   int key = getIRKey();   //Fetch the key
   //Serial.println(key);
   if (key != 0) {
     state != state;
     digitalWrite(tipPin, state);
   }
   delay(400);    // avoid double key logging (adjustable)
}

int getIRKey() {
  int data[12];
  int i;

while(pulseIn(irPin, LOW) < start_bit); //Wait for a start bit

for(i = 0 ; i < 11 ; i++)
  data[i] = pulseIn(irPin, LOW);      //Start measuring bits, I only want   low pulses

  for(i = 0 ; i < 11 ; i++)             //Parse them
  {
    if(data[i] > bin_1)                 //is it a 1?
data[i] = 1;
else if(data[i] > bin_0)            //is it a 0?
data[i] = 0;
else
return -1;                        //Flag the data as invalid; I don't know what it is! Return -1 on invalid data
  }

  int result = 0;
  for(i = 0 ; i < 11 ; i++)             //Convert data bits to integer
    if(data[i] == 1) result |= (1<<i);

  return result;                        //Return key number
}

```

The ouput values are 3-digit numbers which work OK and i'm not even checking the value here. Just if something came in. And it doesn't bloody work!!!!

## Stuff i've already checked

* The circuit
* If the pin works
* If the timers are set correctly
* Using adafruits library
* Changing every possible core
* If the receiver works
* The wiring

# Answer
> 1 votes
If you are trying to toggle the LED when a signal comes in, then there is a glitch in the code and I have no idea how the UNO worked for you as I tried and it only spat out Serial, but didn't do anything with the LED.

Try changing this line of code:

`state != state;`

**to**

`state = !state`

you are not actually toggling the LED `state` with the other line, but instead doing a logical `not equal to` which won't do what you want.

---
Tags: attiny, ir, isp
---


# Question
Title: Arduino/DuinOS vs Normal C/ARM Programming
I'm trying to understand the difference between programming Arduino hardware (Atel/ARM based) versus 'normal C-based ARM programming'.

My *understanding* is that the Arduino language is cross-compiled into C-compatible binary, and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip, which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

My *understanding* is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

I'm sure I'm mucking up a few things here, but this is my general understanding: can someone correct/clarify these things for me?

# Answer
> My understanding is that the Arduino language is cross-compiled into C-compatible binary,

There is no "Arduino language". Programs are written in C++ or C, and the IDE mangles them in certain ways in order to ease development by beginners (and on occasion frustrate development by veterans).

> and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip,

No. The uploading of the compiled code is done using a separate program, usually AVRDUDE or bossac, and the code is uploaded into flash. Data can be optionally uploaded into EEPROM via the same program, but this is not required.

> which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

Not by default. If you want to use DuinOS then you will need to download, compile, and upload it yourself.

> My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

Nope. Any system can be run without an OS.
> 3 votes

---
Tags: arduino-uno, c, isp
---


# Question
Title: When and where do I have to worry about accounting for sensor "noise"?
I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!

Being brand new to electronics/robotics, I was shocked that something as simple as a pushbutton required his `debounce` behavior. That's something I would have never thought about in a million years. What is the 'rule of thumb' for when this type of `debounce` behavior (regardless of what sensor we're talking about, pushbutton or otherwise) must be accounted for? Is it simply that any type of *analog sensor* can generate this kind of unexpected 'noise'?

Can someone provide other examples for when special code must be put in place to accommodate unexpected sensor noise?

# Answer
Switch bounce is a physical issue that can be cleaned up with filtering. Since the sense states are very simple, only very crude (time-based) filtering is required to clean up its signal.

Other mechanical sensors that can exhibit similar characteristics are bump sensors, tilt sensors, and accelerometers. Bump and tilt sensors are also very simple, and similar filtering will clean up their signals.

Accelerometers on the other hand react to very minute perturbations, so they may require more advanced filtering based on the application they will be used in; orientation sensing can use time-based filtering, whereas things such as motion tracking including dead reckoning will require one or more layers of calculus in order to clean up the signal.
> 1 votes

# Answer
Anyone who believes sensors do not have noise has never used one. True you may not encounter noise while reading the digital information, but I promise you the information will have noise in it. Noise from a switch can be dealt with by hardware or software, such as his debounce behavior. Other sensor noise is 4 years of study at college. Look into Kalman Filters, probabilistic robotics. Even the self driving cars you hear about currently require large compute capacity, mostly in order to deal with sensor noise.
> 0 votes

---
Tags: arduino-uno, sensors, analogread, analogwrite
---


# Question
Title: How to tell what components are compatible with Arduino Due?
I am interested in using the Arduino Due in an upcoming project, however I am worried that the other shields/components that I need will not be compatible with it, because, according to that link:

> The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0 Arduino pinout.

The components I need to use are:

Essentially a solar panel will power the energyShield (rechargeable battery), which in turn will power multiple servo motors.

I cannot tell if the energyShield uses the 1.0 pinout or not. I am also worried that since the the solar power generates 6V it will overload the energyShield which is rated at 3.3V. At the same time, I am worried that the servo motors, which seem to require 4.8V, will not be capable of being powered by the energyShield which outputs 3.3V. Thoughts?

Bonus Points if someone can explain to me what the "1.0 Pinout" is, and whether it is the latest/most modern pinout available for Arduinos.

# Answer
As far as I understood this energyShiled accepts any input between 5-24V and output 5 - 3.3V. This specs are compatible with arduino Due. And with the solar panel.

You can always power servos from seperate source or from the same battery but with seperate direct line.
> 2 votes

---
Tags: motor, arduino-due, electronics, solar
---


title: Arduino: Breadboards and PCBs

text:
# Question
Title: Arduino: Breadboards and PCBs
I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!

In the video, the author is using a breadboard for prototyping his circuit. What's the next "step up" from this? In other words, say I get my breadboard circuit working perfectly, is it now time to create a PCB? If my understanding of circuitry is correct, this is *not* a trivial process. I would need a CAD program to design my circuit, and it would likely be very expensive to get the design actually fabricated. At least too expensive for simple hobby purposes. **Is there a middle ground between breadboard and PCB?**

# Answer
> 3 votes
You can build your project on stripboard (aka Veroboard, which is a particular brand). The wiki page at http://en.wikipedia.org/wiki/Stripboard covers most of the salient points - it is essentially a generic PCB. You can cut tracks, either with a knife, or a specialized tool, and you can solder your parts on to the tracks.

They come in various configurations - my personal preference is just straight strips - and you can cut them to size with a hacksaw.

If your project is non-trivial, you might still like to spend some time working out a decent layout. There are free, and not quite free, products to help you - I use Kicad, which is free & opensource, there are many others.

I have also used stripboard to group a few components together - for example, 2 7-segment displays and two SIPO chips to run them - this can then be a "component" for future bread-board projects.

# Answer
> 0 votes
Eagle CAD is one of the most popular E-CAD programs, and is reasonably priced free for personal use. When Libraries, tutorials and examples are made available it is most often in Eagle CAD format.

Once you ready your design and layout (in Eagle) you can get boards made for $30ish (https://oshpark.com/)

You will have to obtain parts and solder yourself for assembly, but your time is free, right? I have done a few. I was a software only person until I started in November 2014 (http://www.spiked3.com/?p=5981)

# Answer
> 0 votes
If you are only making one or two the following works well:

1. Download Kicad (Free) and design your board.
2. Print out the layout on special film, and transfer to a blank PCB using a domestic iron.An example: http://www.maplin.co.uk/p/press-and-peel-film-pcb-transfer-system-ab15r
3. Etch the board in ammonium persulphate or ferric chloride solution.
4. Drill the holes. You will need some 0.8 and 1.0mm drills and a Dremel drill press or similar.
5. Mount your components and solder away.

The above works well for single-sided boards. Double sided are possible, but will take some practice.

There is a learning curve getting to grips with Kicad, but if you are serious about electroncs, the time invested is well worthwhile. I got from being a Kicad novice to producing a specialist Arduino shield in a weekend. I had the advantage of having used similar tools in the past, and the disadvantage of being 67 years old (with eyesight to suit)

All the required parts should be available from agood electronics parts suppier (For example Jaycay here in New Zealand)

# Answer
> 0 votes
> Is there a middle ground between breadboard and PCB?

A prototype PCB with breadboardlike layout is a fast way to turn a breadboard design into a permanent build. So it may be in the range of valid answers to your question.

(-: *The link below is just an example, there are lots of other names, designs and sellers and I am in no way releated to any of those...* :-)

https://www.tindie.com/products/Schmart/400-tiepoint-schmartboard-breadproto-board-bundle/

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