# Question
Title: How can one use the SPI hardware on the Arduino Nano?
I recently prototyped and programmed a system that used some SPI sensors on an Arduino Uno. I wanted to get the size down a bit, so I was thinking I might buy an Arduino Nano and re-wire my system around that. The problem is that I have seen mention of SPI not working on the Nano. From the Nano product page:

> These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

Yet I have also seen mention of SPI working on this board, or at least people saying that it should. Someone asked a similar question on Stack Overflow and was told that it should work with the same level of support as I2C, even if it isn't built in to the core framework. But that answer does not definitively answer the question of whether SPI *does* work, and it doesn't explain any caveats that one may come across. In this question, the OP's premise is that their SPI device works on the Nano but not on other boards; this seems to be a strong indication that SPI *does* work.

I figured it would be worth it to buy a Nano 3 and see if it worked. SPI devices did not work on that board, including the same radio module mentioned in the question linked to above. So, I am inclined to believe the Arduino product page when they say it isn't supported. But that still isn't satisfactory, and it is the opposite conclusion from that of the other questions: **The hardware is all there and the software framework is in place, so what does one need to do to make SPI work on the Arduino Nano?** Why is it that some sources say it works while others say it doesn't?

# Answer
> 3 votes
Yes, the Nano supports SPI when used with a modern Arduino version, and no, you do not have to do anything special to utilize it on this board.

The information you found that seems to suggest something to the contrary is simply a result of the fact that that the web page for the Nano is sadly out of date date and does not reflect the current state of the Arduino libraries which support SPI on this processor and hence board.

In terms of components, the Nano it is very nearly just a form-factor shrink of the discontinued Duemilanove, and in the current version updated to an an ATmega328p it has capabilities essentially comparable to an Uno, differing primarily the in the USB interface which has nothing to do with SPI.

In terms of what is wrong with the web page, if we examine archive.org's records for the page of the comparable Duemilanvoe, on September 15th, 2010 it said:

> SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

But a few days later on September 26th, 2010 it had been changed to say:

> SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the SPI library.

Although the page for that once-flagship product was updated to reflect SPI support nearly six years ago, they've not yet made a corresponding correction to the Nano page. But as the difference is in the software and the same software is used in either case, the addition of SPI support to the Duemilanove was also automatically an addition of that support to the Nano.

# Answer
> 0 votes
In this Nano schematic, I see MOSI, MISO & SCLK on pins J1-14, J1-15 & J2-15.

On this page I see a SPI library.

The Nano is not specifically listed in the latter link. However the Nano and other Arduino boards are similar.

---
Tags: arduino-nano, communication, spi
---


title: Getting Firmata to control WS2801 LEDs

text:
# Question
Title: Getting Firmata to control WS2801 LEDs
I am trying to control a strip of WS2801 LEDs through an arduino uno running firmata from Python on my laptop.

I've written some basic code based on adafruit's library here (from line 187):

```
from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
import time

leds = [(255, 255, 0), (255, 255, 0), (0, 255, 255)]

uno = PyMata3()

uno.set_pin_mode(2, Constants.OUTPUT)  # signal
uno.set_pin_mode(3, Constants.OUTPUT)  # clock

def show(leds):
    for pixel in leds:
        for channel in pixel:
            i = 0b1
            for x in range(0,8):
                if i & channel:
                    uno.digital_write(2, 1)
                else:
                    uno.digital_write(2, 0)
                uno.digital_write(3, 1)
                uno.digital_write(3, 0)

                i = i << 1

    uno.digital_write(3, 0)
    time.sleep(0.001)

```

When I run the code it seems to run ok, but only the first LED will light up. I think (too quick to be certain) that it flashes through all the colours - ie displaying each colour rather than passing them through.

I'm wondering if there is something wrong with the timing for the clock pin making it latch, but I'm grasping here.

# Answer
> 0 votes
You cannot do precise timing of I/O mediated by USB like that. Regardless of the serial baud rate in use, the USB mode utilized basically puts a 1ms minimum interval between any two distinct *communication* operations.

Providing there are no intervening reads, if firmata is coded to deliver its data to the host's serial API in buffers matching or exceeding the USB packet size rather than individual writes for each command, it is possible that "keeping the pipe full" may mean that commands are able to be executed without such gaps, but any little interruption could introduce a problematic delay.

The key problem with delay is this part of the data sheet:

> CLK pin keeps low more than 500uS will make the WS2801 internal status register reset, and at this moment, the gray scale data in the data shift registers will be latched.

Basically, that says that you need a clock low pulse of more than a half millisecond to start the process, but by extension it also means that all of the subsequent clock pulses have to be shorter than that or you will inadvertently reset the process, and this is not something you can easily achieve reliability of with a USB bus of the type utilized here mediating your software manipulation of the clock line.

**Essentially, don't try to bit-bang things with Firmata.** You should send the desired intensity values across the USB as byte data, and then have software running on the Uno clock this data out in accordance with the WS2801 timing requirements.

Personally, I'd just write that as an ordinary sketch reading the Serial input - no need for firmata. You can still feed the data from python on the host if you like, or anything else that can push data over a serial port.

# Answer
> 1 votes
It's possible that time.sleep is causing a latching issue. You should instead use pymata-aio's sleep function:

```
uno.sleep(0.001)

```

The documentation for it can be found here: http://htmlpreview.github.io/?https://github.com/MrYsLab/pymata-aio/blob/master/documentation/html/pymata\_aio.html#module-pymata\_aio.pymata3

You could also try a different pin and see if you still have the issue?

---
Tags: led, adafruit, python, rgb-led, firmata
---


# Question
Title: Serial Communication to WPF (Windows Presentation Foundation) giving me odd results. How do I clear up the Strings I am receiving?
I'm trying to make a voltage/temp logger that will post to SQL. I'm using a WPF to make kind of a UI for people to measure the voltage of a cell, and take the temp of the battery acid in the battery. My end goal is to have the Arduino Bluetooth to a computer. the computer will handle all the SQL. The Arduino will have a physical button to post or save the data to my SQL server. Also the Arduino will have a little display to display the battery S/N, Voltage, Temp. (Side Question: Am I going to be able to do the screen and access the serial, with also sending the serial data over Bluetooth?)

My problem is that when I call my function to get that data sometimes it comes out messed up. Sometimes I get, for example: "3.1234 V=" Or "V= 3.123V=" It also happens with the temperature, sometimes I get the voltage in the temp box and vice versa.

More times than not I get a bad result. When I run it in the Serial Monitor with the Arduino IDE It looks fine. Does anyone have any advice how I can clean up the communication and get more reliable results?

Thanks for any help!

I'm using to place the serial port string into a textbox.

```
txt_Volt.Text = sp.ReadExisting();

```

I tried using the `Serial.flush();` to clear out any old stuff to no avail.

The Arduino code:

```
else if (c == '3')
 {
   int analog_value = analogRead(A0);
   volt = (analog_value * 5.0) / 1024.0;
   Serial.print("v= ");
   Serial.print(volt, 5);
   Serial.flush();
}

```

Arduino `loop()`:

```
void loop() {
  if (Serial.available() > 0)
  { Serial.flush();
    char c = Serial.read();
    if (c == '1')
    {
      digitalWrite(13, HIGH);
      Serial.println("LED is On");
      Serial.flush();
    }

    else if (c == '0')
    {
      digitalWrite(13, LOW);
      Serial.println("LED is off");
      Serial.flush();
    }
    else if (c == '3')
    {
      int analog_value = analogRead(A0);
      volt = (analog_value * 5.0) / 1024.0;
      Serial.print("v= ");
      Serial.print(volt, 5);
      Serial.flush();
    }
    else if (c == '4')
    {
      //Temp Function go HERE
      getTemp();
    }

```

C# CODE:

```
         private void Connect_Click(object sender, RoutedEventArgs e)
         {
           while (portNum >= 0) //automaticly connect to correct port.
           {
            try
            {
                String portName = "COM" + portNum;
                comportno.Text = portName;
                //String portName = comportno.Text;
                sp.PortName = portName;
                sp.BaudRate = 9600;
                sp.Open();
                status.Text = "Connected";
            }
            catch (Exception)
            {
                portNum--;
                // MessageBox.Show("Please give a valid port number or check your connection");
                if (portNum == -1)
                {
                    MessageBox.Show("Could not find Arduino\nCheck Connection");
                }
            }
        }

    }

    private void Disconnect_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            sp.Close();
            status.Text = "Disconnected";
        }
        catch (Exception)
        {

            MessageBox.Show("First Connect and then disconnect");
        }
    }

    private void on_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("1");
        rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 255, 0));
        // DebugWindow.Text = sp.ReadExisting();
        //  readingStuff();
    }

    private void Of_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("0");
        rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0));
        //  DebugWindow.Text = sp.ReadExisting();
        //  readingStuff();
    }

    private void Get_Volt_On_Click(object sender, RoutedEventArgs e)
    {

        sp.Write("3");
        string volts = sp.ReadExisting();
        int volt_length = volts.Length;

        bool isLetter = !String.IsNullOrEmpty(volts) && Char.IsLetter(volts[0]) && Char.IsDigit(volts[volt_length - 1]);

        if (isLetter)
        {
            DebugWindow.Text = volts;
        }
        else
        {
            DebugWindow.Text = "Error";
            sp.Write("3");
        }
    }

    private void Get_Temp_On_Click(object sender, RoutedEventArgs e)
    {
        sp.Write("4");
        txt_Volt.Text = sp.ReadExisting();
    }

    void readingStuff()
    {
        String comdata = sp.ReadLine();
        Dispatcher.Invoke((Action)(() => DebugWindow.Text += "Data\n" + comdata + "\n"));
    }

```

What a bad result looks like:

A Good result:

# Answer
Your problem arises from a mix of newline-terminated and un-terminated messages.

The newline terminated values probably would work by themselves as you can use a `ReadLine()` type method to wait until they have been completely transferred.

But the non-terminated attempts such as your use of the `ReadExisting()` method cause a problem - these likely fetch whatever has been received *up to the time of the call* but that will not necessarily be the full message sent (or even anything at all). Whatever is left over (had not been received by the time of the call) will become the beginning of the data achieved during the next partial or until-newline read.

As a solution you should probably either:

* Terminate each message with a newline

or else

* Always read only complete lines, and then *parse* individual messages out of them

or

* Always read until you find some delimiter character such as a space or comma, *or* a newline. You may have to write your own read method to accomplish this.

*Using delays to try to fix a problem like this is bad practice as it is fragile and can easily break if there is an unexpected delay on the other side, or if the execution speed of one of the components changes*. A number of fragile techniques that generally worked with true serial ports subsequently broke when USB converters were introduced in the middle, as USB bunches data into packets with gaps in between, a behavior not necessarily previously seen in many pure serial implementations.
> 1 votes

---
Tags: serial, bluetooth, arduino-leonardo, c#
---


# Question
Title: Unstable system when controlling power to serial peripheral devices and sleeping
In the process of trying to make a small system that will last a while on 4 AA batteries, I've reduced my Arduino project to a barebones system that when asleep draws a tiny amount of current from the batteries.

However, to achieve this, I found it would be necessary to cut power to the two attached peripheral devices (connected to an ATMega328P-PU). One of them is an I2C device, and the other is a serial device, and both are attached to the hardware serial/I2C pins as appropriate.

In terms of powering the peripherals, the bases of two transistors are connected to two of the digital pins, and power to them is controlled from code via these transistors. Both devices are 5V, and when the system is running the total current draw is around 200mA.

Basically this setup works, however I'm getting "random" system hanging and essentially an unreliable project. Sometimes when I power it up it will work as normal, but then hang and not sleep. Other times, it will sleep, but then freeze after waking or just get stuck during waking (which I can tell because the serial device powers up first and does nothing, but the I2C device remains off).

My best guess is the root of the cause is either something to do with the serial communication being interrupted by sleeping the MPU (I'm using the maximum power saving sleep, which is woken by an external interrupt on pin 2), or possibly some sort of power problem (sudden current draw from battery?) that occurs when the peripherals are powered on in code (though I don't know how I should test this).

So far, I've tried calling `Serial.end()` before sleeping the MPU, and `Serial.being(9600)` on waking, and have scattered `delay(1000)`s throughout to ensure everything has enough time to get running, but the problem still remains.

Does anyone have any pointers on things I could change/test, or an alternative approach I could take to make the same power savings?

EDIT: Some more details

The transitors used are TIP 120's. The connections are essentially an exact copy of the image here: https://ctheds.files.wordpress.com/2007/10/tip120.jpg, except the resistors used are 560 Ohms (just what I had to hand, no other reason, didn't think it would change anything).

The I2C peripheral is a 20x4 LCD (which I believe is HD44780 compliant). The serial device is an GT511C3 fingerprint sensor. I don't believe either of them have any automatic power saving features, though I haven't looked for such things in the documentation explicitly.

The exact code I use to call sleep is

```
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_mode();

```

which I'm lead to believe is the lowest power mode, and aside from this problem works well for my system.

# Answer
Using an NPN transistor to control power to a peripheral may be problematic.

An NPN transitor would presumably be used as a `low-side switch` interrupting the peripheral's ground line, however, even when turned on this will have a non-trivial voltage drop.

Most logic level definitions are asymmetric, ie, the maximimum legal voltage for a logic "0" is relatively low. If you insert the voltage drop of a bipolar transistor into a peripheral's ground line, then it may be borderline unable to drive a fully legal '0' to the ATmega, which is reference to the lower true ground and would see the peripheral's ground difference added to its output voltage.

A better approach would be to use either a high-side switch (as there is typically more room between the minimum legal '1' and the supply) or else to use an FET switch which would have a much lower voltage drop.

Also keep in mind that most IC's are not specified to tolerate lasting I/O voltages much outside of the range of their power suppliers, and in fact their protection diodes may mean that application of such voltages effectively powers them through the I/O pin. So before turning off power to a peripheral, you probably want the ATmega software to assert all shared I/O lines towards the side of the peripheral supply which is not being disconnected, ie, for a low side switch drive everything high and for a high side switch drive everything low.

Finally, the process of power cycling could potentially confuse peripheral interface engines and it is possible that some error flags set in this process might never be cleared. So you may want to clear the flags of and generally re-initialize your USART, I2C, etc on resume.
> 1 votes

# Answer
I hear great things about the cosa core for Arduino. It's a fantastic alternative Arduino core and exposes the power management capabilities of the micro-controller that are not exposed by the standard Arduino core.

You might find it is too different for your experience but then again it is excellent and worth a look.

https://github.com/mikaelpatel/Cosa
> 0 votes

---
Tags: serial, power, i2c, interrupt, sleep
---


# Question
Title: Trouble using lcd.readButtons() in RGBLCDShield library
I am trying to create a state machine that loops in whatever state it's in until a button is pressed. I am using the **Adafruit\_RGBLCDShield** library along with the LCD shield and 16x2 display. For some reason the buttons aren't being detected at all. Here is the code for one of the states:

```
    case STANDBY_MODE:
  lcd.clear();
  lcd.setBacklight(0x0);
  delay(100);
  noInterrupts();
  digitalWrite(fire, LOW);
  digitalWrite(chg, LOW);
  digitalWrite(trig, LOW);
  analogWrite(eprgm, 0);
  // Wait for button press
  while(1)
  {
    button = lcd.readButtons();
    if(button)
    {
      showLCD();
      t0 = millis();
      state = NO_CHARGE;
      analogWrite(eprgm, (vSet*0.0204)/5);
      interrupts();
      return;
    }
  }
break;

```

In this state, the system turns off all outputs and display and waits for a button to be pressed. For some reason, though, it doesn't respond when I press the button. Is there something missing here?

# Answer
IMO, your post doesn't provide enough information to allow definitive problem diagnosis.

Why do you say `noInterrupts();` at line 5? Some versions of the Wire library might be interrupt driven\[1\]. If interrupts were off, such a library wouldn't detect any button presses on a TWI-interfaced shield like Adafruit's RGBLCDShield.

\[1\]: Per arduino.cc's WireLibraryDetailedReference page, “"The AVR TWI is byte-oriented and interrupt based...." (section 21.6 on p. 224) ... The TWI module sends an interrupt when it finishes, to notify the processor of the change in conditions ... However, notice that the Wire library has blocking I/O. ” \[Ie, the usual Wire library doesn't take advantage of TWI interrupts.\]
> 0 votes

---
Tags: arduino-uno, lcd, shields, button
---


title: Possible to condense this if statement?

text:
# Question
Title: Possible to condense this if statement?
I have this if statement:

```
if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

```

Is there a way to condense that for the purposes of saving on some bytes?

Ultimately trying to say "At 5:10 every weekday do X"

# Answer
The following saves a couple of program bytes (but no RAM) when `now` is a structure with a byte called `DayofWeek`:

```
 if ((byte)(now.DayofWeek+249)>250) ...
   -vs-
 if ((now.DayofWeek != 1 && now.DayofWeek != 7)) ...

```

It might save slightly more than that in your case, where `now.dayOfTheWeek()` appears to be a function reference. This technique will work if function `now.dayOfTheWeek()` returns a `byte`, that is, an `unsigned char`. The technique depends on value 7+249 overflowing to zero in byte arithmetic when truncated to a byte, because 7+249 is 0 modulo 256.

The cast to `byte` \[or `uint8_t`\] of `now.DayofWeek+249` is needed because of `int` promotion as Edgar Bonet pointed out.
> 2 votes

# Answer
Yes. The method now() Returns the current time as seconds since Jan 1 1970. Simply keep tract of all your time this way and you only need to test this one value.

The Arduino is not a good source of time over long periods. Consider using an RTC (Real Time Clock) chip. This Arduino page links to this page which talks about an RTC. (I will leave it up to you to research any compatibility issues.)

Many RTCs contain a register set specifically designed to handle tasks such as you outlined above. For example, setting alarms off on weekdays only or on specific days of the month.

If absolute time is not important in your application I would try the following code outline. Each test only has 2 operands:

```
// Turn on Arduino on Monday at the time task is to be performed.  Task
// should be performed at that time on Monday, Tuesday, ... Friday.
// Nothing should happen on Saturday & Sunday.  Then cycle repeats.

// Set time to zero.

// Count through days (0, 1, 2, ...).

// Wait each day until number-of-seconds is greater then seconds-in-a-day
// times the day number.

// If day number is 4 or less do activity.  Else skip activity.

// If day number is more than 6 set the day counter to 0 and set the time
// to zero.

```

If you want to start the Arduino at arbitrary times, set the initial Arduino clock value to the number of seconds from the time the activity would have been performed on Monday and initialize the day counter to the appropriate value. For example if you started the Arduino on Tuesday 23 hours after the time the activity should have happened on Monday set the Arduino clock to 23 * 60 * 60 seconds and initialize the day counter to 2. Of course you can calculate the initial day counter value using = initial\_number\_of\_seconds / 60 * 60 * 24.
> 1 votes

---
Tags: code-optimization
---


# Question
Title: why are there odd spikes in the USB serial data transfer rates?
I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.

I looked into the serial communication using the simplest program I could, but it produces odd results.

```
void setup() { Serial.begin(9600); }
void loop() { Serial.println("00000"); }

```

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.

Using the seconds as a marker, I then count the number of data lines for each second. for example:

```
44 00000  // recorded at time 44 seconds
44 00000
44 00000
45 00000  // recorded at time 45 seconds, etc

```

I was expecting that there would be a somewhat stable value for this. Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second. When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.

Collecting the zeros for 5000 seconds produced the following results: most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000. This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.

What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.

Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created. That isn't too bad and could be due to timing.

But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.

The percent breakdown is as follows:

```
137 sets of 00000:  79.15%
138 sets of 00000:  13.8%
139 sets of 00000:  0.39%
140 sets of 00000:  0.51%
141 sets of 00000:  2.05%
142 sets of 00000:  4.11%

```

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain. with 137 sets of 00000 there are 685 characters sent serially in one second.

with 142 sets of 00000 there are 710 characters sent serially in one second.

What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

Is there any explanation for the variability?

Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.

I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.

Using a delay of 8ms produced another interesting result: with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters. this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.

After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.

This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets. The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.

I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second. What could be causing this? and what can be done to make the transfer rates more constant?

# Answer
While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.

As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its *origin* just by looking at the timing of its *arrival*. That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.

A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino. That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.

If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.
> 1 votes

# Answer
This could be largely to do with how USB serial works.

USB has a number of different methods of transferring data between the device and the host. Both CDC/ACM use FT232 use a method called *bulk transfer*. This is a very low priority transfer method and data is moved across the bus as and when it can - that is, when the bus isn't doing anything else. If there is anything else happening on the bus (and there will be) the transfers get delayed until the bus is doing nothing else.

If timing is critical for a protocol, such as USB audio or video where you have to have the data transferred to the host absolutely right now a different method is used. This is called *isochronous*. It is the highest priority of data transfer, even higher than interrupt data.

However there is no way on the Arduino to use any form of isochronous transfers so you will have to come up with some other method of managing your timing.

As Chris has mentioned the most common method is to include a timestamp with each packet of data. That packet may contain just one sample, or it may contain a block of samples. The important thing is to know when the block starts and from that infer the time of each sample within the block.

It is also important to ensure that your communication with the host isn't running at 100% saturation. You should be running at the highest baud rate that is reliable and only send data at regular intervals giving you time to get the data in between each transfer. Keeping your data packets as small and efficient as possible is also good for keeping you transfer rate sustained properly.
> -1 votes

---
Tags: serial
---


title: Refactor to save bytes?

text:
# Question
Title: Refactor to save bytes?
I'm a painful 128 bytes of my max for this Trinket. Any refactoring I could do to get down the size?

```
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);

const long fadeTime = 10 * 60000L; // X minutes
const int colorStops = 255;
const int delaySpeed = fadeTime / colorStops;
const int notes[] = {262,294,330,349};
const uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  rtc.adjust(DateTime(__DATE__, __TIME__));

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  // If it's 5:10 am on a week day, start the fade in
  if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,i));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
         strip.setPixelColor(np, strip.Color(random(50,255),random(50,255),random(50,255)));
      }
      strip.show();

      beep(notes[random(0,3)]);
      delay(100);
    }

    turnOffPixels();
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
  {
    digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

void turnOffPixels() {
  for(int np = 0;np<strip.numPixels(); np++){
    strip.setPixelColor(np, strip.Color(0,0,0));
  }
  strip.show();
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    turnOffPixels();
    return true;
  } else {
    return false;
  }
}

```

Error...

```
Sketch uses 5,438 bytes (102%) of program storage space. Maximum is 5,310 bytes.
Global variables use 97 bytes of dynamic memory.

```

# Answer
Remove the `rtc.adjust(DateTime(__DATE__, __TIME__));`. You only need to set the RTC once, after e.g. you insert the backup battery.

Change

```
pinMode(BTNPIN, INPUT);
digitalWrite(BTNPIN, HIGH);

```

to

```
pinMode(BTNPIN, INPUT_PULLUP);

```

Inline the beep function using the `inline` hint:

```
inline void beep(int delayAmount)
...

```

Shorter `beep` function:

```
inline void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000; t += delayAmount)
  {
    digitalWrite(TONE,t & 0x01);// HIGH is odd, LOW if even
    delayMicroseconds(delayAmount);
  }
}

```
> 2 votes

# Answer
On a quick test build for an ATmega328p type Arduino, the implementation of random() and its unique dependencies seems to be about 180 bytes, so you might see if there's a more compact way of achieving your need there, perhaps using the low byte of some mathematical expression of the time, and just retrying until you get an in-range value.

Of course if you get really stuck, you could remove the bootloader and program it with ISP from an ordinary Arduino or something like that.
> 1 votes

# Answer
Very good suggestions so far. I have only one to add: instead of `strip.Color(0,0,0)` use just the constant number 0. This saves a function call.
> 1 votes

# Answer
For refactoring, consider using a `for` loop that executes twice, once for the “// Fade in light” section of code, and once for the “// Play tone after light fully bright” section. For parts of the code that differ, test the loop index and do one action or the other.

Here are two ways to get rid of a few (eg 54) bytes of code:

1. Instead of

```
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);
 ...
 for(int np = 0;np<strip.numPixels(); np++){
 ...

```

(with three instances of the latter), say something like

```
enum {numPixels = 5 };
Adafruit_NeoPixel strip = Adafruit_NeoPixel(numPixels, LEDPIN, NEO_RGB);
...
for (byte np=0; np<numPixels; ++np){
...

```

This will save about 40 bytes (10 bytes per `for`, and another 10 probably due to `strip.numPixels()` code not linking). (Note, the savings is due to getting rid of function calls; the change from `int` to `byte` apparently makes no difference in program size, probably because the compiler optimizes `int` to `byte` where its analysis shows it can do so.)

2. Instead of

```
if (... && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

```

say

```
if (... && now.dayOfTheWeek()+250>250){

```

which will save 14 bytes. This works as explained in my answer to your previous question. However, I've written `+250>250` here instead of the `+249>250` there because according to `RTClib` documentation and `RTClib.cpp` code, `.dayOfTheWeek()` returns 0 for Saturday, rather than 1 as you seem to expect.

3. Possibly inline `beep()`, since you call it only once.
> 0 votes

---
Tags: code-optimization
---


title: convert String to unsigned long long

text:
# Question
Title: convert String to unsigned long long
i want to convert string for example "68976543210" to unsigned long long(64 bit) in mega2560, do is possible?

```
String x="68976543210";
unsigned long long y=?;

```

# Answer
avr-libc lacks `strtoull()` that I would normally use for such a conversion. You will have to do it manually.

Fortunately it's quite simple - just start with y=0 and, for each character in the string, multiply y by 10 then add the numeric value of the character in the string:

```
String x = "68976543210";
unsigned long long y = 0;

for (int i = 0; i < x.length(); i++) {
    char c = x.charAt(i);
   if (c < '0' || c > '9') break;
   y *= 10;
   y += (c - '0');
}

```

Note that the Arduino Print API has no method for printing a 64-bit integer.
> 3 votes

---
Tags: arduino-mega, string, convert
---


title: Pin toggle speed

text:
# Question
Title: Pin toggle speed
If I use direct port manipulation, what is the average number of clock cycles it takes to flip a pin on the arduino

ie.

```
void loop(){
  PORTB |=  0b00010000;
  PORTB &= ~0b00010000;
}

```

So how fast is this generally?

# Answer
If you compile the code and examine the results you can see how many instructions it will take, and thus how many clock cycles.

It's slightly more complex because of what else happens in main() to call loop, but basically you have:

```
for (;;) {
loop();
  aa:0e 94 49 00 call 0x92; 0x92 <loop>
if (serialEventRun) serialEventRun();
  ae:20 97       sbi wr28, 0x00; 0
  b0:e1 f3       breq.-8      ; 0xaa <main+0x10>

00000092 <loop>:
  92:2c 9a       sbi0x05, 4; 5
  94:2c 98       cbi0x05, 4; 5
  96:08 95       ret

```

So you can see there is:

```
Operation                            Cycles
Call loop()                          4
Check if serialEventRun exists       2
Since it doesn't, got start of loop  2

```

Then in loop:

```
Set bit                              2
Clear bit                            2
Return                               4

```

So in total you have 16 clock cycles. At 16MHz that gives you a frequency of 1MHz - however that won't be a square wave of 50% duty cycle since there is much less time between set and clear than between clear and set. The full 16 cycles, mapped to the state of the IO pin, would look like this:

```
             _
 _ _ _ _ _ |   | _ _ _ _ _ _ _ _
| call  |sbi|cbi|  ret  |chk|bra|
 . . . . . . . . . . . . . . . .

```

You can get a much tighter operation by wrapping the pin manipulation in a `while (1)` loop:

```
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    PORTB &= ~0b00010000;
  }
}

```

That reduces down to just:

```
00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:2c 98       cbi 0x05, 4; 5
  96:fd cf       rjmp .-6      ; 0x92 <loop>

```

That's `sbi` (2) `cbi` (2) and `rjmp` (2). A total of 6 clock cycles. At 16MHz that's 2.667MHz. Again, though, not a 50% duty cycle, since the `rjmp` takes two extra clock cycles:

```
     _
 _ |   | _ _
|sbi|cbi|jmp|
 . . . . . .

```

By inserting a pair of 1-cycle `NOP` instructions you can even out the duty cycle and make it 50%:

```
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    asm volatile("nop");
    asm volatile("nop");
    PORTB &= ~0b00010000;
  }
}

00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:00 00       nop
  96:00 00       nop
  98:2c 98       cbi 0x05, 4; 5
  9a:fb cf       rjmp.-10     ; 0x92 <loop>

     _ _ _
 _ |       | _ _
|sbi|n|n|cbi|jmp|
 . . . . . . . .

```

Now, of course, it's 8 clock cycles, so at 16MHz that's 2MHz output, but with 50% duty cycle.

Incidentally, all these instruction timings are available in the Instruction Set Summary chapter of the ATMega328P data sheet.
> 4 votes

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


title: ESP8266 Battery Monitor

text:
# Question
Title: ESP8266 Battery Monitor
Is there a way to monitor the battery that feeds an esp8266 in a portable project?

I have been meaning to implement that feature into my project so that i can be warned when the battery runs low on juice but i don't know if the esp has some kind of onboard sensor to do that.

# Answer
There are two things you need to measure the battery of the system that is doing the measuring of the battery:

1. An analog-to-digital converter
2. Some form of fixed voltage reference to compare the battery voltage against.

Some ESP8266 modules have a single analog input available, and some don't. You need to check which module you have and which pins are available on it.

Then you need to use the ADC to measure the fixed known voltage. That could be from a small LDO voltage regulator that is below the voltage of the minimum voltage you will care about from your battery, or something like the forward voltage drop of a silicon diode (~0.7V) - something where you know what the voltage is.

From that reading you can then back-track what the supply voltage must be in order to give you the reading it has given you. As the battery voltage drops the voltage range the ADC will be measuring will be reduced, and so the fixed voltage will rise within that range giving you higher readings from the ADC.

Here is a snippet of code I use with the 1.1V internal voltage reference of the ATMega328P to calculate the supply voltage:

```
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

```

Of course, you need to change that to use the analog input of the ESP8266 instead (probably just using analogRead()). And of course change the ADC-scaled voltage. The formula is basically:

```
Vref * ADCmax / ADCreading

```

So if you have the 1.1V reference as above, and the ADC can read 0-1023, then it's:

```
1.1 * 1023 / reading

```

Or, pre-calculate the first half of the sum:

```
1125.3 / reading

```

To keep it as integer mathematics work in millivolts instead of volts by multiplying the reference voltage by 1000:

```
1125300 / reading

```

And that, as you can see, is what is in the function above.
> 4 votes

---
Tags: esp8266, battery
---


# Question
Title: Where could I find the "Serial.find()" source code?
As written in the title, could you tell me where to find the source code of the function "Serial.find()"?

I haven' t installed the Arduino IDE, so I'm glad if you could me link a web resource, or if you directly copy the source code here .

Thanks for your time.

# Answer
> 1 votes
It is part of the Stream class which the Serial class inherits from.

It just calls `findUntil()` which is a little further down in the same file:

That itself calls `findMulti()` which is where all the magic happens:

---

```
int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
  // any zero length target string automatically matches and would make
  // a mess of the rest of the algorithm.
  for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
    if (t->len <= 0)
      return t - targets;
  }

  while (1) {
    int c = timedRead();
    if (c < 0)
      return -1;

    for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
      // the simple case is if we match, deal with that first.
      if (c == t->str[t->index]) {
        if (++t->index == t->len)
          return t - targets;
        else
          continue;
      }

      // if not we need to walk back and see if we could have matched further
      // down the stream (ie '1112' doesn't match the first position in '11112'
      // but it will match the second position so we can't just reset the current
      // index to 0 when we find a mismatch.
      if (t->index == 0)
        continue;

      int origIndex = t->index;
      do {
        --t->index;
        // first check if current char works against the new current index
        if (c != t->str[t->index])
          continue;

        // if it's the only char then we're good, nothing more to check
        if (t->index == 0) {
          t->index++;
          break;
        }

        // otherwise we need to check the rest of the found string
        int diff = origIndex - t->index;
        size_t i;
        for (i = 0; i < t->index; ++i) {
          if (t->str[i] != t->str[i + diff])
            break;
        }

        // if we successfully got through the previous loop then our current
        // index is good.
        if (i == t->index) {
          t->index++;
          break;
        }

        // otherwise we just try the next index
      } while (t->index);
    }
  }
  // unreachable
  return -1;
}

```

---
Tags: serial, library
---


# Question
Title: How to switch on an AC bulb using arduino as well as regular switch?
I'm trying to build a GSM based AC Power ON/OFF switch using Arduino. I've successfully completed the ON/OFF mechanism using SMS with the help of 240v 100amps relay to control the circuit. Apparently I don't want to disturb the regular on/off switch's operation. I want both of them to be operational. When I'm not at home arduino should be the switch control and the regular one should be preferred while at home. I'm actually a noob in this topic, and want your precious help to solve this issue.

# Answer
> 1 votes
This can be done (to a certain extent) using a SPDT (Single-Pole-Double-Throw) relay and an SPDT switch.

The basic principle is the same as when you have two light switches controlling the same light (such as on a staircase - one switch at the top and one at the bottom). The two switches alternate between one of two different paths for the current. When both switches are routed to the same path the light is on.

Both the Arduino and the switch can turn the light on and off at will. The only problem, though, is that the Arduino has no clue if the light is on or off. To know if the light is on you will need some kind of feedback mechanism. That might be a simple LDR that looks to see if it's light or dark, or some kind of current monitoring system (current transformer, hall effect current monitor, etc) which the Arduino can use to see if current is actually flowing through the lamp circuit or not.

# Answer
> 0 votes
A safer approach is to optically link the Arduino to an IR remote control light switch. Such an approach is discussed in this thread. The technical specifications appear to be here for the Lutron light switch remote controls. From this document one could construct an Arduino IR transmitter to send out these code.

---
Tags: relay, switch
---


# Question
Title: Problems With Fading Through Neopixel Colors
I have a 20x20 matrix of neopixel LED's. I have a certain set of LED's on in different places at different times. Each one is set to `mainColor`. Right now `mainColor` is just set to `strip.Color(r, g, b)` but I would like to have those color fade through the spectrum. I decided the easiest way would just be to do something like this, and simply `return strip.Color(r, g, b)` to `mainColor`, then calling it to turn change the colors like so:

```
strip.setPixelColor(pixelNumber, mainColor(5));

```

Here is the code for `mainColor`: int r; int g; int b = 255; int \_r; int \_g; int \_b = 255;

```
void Color (int FADESPEED)
{
    // fade from blue to violet
    for (_r = 0; _r < 256; _r++) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from violet to red
    for (_b = 255; _b > 0; _b--) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from red to yellow
    for (_g = 0; _g < 256; _g++) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from yellow to green
    for (_r = 255; _r > 0; _r--) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from green to teal
    for (_b = 0; _b < 256; _b++) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from teal to blue
    for (_g = 255; _g > 0; _g--) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
}

```

This was good but it would only return `r, g, b` as it was on the last iteration of the last for loop, which obviously isn't what I want. But when I un-comment the `Serial.print's` the values were perfect. So then I put `return strip.Color(r, g, b)` into each for loop, however this only returns the first iteration of the first loop, which is also not what I want. Does anyone know how in the world I can `return strip.Color(r, g, b)` for every iteration of every for loop? Or if not, any alternatives that would work in this situation.

Thanks, Matthew

# Answer
There appears to be a number of problems with this code.

The variables only have scope with in this function and are not static. So they will not survive from call to call. Every time you call this function it will be like starting over.

Putting returns in the middle of code is not good coding practice. It is very difficult to follow and hard to debug. It would be best to arrange your code so that there is only 1 return at the end of the function.

This code (from Adafruit) only controls 1 RGB LED. If you are to control 40 RGB LEDs all at different stages of color changing you would need 40 copies of this function. This is not very efficient. Instead use this function to populate one lookup table with R G B data. Then track 40 variables, one for each RGB LED. Use the 40 variables to lookup a specific color combination in the lookup table for each of the 40 RGB LEDs.
> 1 votes

---
Tags: led, rgb-led, neopixel
---


# Question
Title: How is a 41KB char array filling up 256KB of program memory?
I have an array of 41,400 elements of type char, which I am trying to put in program memory on a Mega2560. It should have 256KB of flash memory, but when I try to compile my sketch, it says the size of the array is too large. Each char is one byte, so this array should be 41,400 bytes. I'm at a loss as to how this can be too big.

I have also tried using an array of byte variables (should be the same thing) with no success. This is the only variable going into program memory.

Here is the relevant line:

```
const char Array[] PROGMEM = {0,19,21,25,27,27,27,29,24, ... };

```

I have included avr/pgmspace.h

Thanks in advance for any help.

# Answer
> 3 votes
The limitation here is the data type of the index of the array. That is `int`, and on an 8-bit system an `int` can hold a value in the range -32768 to 32767.

That means the biggest index number an array can have is 32767.

That limit cannot be changed. You're stuck with it.

However, there are some tricks you can use to expand it. One is to use a larger data type than `char` and pack your data into it. For instance, using `unsigned int` as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.

Using unsigned long (32 bits) would double that again.

It is then up to you to work out how to get to the individual bytes. Using the `pgm_read_byte_*()` function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...

# Answer
> 1 votes
You cannot have more than 32767 elements in one array. The reason is explained nicely by Majenko.

Solution for your problem is very simple, because you need only 41400 elements:

```
class MyArray
{
  static char array1[30000] = {...};
  static char array2[11400] = {...}; // rest

  public:
    char get(long index)
    {
      return index > 30000 ? array2[index - 30000] : array1[index];
    }

    char operator[] (long index)
    {
      return get(index);
    }
};

```

So you can use two arrays and depending of the index choose which one to use. I think it is faster than using array of ints, because you need to have division (by two, so it can be only shift right by one) and than again shifting to get the char. Also it is easier to use because for ints you need first to pack values (two values in one int).

This is just example code, fit it to your needs.

---
Tags: progmem
---


title: How to use Arduino as RC Receiver

text:
# Question
Title: How to use Arduino as RC Receiver
I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

Following is the image of my CC3D. The cable colors does not correspond to each other.

Which input cable should I connect to Arduino? How should I connect black(ground) and red(5V) cables to Arduino:

# Answer
EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..) It seems it is not the question of op.

What you want is easy but there are some pitfalls. I can make a long story short by these links

http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with\_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html

if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with\_25.html

I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib

And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.
> 2 votes

---
Tags: drone
---


# Question
Title: DC Motor Speed Measurement using Rotary Encoder
I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.

```
boolean check;
boolean start;
unsigned int angle = 5;   //angle moved per encoder tick
unsigned long volatile time1;
unsigned long volatile time_11;
unsigned long interrupt_time;

void setup() {
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(21, INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
  attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
  time1 = 0;
  time_11 = 0;
  interrupt_time = 0;
  check = true;
  start = false;
  time_11 = millis(); //Start Clock
}

void loop() {
  if(time1 == interrupt_time && start) //Both times same , hence bool start.
  {
    if(check)
    {
      Serial.print(millis());  //Time taken to rise to steady speed.
      check = false;
    }
    Serial.println((angle/time1)*1000);   //Display Speed.
  }
  interrupt_time = time1;
  start = false;
  while(!start)
    {}
}

void speed(void) {
  start = true;
  time1 = millis()-time_11;
  time_11 = millis();
}

```

I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?

# Answer
Just a couple of remarks:

1. `start` should be volatile, but you can remove it and simply check that `time1 != 0`.
2. there is no point in calling `millis()` twice inside the interrupt service routine:

```
void speed(void) {
  unsigned long now = millis();
  time1 = now - time_11;
  time_11 = now;
}

```
> 1 votes

# Answer
Thank you for the feedback! This is my attempt at calculating speed using the averaging method.

```
unsigned long volatile encodercount;
unsigned long encodercount_previous;
unsigned long volatile timer;
unsigned int angle;
boolean first;
boolean firstencodertick;
void setup() {
      angle=3;
      encodercount=0;
      encodercount_previous=0;
      Serial.begin(9600);
      while (!Serial);
      pinMode(21,INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
      attachInterrupt(digitalPinToInterrupt(2),speed,FALLING);
      first=true;
      firstecnodertick=true;
        }

  void loop() {
     delay(100);

   if(encodercount==encodercount_previous&&encodercount!=0)
    {
   if(first)
     {
   Serial.println(millis()-timer);  //Steady State Time Taken
   first=false;
     }
  Serial.println((encodercount); //Angle Moved in 0.1second.
    }
  encodercount_previous=encodercount;
  encodercount=0;
   }

  void speed(void)
 {
 if(firstencodertick)
 {
 timer=millis();
 firstencodertick=false;
  }
 encodercount++;
}

```
> 1 votes

---
Tags: arduino-mega, motor, code-review
---


# Question
Title: teensy as a keybooard throws error as keyboard input
I have a program (bash script) I wrote that is for stop motion animation. The script works perfectly, when I use any given keyboard on my laptop, and it works on other computers, as well. So i wanted to add a controller, using a teensy, and the keyboard library. source here:

The teensy, set up as a keyboard, using one of the example codes, which I modified. The output appears correct: when I press any of the buttons, I get the expected output (asdw). But, the script throws an error, and exits anyhow, which means something else is being sent besides the key presses I desire.

So, WHY? Here is the keyboard source for the teensy:

```
 /* Buttons to USB Keyboard Example

   You must select Keyboard from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

#include <Bounce.h>

// Create Bounce objects for each button.  The Bounce object
// automatically deals with contact chatter or "bounce", and
// it makes detecting changes very simple.
Bounce button0 = Bounce(0, 10);
Bounce button1 = Bounce(1, 10);  // 10 = 10 ms debounce time
Bounce button2 = Bounce(2, 10);  // which is appropriate for
Bounce button3 = Bounce(3, 10);  // most mechanical pushbuttons
Bounce button4 = Bounce(4, 10);
Bounce button5 = Bounce(5, 10);  // if a button is too "sensitive"
Bounce button6 = Bounce(6, 10);  // to rapid touch, you can
Bounce button7 = Bounce(7, 10);  // increase this time.
Bounce button8 = Bounce(8, 10);
Bounce button9 = Bounce(9, 10);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);  // Teensy++ LED, may need 1k resistor pullup
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
}

void loop() {
  // Update all the buttons.  There should not be any long
  // delays in loop(), so this runs repetitively at a rate
  // faster than the buttons could be pressed and released.
  button0.update();
  button1.update();
  button2.update();
  button3.update();
  button4.update();
  button5.update();
  button6.update();
  button7.update();
  button8.update();
  button9.update();

  // Check each button for "falling" edge.
  // Type a message on the Keyboard when each button presses
  // Update the Joystick buttons only upon changes.
  // falling = high (not pressed - voltage from pullup resistor)
  //           to low (pressed - button connects pin to ground)
  if (button0.fallingEdge()) {
    Keyboard.println("s");
  }
  if (button1.fallingEdge()) {
    Keyboard.println("d");
  }
  if (button2.fallingEdge()) {
    Keyboard.println("w");
  }
  if (button3.fallingEdge()) {
    Keyboard.println("a");
  }
}

```

What should I do to just get the key presses (asdw) from the teensy as if it were a plain old keyboard.

# Answer
> 1 votes
You are calling Keyboard.println() which sends the character string followed by a new line. If you want to emulate a keyboard you should only use Keyboard.print() which only sends the character string with no new line.

# Answer
> 0 votes
Ok I figured it out. The code includes "keyboard.println". I should use "keyboard.print instead", to properly simulate keyboard presses. the newline is what was screwing it up.

---
Tags: arduino-ide, teensy, keyboard
---


# Question
Title: My Arduino Code isn't workig... and i just couldn't see any problems... thoughts?
> **There's Latest Update!**

So i'm working on a counter just for fun. How it works is when you press BUTTON1 the LED Lights up red, the buzzer beeps and the variable "counter" adds one to itself; After counting, you can press BUTTON2 then it will first show a transition animation then blink&beep while taking away the value of "counter". After the value of "counter" is less than 1, everything will start from the beginning.

But what actually happens is after the transition animation played, the LED and the buzzer just won't do any thing. I'm sure my physical connection is all correct, and the buttons are also pulled to ground with a resistor& a 100nf cap to prevent accidental pressing and vibration.

---

Note that I'm using a common anode RGB LED, so the anode pin is always HIGH but to light up individual colors i'll have to pull the cathode pins LOW (remember how electrons flow?)

> **Update** @Tom Carpenter's latest answer still didn't solve the problem. I found the "else" function inside the "if" didn't work at all. So if i put the counter code inside the "else" function, the result would be none. But if i put the counter code in the "if" inside the primary "if", it would, again, count at clock speed, which results blinking forever! **So is there anyway for the code to only count once per press&release cycle without losing?**

*The latest code:*

---

```
#define RLED 10
#define GLED 11
#define BLED 12

#define B1 4
#define B2 5

#define BZZ 3

boolean OB1V;

int counter;

void setup() {

  pinMode(RLED, OUTPUT);
  pinMode(GLED, OUTPUT);
  pinMode(BLED, OUTPUT);

  pinMode(B1, INPUT);
  pinMode(B2, INPUT);

  pinMode(BZZ, OUTPUT);

  OB1V = digitalRead(B1);

}

void loop() {

  digitalWrite(RLED, HIGH);
  digitalWrite(GLED, HIGH);
  digitalWrite(BLED, HIGH);

  boolean NB1V = digitalRead(B1);

  if (NB1V != OB1V)
    {
      digitalWrite(RLED, LOW);
      digitalWrite(BZZ, HIGH);
      counter = 0;
    }
  else
    {
      digitalWrite(RLED, HIGH);
      digitalWrite(BZZ, LOW);
      counter = counter +1;
    }

  if ( digitalRead(B2) == HIGH )
    {
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(RLED, LOW);
      delay(300);
      digitalWrite(RLED, HIGH);
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(BLED, LOW);
      delay(100);
      digitalWrite(BLED, HIGH);
      delay(300);

      for ( counter; counter >= 1; counter -- )
        {
          digitalWrite(GLED, LOW);
          digitalWrite(BZZ, HIGH);
          delay(200);
          digitalWrite(GLED, HIGH);
          digitalWrite(BZZ, LOW);
          delay(200);
        }
    }
}

```

---

# Answer
> 1 votes
There are a number of problems with your code. Your code does not deal with releasing the button. Once you press B1 (assuming pressing B1 causes the input to go high) the counter (if correctly implemented (that is, it should be counter++)) would count up to 32K then start over at zero and count up again. Only stopping when you release B1. The value of counter could be any number between 0 and 32K.

Working with buttons is difficult. And the 100nF capacitor will do little to help. It would be better if you learned how to debounce buttons and treat both the press and the release with equal importance.

There is an Arduino library called Bounce that will do some of this for you. It will not help with your logical errors. You still need to treat pressing and releasing the button with equal importance. But it will help debounce button presses so your results will more closely match your expectation.

added later...

Your altered code will still not work. You need to keep track of the state of the button in order to increment the counter by one for each button press. You can call it edge detection code or state machine code. But the code needs history to decide what to do next. Here is an example of code which does this.

# Answer
> 1 votes
Your problems come down to the fact that in the first code you are trying to do things on level sensitivity rather than edge sensitivity.

To try and understand the difference, some examples. Level sensitivity is effectively:

> Do 'x' **while** 'y'

In other words, if 'y' is true (for example an input is high), then keep doing 'x' (e.g. adding to a counter). This is what your code is doing at the moment, but not what you want it to be doing.

Edge sensitivity on the other hand is:

> Do 'x' **when** 'y changed'

In other words, when the state of 'y' changes (for example from true to false), then doing 'x' once.

The key difference between the two is the difference between 'while' and 'when'.

---

So how do you do edge sensitivity in code?

The way you have done it requires that the button be high and then low at exactly the right moment for the code to catch it. What happens if the button goes low at the end of the loop? Your code will miss the edge because at the start of the next loop it is not high, so doesn't get in to the first if statement.

Lets think about what 'changes' means. It means when the current value is different from the previous value. That implies that we need to keep track of what the previous value is in order to compare it to the current value. In fact that is exactly what we do:

```
boolean oldButtonValue; //It would be better to use a static variable in loop, but for simplicity of the example lets use a global.

void setup() {
    oldButtonValue = digitalRead(buttonPin); //This line is executed once to initialise the variable.
}

void loop() {

    //Each loop we read our current value
    boolean newButtonValue = digitalRead(buttonPin);

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Do something on edge.

    }

    //Update the old button value to match the new one (so we can check it again next loop
    oldButtonValue = newButtonValue;
}

```

What this does is each loop it compares the current state of the button with the state of it from the previous loop. If the value changes, it does something.

---

Now the trouble with that code is it executes on *any* edge. That means that each time you press the button, it will run twice, once on press and again on release. So lets modify it slightly:

```
    ...

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Was it a rising edge?
        if (newButtonValue) {
            //If the button value is now high, it must have been a rising edge
        } else {
            //Otherwise it was a falling edge

        }
    }

    ...

```

The extra comparison allows us to determine whether it was a rising edge or a falling edge. So you can now do something either when the button is pressed, or when it is released (or both if you want).

---

You can have a second boolean variable to keep track of the old state for the second button. Then you use the same approach to do edge sensitivity detection approach for the second button.

---
Tags: programming, sketch
---


title: Serial is freezing arduino

text:
# Question
Title: Serial is freezing arduino
I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.

It always worked very well, then out of the blue, it stopped printing anything using Serial.print();

But if I ommit the "Serial.begin(9600);" line, the code runs **normally**, sending sensor data via MQTT, even if I can't see debug output.

This shows the problem is on the Serial handling.

Since I can't show the entire code here, here's two test cases:

1.

```
void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial1.println("This came from serial 1"); //does nothing
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

```

It shows me the following output:

> This came from serial 0
>
> This came from serial 0
>
> Thi

Looks like the module freezes before the third iteration.

But if I omit the lines that aren't printed, from Serial1:

2.

```
void setup(){
  Serial.begin(9600);
  while(!Serial);  //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

```

No output is shown on Serial monitor.

What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?

Observations:

I tested the code in two LinkIt ONE modules of the same model.

I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.

Edit:

Just made another test using the code below. It blinked two times showing that

Serial.begin(9600); runs

while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)

But Serial.println(); freezes

```
void setup(){
  pinMode(13, OUTPUT);
  blink();
  Serial.begin(9600);
  blink();
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  blink();
  delay(1000);
}

void blink(){
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);
}

```

# Answer
The problem was solved by:

* making a clean install of Arduino IDE 1.6.9
* uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.
> 1 votes

# Answer
I have bit similar problem. I thing, this is arduino bug. When start serial port, must be take out data from Rx. When read buffer overflow my arduino freeze. I can't run delay because when arduino wait, serial port can receive lot of data -\> overflow -\> freeze. Instead of delay I use own function wait(milis):

```
void wait(unsigned long wait_time){
  unsigned long start_time;
  start_time=millis();
  while ( millis() < (start_time+wait_time) ){
    if (serial.available() > 0) serial.read();
  }
}

```
> 0 votes

# Answer
> This shows the problem is on the Serial handling.

The problem isn't actually in Serial, it's somewhere else. Many things are able to make the Arduino hang in mid-write. Show us the any code that you have written, plus links to the libraries you are using, and you'll have your answer in short order.

I will guess that you have a low-RAM condition, perhaps exacerbated by heap usage. Do you use `String`? I notice you're not using the F macro to save RAM.
> -1 votes

---
Tags: serial, programming
---


# Question
Title: Why is timer0 the fastest timer in the arduino?
In the documentation, it shows that the higher frequency that can be reached with an Arduino UNO for and 8bits PWM is using timer0 with the pre-scaler set at 1. That gives a Fs of 62500 Hz, but why is that so?

I understand the Prescaler is dividing the frequency, but why it does start at 62500 Hz and timer1 and timer2 have as maximum 31372 Hz.

# Answer
Timers 1 and 2 are configured by the Arduino core library to run the so called “*phase correct PWM*” mode. In this mode, the timers count forward from 0 to 255, and then they count backwards to zero. Timer 0 is configured by the same library in “*fast PWM*” mode, where it counts from 0 to 255 and then overflows back to zero in a single timer cycle.

You can, if you want, configure timers 1 and 2 in fast PWM mode. For doing this, you will have to access their I/O registers directly. C.f. the datasheet of the relevant microcontroller for details.

A couple of links:

* the datasheet of the ATmega328P microcontroller describes all the possible configurations of the timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
* the source code of the Arduino init() function to see how Arduino core configures them.
> 3 votes

---
Tags: pwm, timers
---


# Question
Title: Looking for a wireless soil moisture sensor
I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?

# Answer
The project is very much possible but it will be easier if you attach the moisture sensor directly to the arduino and add a wifi shield or a bluetooth shield to the arduino itself and make it communicate with computer or phone. You could also program the arduino to directly water the plants if it finds that they dont have much moisture. You will rarely find a sensor that transmits data wirelessly and still be economically feasible. The Sparkfun SEN-13322 moisture sensor is good for the purpose but again connect it to arduino direclty.
> 2 votes

---
Tags: sensors, bluetooth, wifi
---


title: Interrupt numbering

text:
# Question
Title: Interrupt numbering
I'm using an Arduino Mega and four of its interrupts. Each interrupt is only used to start/stop a timer, depending if it's rising or falling, so effectively runs the same function. Does anyone know if theres a way to differentiate between which interrupt has been triggered? This way I can attach them all to the same ISR and just start/stop different timers.

Thanks, Shaun

# Answer
> 0 votes
The only sure-fire way of knowing which interrupt triggered your ISR is to examine the GPIO pin that the interrupt is associated with.

You need to use CHANGE interrupts so that you can keep track of the state of the pins - both HIGH and LOW. When you get an interrupt and read all the GPIO pins you have tied to the ISR you can then compare their values to the previously stored values. Any pins that have changed since the last ISR (or a pre-defined initial state) can be processed and handled accordingly.

Yes, it adds a certain amount of overhead to your code, and using `digitalRead()` may not be the most efficient way of doing it. Instead you may want to use direct port access to read the pin's state directly.

# Answer
> 0 votes
Assuming that by "Mega" you mean the Mega 2560, see sections 15.2.4 and 15.2.5 of the 2/2014 datasheet referring to the External Interrupt Flags and Pin Change Interrupt flags:

> When an edge or logic change on the INT7:0 pin triggers an interrupt request, INTF7:0 becomes set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT7:0 in EIMSK, are set (one), the MCU will jump to the interrupt vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. These flags are always cleared when INT7:0 are configured as level interrupt.

It is not clear from the above when specifically "The flag is cleared when the interrupt routine is executed" happens. It wouldn't be much use if it happened on ISR entry so I'll take a guess that it happens on return from interrupt, in which case the flags would be available to read in the ISR. An experiment would be in order, here. These flag registers are known to the compiler as EIFR and PCIFR, respectively.

---
Tags: programming, arduino-mega, interrupt, code-optimization, isr
---


title: Split Power supply in voltage and gnd?

text:
# Question
Title: Split Power supply in voltage and gnd?
I am new to electronics and arduino in general. I need to split a power supply in gnd and voltage. Basically, the power supply has one single wire (with the voltage and the gnd passing through it i think), and I need them to be separated. Sorry if this is a noob question, but I am really new to this whole thing.

# Answer
> 1 votes
Do you have a image of this? Logically, and as far as I know, One wire will not carry both GND and Positive.

Are you talking of a DC jack kind of thing?

BTW, I'm starting out here too!

# Answer
> 1 votes
If the cable of the power supply contains voltage and gnd, it's two cables, with a layer between them.

On the inside they look much like coaxial cables, so if you softly cut the outer shell(A) you maye see a mesh of blank wires(B,C,D), they're gnd in most cases. There also is an inner wire(C) which you have to cut softly, too. That's the voltage carrying wire(D), in most cases. (If it's approx. less than 10 Volts, check with a LED.)

---
Tags: arduino-uno, power, electronics, electricity
---


title: COM+ and COM- to RX and TX

text:
# Question
Title: COM+ and COM- to RX and TX
I want to connect a Hokuyo scanning range finder to an Arduino Mega, the outputs are labeled like this:

* COM+
* COM-
* Input
* Output
* DC12/24
* GND

I want to read its serial output with Arduino, please help me in details. Thanks

# Answer
You should specify what model of Hokuyo scanning range finder you have. Some models are USB-interfaced, in which case COM+ and COM- could possibly correspond to USB D+ and D- leads.

The Hokuyo URG-04LX has both USB and RS-232 interfacing. The linked page shows the following pinout on CN1:

```
Pin No.   Signals                                Colors
1         N.C.                                   Red
2         N.C.                                   White
3         OUTPUT(Synchronous output)             Black
4         GND(5th pin of 9-pin, D-sub connector) Purple
5         RxD(3rd pin of 9-pin, D-sub connector) Yellow
6         TxD(2nd pin of 9-pin, D-sub connector) Green
7         0V                                     Blue
8         DC5V                                   Brown

```

Given that pinout, you would connect pin 5, RxD, to a TXD output on the Mega, and pin 6, TxD, to an RXD input on the Mega. Note, before making any such connection, measure the output voltage on pin 6. An ordinary Mega supports 0 V and 5 V levels for serial data, but standard RS-232 levels are lower and higher than that; for example, ±12 V. If you connect ±12 V RS-232 levels to your Mega, you will damage it. The several Hokuyo documents I've looked at don't say whether they use traditional RS-232 levels (±12 V) or TTL levels (0-5 V).
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Adafruit GPS module with SoftwareSerial affecting servo signals
I'm having a bit of an odd problem here. I'm programming a self-built quadcopter using an Arduino Uno for control. One of the sensor's that I'm using is Adafruit's GPS breakout. The motors are controlled with electronic speed controllers (ESCs) that controlled identically to normal servo motors. Everything is connected together with a custom Arduino shield. The GPS is using SoftwareSerial on pins 3 and 4, and the ESCs are connected on pins 5-8. Most of the GPS code is directly copied from Adafruit's documentation.

What I've found is that even when the throttle is held steady (at any power level), the motors experience quick bursts of power far beyond normal whenever there is communication between the GPS module and the Arduino. For example, the GPS updates on 1Hz intervals and so the motors get a burst of speed about every second. Has anyone else experienced something like this or could someone at least point me in the right direction?

Here's an abbreviated version of the code that I'm currently using:

```
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

Servo ESC1;
Servo ESC2;
Servo ESC3;
Servo ESC4;
const int maxThrottle = 2000;
const int minThrottle = 1000;

SoftwareSerial softwareSerial(4, 3);
Adafruit_GPS GPS(&softwareSerial);
// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
bool usingInterrupt = false;
uint32_t timer = millis();

void setup() {
    ESC1.attach(5);
    ESC2.attach(8);
    ESC3.attach(6);
    ESC4.attach(7);
    setThrottleAll(minThrottle);

    GPS.begin(9600);
    GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
    GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
    GPS.sendCommand(PGCMD_ANTENNA);
    useInterrupt(true);
}
int throttleCommand = 20;
void loop() {
    // Map throttle command percentage to raw throttle values that are sent to the ESCs
    int throttle = map(throttleCommand, 0, 100, minThrottle, maxThrottle);
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}

// GPS interrupt
SIGNAL(TIMER0_COMPA_vect) {
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    #ifdef UDR0
        if (GPSECHO)
            if (c) UDR0 = c;
                // writing direct to UDR0 is much much faster than Serial.print
                // but only one character can be written at a time.
    #endif
}
void useInterrupt(boolean v) {
    if (v) {
        // Timer0 is already used for millis() - we'll just interrupt somewhere
        // in the middle and call the "Compare A" function above
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
    }
    else {
        // do not call the interrupt function COMPA anymore
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
    }
}

void setThrottleAll(int throttle) {
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}
void setThrottle(int index, int throttle) {
    if (index == 1)
        ESC1.writeMicroseconds(throttle);
    if (index == 2)
        ESC2.writeMicroseconds(throttle);
    if (index == 3)
        ESC3.writeMicroseconds(throttle);
    if (index == 4)
        ESC4.writeMicroseconds(throttle);
}

```

# Answer
The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit\_GPS), and your program structure is based on the awful Adafruit\_GPS example.

The good news is that there are much better alternatives: NeoSWSerial and NeoGPS. Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos. It can be an "interesting challenge" or a "beginner's nightmare."

Suggestions:

**1)** Consider using the HardwareSerial object, `Serial`, for the GPS interface. Your excerpt does not show what `Serial` is currently used for, but if it's debug print statements... don't. Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC). This would have a tremendous impact.

**2)** If you *really really* can't use `Serial` for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded `SoftwareSerial`. Next best is NeoSWSerial on any pins, including 4&3 that you are using now. There is absolutely no reason to shoot yourself in the foot with `SoftwareSerial`.

**3)** As other's have commented, use HW PWM... let the machine do the work for you.

**4)** Consider using the faster and smaller NeoGPS library. And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient. The Adafruit\_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a `SoftwareSerial` interrupt... that was on for the entire character time of ~1ms. What a phenomenal waste!

**5)** Use interrupt-driven GPS parsing. All three Neo\__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters *during* the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow). And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete. This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with `strcmp` and `strchr`. Ugh. No, I meant to say UGH!

**6)** NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.

It's definitely a tight squeeze. Either reallocate your pins and use better libraries, or get a bigger hammer. :-)
> 1 votes

---
Tags: servo, gps
---


# Question
Title: Camera switch with ov7670 to output standard A/V signal - composite
I've got 3 OV7670 cameras and would like to create a switch that outputs one of the cameras video as standard A/V out (I'm not sure the correct naming).

I found docs explaining how to use the cameras on the Arduino platform but I'm not sure how to output video signal - composite.

# Answer
An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see here the signal specification.

Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

1. you will need a very fast DAC (a flash one)
2. you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...
> 2 votes

---
Tags: arduino-uno
---


title: What is the Vin Pin for?

text:
# Question
Title: What is the Vin Pin for?
I always asumed it was a different option to power the board, but it seems to act more like a 5V supply. What then is the difference between this pin and the 5V pin?

# Answer
The Vin pin serves the same purpose as the barrel jack. The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.

Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.

If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin. It's not safe to use that power for anything since you could damage the 5V regulator if you do.

The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).
> 9 votes

# Answer
To answer this added question:

> At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short

I certainly would **not** be using it as a 5V "virtual ground" - whatever that means. The Vin pin could easily be up around the 10V mark, depending on what you plug into the barrel jack.

I had a project a while ago where I wanted to trigger a camera flash. In the same way as you describe, two pins had to be shorted.

I wasn't sure what voltages would be on them, or if there would be a spike, so I used an opto-coupler like this:

You need to identify by measuring with a meter which pin has the positive voltage on it. That would go to the collector of the transistor in the opto-coupler (pin 5 in this particular case).

---

*(edited to add)*

> I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

We can probably assume that the current will be low, after all they wouldn't short out the camera's battery through that pin. Put your meter in **current** mode across the camera's pin and measure the current when the pin is shorted (ie. the meter will short it).

If it is 20 mA or less then the Arduino digital pin can handle that. I imagine it will be a steady flow of current. I just measured my flash shoe with that method, and it seems to use a tiny fraction of current (0.1 mA).

So that should be safe, safer than your method with Vin anyway.

> Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires.

Sounds complex. Just make the pin LOW, and make it output to fire it. eg.

In setup:

```
digitalWrite (cameraPin, LOW);  // default will be INPUT mode

```

To activate camera:

```
pinMode (cameraPin, OUTPUT);  // drive low
delay (500);  // or whatever
pinMode (cameraPin, INPUT);   // make high impedance

```

Make sure you measure the pin and get the correct polarity. You want the positive side to go to the Arduino pin, and the negative side to Ground.

And make sure it isn't higher than 5V. (Use **voltage** mode on the meter to check that).
> 4 votes

# Answer
I like the way someone explained Vin to me. "Whatever power source you connect to the DC Jack is supplied there, be it 12v or lesser"
> 0 votes

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


# Question
Title: Moisture sensor data will not output data to Serial Monitor?
I am making a Soil Analysis system with an Arduino Uno, but I have run into a problem and was wondering if /r/learnprogramming could help!

The moisture sensor section of my code will not output the data to the Serial Monitor in Arduino 1.7.1 IDE. I am not sure why it's not working. Running the moisture sensor code by itself works, and I just copied and pasted that code into my combined code file since I'll I am running 4 sensors at once with my Arduino Uno.

These are the four values I need to output data on one baud rate:

* pH value
* EC
* DHT temperature reading
* Moisture Sensor Value
I am currently missing Moisture Sensor Value when I run Combined1.ino

Here is the Combined1.ino code of the code from four sensors together that's uploaded to the Arduino: Combined Code Link
Moisture Sensor Link

Any help would be much appreciated!

# Answer
Your second print section will always fail.

You have:

```
if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator

```

However, a bit before then you have:

```
if(millis()-printTime>=printInterval)
{
  printTime=millis();

```

So `millis() - printTime` can never be greater than `printInterval` since you have just set `printTime` to `millis()`. So `millis() - printTime` will always be somewhere between `0` and `printInterval - 1`.

Consider combining your different printing routines into one single printing routine so you are comparing (and changing) the `printTime` only once.
> 1 votes

---
Tags: sensors
---


title: Power motor with Uno

text:
# Question
Title: Power motor with Uno
I am trying to power a small peristaltic pump using an UNO R3. I have it powered using usb, and I tried running the blink program to see if I could power it using digital write, and extended the delay to troubleshoot voltages using a multimeter. The motor doesn't do anything connected to the digital pins even when the digital write is set to high. If I connect the motor to the 5 V power pin the motor turns on so I know 5 V is enough voltage. I've looked at tutorials for DC motors and they explain how to set it up with motor reversing using components I don't have, and I don't need it to reverse. How can I get the motor to turn for a specific length of time?

# Answer
> 3 votes
Most likely the motor you are trying to drive requires much higher current than what the UNO can provide through its digital outputs.

Check out this summary to find out detailed specs for the I/O ports.

What you could do is to draw power from the 5V line provided by the Arduino. If that can drive your motor, then use the line to power an output stage, driven by the digital I/O. See this example. In general, the idea is that the digital I/O provides the control logic, while the output stage provides the power required by the specific load.

The typical loads that can be driven directly by GPIOs are low power LEDs. Anything that involves moving parts is generally out of reach, power-wise.

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


# Question
Title: Can an arduino tell between being powered by USB or by the jack?
I have an arduino mega that will be communicating through serial to a pc. One of the things I want it to tell the pc is whether or not it is connected to a wall power to 12V converter (where there is a switch between the arduino and the wall power). I was just wondering if there was a way to do that in software without having any additional hardware.

Thanks!

# Answer
> 2 votes
No, you can't do it without extra hardware.

You need to pass VIN through a voltage divider so it sits within 0-5V when powered by 12V, then feed that into an ADC input. Protect the on-board voltage regulator with a diode between 5V (anode) and VIN (cathode). Then you can measure the voltage on VIN and make a decision on if it is around 4.5V or 11.5V

A 22K/10K voltage divider will reduce 12V down to 3.75V, which gives plenty of "headroom" for over-voltage situations (where your 12V unregulated power supply actually provides, say, 15V):

---
Tags: power, input
---


title: What is VREF pin?

text:
# Question
Title: What is VREF pin?
Was searching for some help on connecting Flir camera w/ Lepton board to arduino and found this thread

*for power you can reroute the 3-5V to the VREF pin, then you have a nice clean solution. You have to use a Ardunio with at least 16k or ram so you can buffer the image.*

Was that a typo and he meant AREF? If so would the VIN from the camera be connected to the VIN on arduino otherwise?

Thread: https://forum.arduino.cc/index.php?topic=266361.0

# Answer
> 2 votes
VREF normally means Voltage REFerence. Such pins are usually associated with ADCs (Analog to Digital Converters). For example a 3.3 volt microprocessor may have a VREF pin fed by 2 volts. The 10 bit ADC inside the microprocessor sees this as the upper limit. That is, a 2 volt input to the ADC will produce the maximum value or 2^10 or 1024.

# Answer
> 1 votes
Yes, he meant AREF. What he is showing there is the board plugged direct into the Arduino's header, but the VIN of the Lepton board connects to AREF not a voltage pin. By connecting your supply voltage (5V) direct to that AREF pin you are then able to provide power to the Lepton board, and it has no noticeable effect on the Arduino since connecting 5V to AREF is a perfectly valid thing to do (though pretty pointless).

AREF and VREF are both pretty much interchangeable. Analog REFerence, and Voltage REFerence. It could be said that one is the Analog voltage REFerence, and the other is the Voltage REFerence for analog. Some chips call it AREF and some VREF. Some even provide VREF+ and VREF- or AREF+ and AREF- depending on the complexity of the ADC in the chip.

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


# Question
Title: How to 'label' module using electric techniques
I am in a project where it makes set of 'modules(set of separate circuits that will work as a sensor when connected to the board' that would be connected to Arduino Mega.

Currently, I'm planning to connect 'modules' with the Mega board using RJ-45(also known as LAN cable) cables.

At first, using voltage divider circuit, I tried to identify these 'modules' by attaching a resistor to it, so that if the board sends 5V to the 'module', it gets the resistance of the resistor inside the module.

But, as soon as I tested, this way seemed a bit unstable, because the measured resistance of the resistor kept changing.

Now, is there any other way to 'label' the module? I'm a beginner in this thing, so I'll appreciate any help that is provided.

Thanks in advance.

Ps. the voltage divider circuit that I used can be found in here:

Ps2. the resistor in the module does not mean the total resistance of the circuit in the module. It's separate.

# Answer
> 0 votes
If you are unable / unwilling to change your interface into a purely digital system whereby a small microcontroller in the sensor module interfaces the sensor with a communication bus, the best method is probably to include a small 1-wire EEPROM with each module.

An ideal one would be the DS2431 which provides 1024 bits (128 bytes) of EEPROM storage using just 1 wire to both communicate and provide power.

Programming in a unique identifier for the module would be a simple enough task, and that unique ID can then be used to work out what the module is.

The DS2431 is pretty cheap too, available at prices around $1.50 and below (much less for bulk and surface mount).

You can also get bigger versions for storing more data should you want to.

---
Tags: arduino-mega, resistor
---


# Question
Title: What happens if I draw too much current from ATMEGA IO pin?
I revisited an older device that I made and discovered, that I had an 8 Ohm speaker connected directly to ground and an IO pin of an Atmega328P. According to my calculation that means that the pin would have to source 625 mA, which is way above the 40 mA that any single port should be able to source and even above the 200 mA that the Vcc and GND support. Yet it somehow worked and the chip seems to be working just fine. The application uses a duty cycle of 50%, so in the best case it would use maybe 312.5 mA, which is a little better but still way above the ratings.

So my question is, what happens if the output pin is asked to source more than it's rating?

I've seen chips that just release their magic smoke while others just can't keep up with supplying that kind of voltage, so only the voltage drops without any other problems. How does the Atmega328P handle this?

The Atmega clearly didn't burn through, but what other kind of damage should I expect?

# Answer
> 5 votes
There's a few crude calculations you can do using some numbers from the datasheet.

This graph is in the datasheet:

It shows the voltage dropped by the high-side MOSFET driver in the IO pin for different amounts of current draw. From that we can get its resistance R(DSON).

For instance at 10mA, at 25C, the output voltage would be 4.75V. That's a 0.25V drop from the 5V supply voltage. So we can calculate the resistance as:

* *R=V/I = 0.25V / 0.01A = 25Ω*

Now we have that resistance we can use it to calculate the actual current from the IO pin with an 8Ω load. Simply add the two together:

* *25Ω + 8Ω = 33Ω*

Now we can calculate the current through that circuit:

* *I=V/R = 5V / 33Ω = 0.152A*

That is, of course, way above what the IO pin can actually supply (or so the datasheet says).

So what happens? Well, two things, basically:

1. The voltage on the IO pin will be below the 4.2V specification for the minimum of an output pin when HIGH, and
2. It will get hot.

The actual voltage will be, of course, *V=I×R = 0.152A × 25Ω = 3.8V* droped, so *5 - 3.8 = 1.2V*

What is more critical, though, is the heat. 152mA through a 25Ω resistance generates *P=I²R = 0.152 × 0.152 × 25 = 0.5776W*. That's quite a lot. Enough to melt the internal circuits in the chip and release the Magic Smoke™.

Running at 50% duty cycle, though, makes a difference. That's 50% of the power, which makes a big difference to the heat.

What would the actual allowable heat be? Well, at 40mA, with 25Ω, that is *0.04 × 0.04 × 25 = 0.04W*.

So you're generating more than 14 times the amount of heat you are allowed to. Even at 50% duty cycle, that's over 7x the limit.

Will it kill the chip? Well, possibly, possibly not. It depends how rugged the chip is and how well it can withstand the heat. Short bursts may be OK since the heat doesn't build up enough to melt things. Extended use, though, will make it get too hot, and things will go pop.

---
Tags: atmega328, current
---