# Question
Title: What sensor would work for soccer ball detection efficiently using Arduino?
I want to make a soccer goal counter using Arduino and some sensors. I built using an ultrasonic sensor, but it does not detect if the ball is moving too fast. Are there any other sensors I can use to detect soccer ball?

# Answer
This is potentially well beyond the capabilities of a simple MCU like an Arduino UNO. So I think it is very important to clearly define the problem you're trying to solve.

Currently, at top national and international level, video cameras are used to detect a ball crossing the goal line. AFAICT, a lot of the complexity comes from having the goal keeper and several players on the line too. It is important that a player kicking across the goal line is not mistaken for the ball crossing the line. Also, it is important that players bodies can't block the view; a simplistic approach might not be able to see the ball if its kicked between a players legs.

This amounts to (probably) millions of sensors (one per pixel) being monitored at 100+ Hz.

So, I'll assume you *are not* trying to solve such a complex problem. Instead I'll assume you only want to detect a ball crossing the back edge of the goal line, without considering interference by players.

First, let's gather some numbers to describe the core problem.

A soccer ball/football is at least 68cm in circumference, so it is 68/pi = *21.6cm in diameter*, or 0.216m, which is 0.108cm radius.

Then there is the goal. FIFA rules say "The distance between the posts is 7.32 m (8 yds) and the distance from the lower edge of the crossbar to the ground is 2.44 m (8 ft)"

So a question is, must the system detect the ball crossing the goal line at any place?

A goal is about 34 times wider than the diameter of the ball, and just over 11 times taller. So, if the sensors were some form of 'light beam' being broken, the 'simplest' system would need more than 11 sensors looking horizontally from one goal post to the other.

How fast might the ball travel through the posts? This says Cristiano Ronaldo was measured kicking a ball at 130km/hr. That's 36.1m/s.

So the ball is going to take 0.216/36.1 = 0.006 seconds, 6 milliseconds to pass the back edge of the goal line, ie. front edge to back edge will pass a point in 6 milliseconds. This means the sensors must all be scanned, at worst, every 6 milliseconds.

For a sound based system there are more issues.

How much of the ball is 'seen', ie. if only a small fraction of the ball is 'in view' might the returned sound be too small to register with an off-the-shelf ultrasound sensor? For example, if the angle of the reflected sound is too big, ie. from the front or back of the ball, will enough reflected sound return to the sensor to be detected?

Does the ball reflect sound well? It is a membrane at quite a low excess pressure, very different from a solid wall, so I would guess it isn't a perfect sound reflector. I haven't found anything quantifying this, but it seems reasonable to assume off-the-shelf ultrasound sensors might miss the ball under some circumstances.

So it would seem reasonable to assume that two or more sensor readings of the ball would give a significantly more reliable reading than a single sensor reading.

This equates to sampling at least every 3milliseconds. That is a maximum distance of 0.34m * 3/2millisecons (round trip) = 0.5m (approximately).

This might seem to be too much of a restriction. However, the ultrasound sensor only sends a pulse of a few cycles, so it isn't able to detect the ball for the whole of that 3 milliseconds. I haven't found a spec for the off the shelf sensors, but a plausible assumption might be each pulse lasts for about 10 cycles of 40kHz, so the pulse lasts for 0.25 milliseconds. That is the time the ball might travel, about, 1cm. So the angle of reflection would not change much. Hence trying to detect the ball more frequently will increase the quality of at least one signal.

This may explain why the ball is not always detected using ultrasound sensors in your existing approach.

Using any type of sensors to detect the ball, there is a bit of a trade-off. The ball is round, and so if the sensors are almost at the balls diameter apart, then the sensors are going to need to be scanned more quickly to detect a small part of the ball (think of this as a much smaller ball). On the other hand, if the sensors are much closer so at least one gets a longer 'view' of the ball, then one is going to see something closer to the diameter of the ball, hence see it for longer, and so they could be scanned more slowly.

This adds up to a similar outcome. Increase the number of sensors so one sees the ball for a reasonable length of time, or scan the sensors much faster to have a reasonable chance of a measurement.

A 'classic' way to detect something crossing a plane (a door way or in this case the goal mouth) is with a set of laser beams (think Mission Impossible, Entrapment, etc.).

So, consider eye-safe visible-light laser pointers? They **must** be eye safe, which AFAIK largely implies visible light lasers as eye-safe partly depends on the eyes 'blink response'.

At the width of a goal, the laser will have spread to several cm, but should still be straightforward to detect. With some care, it might be feasible to use mirrors to reflect a beam back towards the goal post carrying the laser, halving the number of lasers, and keeping all of the wiring on one side. I don't know how many reflections might work, but it is worth experimenting as every reflection reduces the number of lasers and sensors.

One advantage of an optical approach vs sound is the goal mouth could easily be monitored at a much higher rate than the ball could possibly pass.

To discriminate between sunlight, stadium or street lights, or other sources of light, the lasers would be modulated. 5kHz is a common figure, this is well away from mains frequency. The signal should be 'low' when the laser is off, and 'high' when the laser is on. If that isn't the case, then their is signal interference, and it isn't going to work.

With a little bit of electronics at the sensors, the signals may be purely digital, so there would be no reliance on the Arduino's slow ADC; the sensors could be scanned with digital GPIO pins, with, say, all 11 sensors being scanned at 10kHz.

You may be able to achieve a similar effect using narrow angle, high-power LEDs, lenses and tubes. A reasonable lens system should be able to focus LEDs over 7.32m of the goal mouth. However, I think eye-safe laser pointers would work with simpler optics, and the mechanics and optical systems are often harder to make robust than the electronics.

**Summary**:
A 'raster' of eye-safe, visible-light lasers, at approximately 10cm apart, maybe with mirrors to significantly reduce the number of lasers and sensors, directed horizontally across the goal mouth, could detect a ball passing.

However, it would be confused by players across the goal line.
> 2 votes

# Answer
You should be able to detect an object as large as a soccer ball with an array of modulated IR transmitters and receivers. However you might want to avoid using IR receivers like the ones found in entertainment equipment. These have an AGC stage which will, when blocked, turn up the gain until the receiver finds a weak indirect signal. Instead, try searching using "Long-Range Presence and Proximity Sensors".
> 0 votes

---
Tags: arduino-uno, programming, sensors, proximity
---


title: Fading RGB LED between 10 and 60 cm

text:
# Question
Title: Fading RGB LED between 10 and 60 cm
What I want to achieve is that between 10 and 60 cm of my HCSR04 sensor the color fades from red to blue on my RGB LED in steps of 1 cm between 10 and 60 cm.

I have tried creating some own functions which calculate how much the analogWrite has to change every cm. Yet have had no succes..

I want to implement this function in the following code:

I hope my question is understandable...

# Answer
> 0 votes
```
analogWrite(Kleur1,distance);
analogWrite(Kleur2,1024-distance);

```

Theoretically, this is all you need.

You'll color the LED "kleur1" with the analog value of the distance, so it will become brighter when the distance is higher. And you'll color the LED "kleur2" with the "inverted" analog value of the distance, so it will become less brighter when the distance is higher.

But this kind of depends on what the value is on your maximal distance etc.

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


# Question
Title: Arduino Mega 2560 from .org- which IDE works?
My personal choice is to purchase from the .cc (or adafruit) for new boards. YMMV. Craigslist locally of course has generic and .org boards now and then.

If I get a .org board on craigslist, will I need to use their fork of the IDE for the board to be recognized by the IDE?

My feeling is "yes" but I wanted to confirm.

A board there just now is Arduino mega 2560 from the .org. Would I have to use their flavor of the IDE?

Thank you for your thoughts- photo of the board I am considering is attached.

# Answer
Arduino.org and arduino.cc have come to a agreement. As such all incompatibilities that exist (I don't think they exist for this mega board) will be solved with next version of the Arduino IDE as if it is a board of their own.
> 0 votes

---
Tags: arduino-mega, ide
---


title: Self made microphone burns Arduino

text:
# Question
Title: Self made microphone burns Arduino
I'm very new to electrical engineering and I'm trying to read microphone input with Arduino Nano. I've made a separate microphone module (based on this example) and plugged it into Arduino like this:

Unfortunately it was the last time my Arduino was working. It's no longer displayed as a connection, and acts "randomly", so I think my microphone toasts controller for some reason. Here are some more pictures and a scheme of my mic module, could someone explain what am I doing wrong?

simulate this circuit – Schematic created using CircuitLab

**R1** \- CR1/4W 10 (brown,black,black,gold)

**R2** \- CR1/4W 2KO (red,black,red,gold)

*I have no education in electrical engineering, so I'm not sure about the correctness of this schema of units, just pasted what's written on the pack*

# Answer
Your schematic shows R1 as 10k ohms. Your color codes and description lists it as 10 ohms. 10K would be Brown, Black, Orange.

http://www.allaboutcircuits.com/textbook/reference/chpt-2/resistor-color-codes/

So R1 is the wrong value by a factor of 1000, you may want to fix that ;-)

As for damage to the main board, depending on the microphone used that may have put an excessive strain on the 5V supply pin. Does the power LED still come on at the same brightness as before? If not then the power supply regulator is probably toast. If it does then I'm not sure what the problem is, you shouldn't have broken anything else.
> 2 votes

---
Tags: arduino-nano, resistor
---


# Question
Title: Using two pins to sum maximum available current
I have a theoretical question about using digital pins of arduino. The specification of Arduino Uno (or any other I guess) says, that maximum current from digital pin is 40mA. If I would need more than 40mA and less than 80mA, can I use two pins to supply enough power to the sensor or would it burn the pins in the end?

Thanks

# Answer
> 4 votes
40mA is the *absolute maximum* current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.

Theoretically, yes, that should be possible. However in practice doing such things is problematic. You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.

It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.

---
Tags: power, pins
---


title: Made a Adafruit Flora unusable

text:
# Question
Title: Made a Adafruit Flora unusable
I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs. After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights. When this orange color appears, it seems to indicate that the Flora has crashed. If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.

The time between boot and crash is short enough that I can't upload a new sketch.

So how would I go about rescuing the Flora? Is there a couple pins I can jumper to put it into bootloader mode? Or some other way of resetting the Flora so as to remove the offending code?

# Answer
> 42 pixels in the strand all set to bright white.

This exceeds the power supply capability of either a USB port or the Arduino's regulator.

Likely the circuit starts out working, then once the LEDs are all on drawing high power either a protective device such as a polyfuse / PTC fuse activates trips or the supply simply sags under load. At this point the circuit either shuts down or starts misoperating, the ATmega may go into brownout protection mode, etc.

Disconnect power to your LEDs and you will probably find that the Flora is fine.

You will need to use a suitable higher current power supply if you want to light more than a few pixels of this type at any given time.
> 2 votes

---
Tags: bootloader
---


# Question
Title: Will 5V 2A current input to the power port kill my Arduino?
I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

# Answer
"*I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?*"

No! It won't. Even tough the reason has been already explained in this other post, I want to add something.

First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly **ok**, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....

You're missing a key point, here: **the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!**

In other words:

* if you have a device that requires a very little amount of current to properly operate (*as an example, this DHT22 sensor, requires as little as 2.5mA, or 0.0025 A*) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;
* if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);
* if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (*Which kind of problems you'll encounter is a matter for a different question!*)

To be more specific:

* a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
* an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

* you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to **not** require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" are strongly related.

In your OP you mentioned "*mobile charger ... 5V*" so I bet that you've an USB power-supply, rated at 2A/5V.

People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed *exactly* to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

* as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;
* as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).

As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a barrel-jack, providing a voltage inline with what specified by official documentation:

> \[...\] The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, \[...\] the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts. \[...\]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

1. from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;
2. apply some "magic" to such a current and bring it down \_to\_a\_very\_precise\_ 5V flow;
3. provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.

You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a **fundamental** concept to be kept in mind is that **such a reduction will produce "heat"**! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!

Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)
> 11 votes

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


# Question
Title: Reading the DotStar datasheet - power requirements
I'm trying to figure out my power requirements for a strand of Adafruit DotStar LEDs - APA102 Cool White, not the RGB. I'm not sure how to interpret the datasheet.

In the middle of the product spec table on page 1, under Power Consumption, it says `0.2W (MAX: 1W)`. Which would mean at 5V, MAX would be 0.2A, or 200mA.

Then on page 3 in the electrical characteristics table under the symbol/Parameter "LOL/Sink Current Voltage" it says `typ. 24.5mA; max. 26.5mA`.

I plan on having the strand on full brightness most of the time.

So which is it? 200mA? or 26.5mA?

# Answer
> 1 votes
I expect you will have to run an experiment and measure how much current each unit draws at full brightness.

The APA102C spec sheet seems to mix together data about the whole unit (controller chip plus three LEDs) and the controller chip itself. The “LOL/Sink Current Voltage (RGB)” line that shows “min. 22.5, typ. 24.5, and max. 26.5 mA” appears to apply to the controller, and probably to single outputs on that controller, which anyway would give a 3X multiplier. (The Cool White strips have three white LED chips per unit, instead of 1 each R, G, B.)

Note, the Adafruit DotStar LED Strip - APA102 Cool White webpage suggests using their 5V 4A power supply to drive “a half meter or meter” and their 5V 10A supply to drive “a couple meters”, which at 30 units per meter works out at 2/3 to 5/6 W of power supply capacity per unit.

# Answer
> 2 votes
You have correctly worked out:

```
I(A) = P(W) / V(V)

I = 0.2 / 5
I = 0.04A

MAX:
I = 1 / 5
I = 0.2A

```

From that it seems it will use between 40 - 200mA depending on brightness.

Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

More information on current sinking

---
Tags: power, led
---


title: VLcd pin to ground?

text:
# Question
Title: VLcd pin to ground?
I just bought an ERC12864-655 LCD screen.

On the datasheet it says that I need to connect the vlcd pin to GND.

However in this (page 8) datasheet it says that vlcd is the main power supply. As far as I know ground is no power supply. That doesn't make sense to me.

So what should I do with this pin?

# Answer
It appears that the LCD is powered/switched by the chip, not directly powered externally. The 10K to ground would be a pulldown to keep pin 20 from floating when the LCD is not being powered, and the .33 uF cap would be for power filtering.

The datasheet pointed to by your second link is a quality-control document; not quite what most of us call a datasheet, but Note B on page 1 suggests more documentation is available on the manufacturer's website. Their interfacing description and demo code should help.
> 2 votes

---
Tags: lcd, voltage-level
---


title: Update variable using buttons

text:
# Question
Title: Update variable using buttons
I made a part of code to change the temperature limit for alarm system. On warm days user have to change the temperature limit with buttons and OLED display.

**The question is:** How can the variable `templimit` keep its last setup value after many restarts(for many reasons)?

This is the code:

```
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit; // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.print("Update temperature limit if not wait 10 sec time out");
  updatevalue();
  Serial.print("Done");

}

void loop() {
// do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  timenow = millis();
  // this loop is just for 10 sec time out
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) {
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    if (timepassed >= 10000)
    return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }
  templimit = buttonPushCounter; // update templimit value

}

```

# Answer
> 0 votes
The microcontroller on the Arduino MEGA boards have 1024 bytes of EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive). These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.

I wrote two read/write functions if the value you want to write on EEPROM is **negative** because temperature has negative values too. Arduino EERROM write word with values between 0-255, also, has a lifetime 100,000 write cycle/ cell.

You can use EEPROM.update(address, value) instead of EEPROM.write(address, value) so the value is written only if differs from the one already saved at the same address.

**Save to EEPROM:**

```
void save_to_eeprom(unsigned int address, float config) { // (address, value)

  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }

```

**Read from EEPROM:**

```
float read_from_eeprom(unsigned int address) { //(address)
  float config;
  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
  }
  return config;
}

```

**This is how `templimit` will keep its last value after restart, the full code is:**

```
#include <EEPROM.h>

  float read_from_eeprom(unsigned int address) {// read
    float config;
    for (byte i = 0; i < sizeof(config); i++) {
      reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
    }
    return config;
  }

// this constant won't change:
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

// Variables will change:
int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit = read_from_eeprom(20); // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.println("Update temperature limit if not wait 10 sec for time out");
  updatevalue();
  Serial.println("Done");
  Serial.println(templimit); // temperature limit for alarm

}

void loop() {
  // do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  int counter = 10;

  timenow = millis();
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) { // this loop is just for 10 sec time out
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    delay(1000);
    Serial.println(counter--);
    if (timepassed >= 10000)
      return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }

  save_to_eeprom(20, buttonPushCounter); // save to address 20 tha value it can be negative

}

void save_to_eeprom(unsigned int address, float config) {// write value it can be negative

  for (byte i = 0; i < sizeof(config); i++) {
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }
}

```

# Answer
> 2 votes
An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex. Fortunately there is an Arduino EEPROM library already written for you. Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library. The read is self explanatory. But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write. In this way we save the EEPROM a little bit of ware and tare. As EEPROMs usually have a finite number of write cycles until they start failing. Which usually is in the tens of thousands.

---
Tags: button, eeprom, variables, memory
---


title: Using Arduino GSM with WiFi

text:
# Question
Title: Using Arduino GSM with WiFi
I have a project that requires data to be sent online from a moving bus. I am using ESP8266F modules to send the data.

I am wondering what Arduino modules to buy that will act as an access point with wifi and will connect to the internet through GSM.

In this configuration, the ESP8266 will connect to the access point and will upload the data online.

I want to connect a DF robot "SIM808 GPS/GPRS/GSM Shield For Arduino" to an Arduino Yun and use them as a wifi access point to connect to the internet through GSM connection.

The ESP8266 (5 of them) will connect to the Arduino Yun and will then send variables to the internet through the internet connection provided by the GSM.

# Answer
ESP is a full stack WiFi module. If you are intended to collect some data from several ESPs you can configure one more as an access point and collect those data from other ESPs as stations. At access pint you can make a small web server as well. To send aggregated data through GSM then you can use a GSM module wire-connected to this ESP. To avoid RF interference while GSM sends data, you should use different power sources and shielded twisted pair for connection. It may happan, that you will need to place GSM module at some distance from ESP access point to avoid overload of the receiver. Even better to use external antennae outside the bus for GSM and shield it inside the bus to minimise the interference. I do not see how Arduino can help here.
> 1 votes

---
Tags: esp8266, wifi, gsm, arduino-yun
---


title: Proper Attiny85 timer/delay

text:
# Question
Title: Proper Attiny85 timer/delay
Im having problems with Attiny85 programming. I am making something similar like this project. But i added function that every day on some time it turns on output - something like alarm clock. The real struggle is to make it active for longer time as one minute.. If current time is equals alarm time `wake_HOUR==hour()& wake_MINUTE==minute()` then it will run only for a minute so I added changeable field for the time how long output should be active - for example 5 minutes despite 1 minute. I tried to make timer with `millis()` and after those 5 minutes reset timer but this is where i stuck, because compiling for attiny it shows error, but if i use same code sample just for arduino then its working.. Code below:

```
#include <avr/sleep.h>
#include <TinyWireM.h>
#include <EEPROM.h>
#include "ssd1306.h"
#include "WDT_Time.h"

#define TIMEOUT 6000            //display timeout
#define UNUSEDPINA 1            //RESET
#define ALARM 4                 //ALARM
#define BUTTONPIN  3            //GND
unsigned int wake_HOUR = 0;     //Hours when it should wake up
unsigned int wake_MINUTE = 0;   //Minutes when it should wake up
unsigned int wake_SECOND = 0;   //Seconds when it should wake up - Not using
unsigned long ALARM_TIME;       //How long alarm should be active- changable in display
unsigned long new_millis = 0;   //Timer
unsigned long interval;         //How long alarm should be active
extern volatile unsigned long timer0_millis;
unsigned int ACTIVE_ALARM = 0;  //alarm activated?

#define SET_UP_BUTTON_THRESHOLD 100   //100k
#define UP_DOWN_BUTTON_THRESHOLD 600  //7k
#define PRESSED_BUTTON_THRESHOLD 1000 //NO resistance

// enum
typedef enum {
normal, sleeping
}  run_status_t;

typedef enum {
time_mode, debug_mode, alarm_mode
}  display_mode_t;

// button field constant
#define NO_FIELD 0
#define YEAR_FIELD 1
#define MONTH_FIELD 2
#define DAY_FIELD 3
#define HOUR_FIELD 4
#define MINUTE_FIELD 5
#define SECOND_FIELD 6
#define ALARM_HOUR_FIELD 7      //Alarm Hour
#define ALARM_MINUTE_FIELD 8    //Alarm Minute
#define ALARM_FIELD 9           //How long should alarm be active - minutes
#define SET_ALARM_FIELD 10      //Activate alarm
#define FIELD_COUNT 10
//#define ALARM_SECOND_FIELD 9

// variables
SSD1306 oled;
static uint32_t display_timeout = 0;
static run_status_t run_status = normal;
static display_mode_t display_mode = time_mode;
static display_mode_t last_display_mode = time_mode;
static bool time_changed = false;
static bool alarm_changed = false;
static uint8_t selected_field = NO_FIELD;

uint8_t wake_SET = 0;
//const char wake_BACK[15] = "GO BACK";

void setup() {
  // setup input pins, also pullup unused pin for power saving purpose
  pinMode(UNUSEDPINA, INPUT_PULLUP);
  pinMode(BUTTONPIN, INPUT_PULLUP);
  pinMode(ALARM, OUTPUT);
  digitalWrite(ALARM, LOW);
  interval = ALARM_TIME*60000;

  // init time
  init_time();

  // init I2C and OLED
  TinyWireM.begin();
  oled.begin();
  oled.fill(0x00); // clear in black

  // init display timeout
  set_display_timeout();
}

void loop() {
  // detect and handle button input
  check_button();
  unsigned long currenTime = millis();
  //unsigned long new_value;
  //setMillis(new_value);

  if (run_status == sleeping) {
    // return to sleep mode after WDT interrupt
    system_sleep();
  } else { // not sleeping
    if (millis() > display_timeout) { // check display timeout
      enter_sleep();
    } else { // normal flow
      readRawVcc();
      readRawTemp();
      draw_oled();
    } // normal flow
  } // not sleeping
  if (ACTIVE_ALARM==1)
  {
    if (wake_HOUR==hour()& wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    new_millis = millis();
    }
    else if (currenTime -new_millis <= interval)
    {
    new_millis = millis();
    digitalWrite(ALARM, HIGH);
    }
    else if (currenTime -new_millis >= interval)
    {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
    }}
  else if (ACTIVE_ALARM==0)
  {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
  }
}
//void setMillis(unsigned long new_millis){
//  uint8_t oldSREG = SREG;
//  cli();
//  timer0_millis = new_millis;
//  SREG = oldSREG;
//}

void enter_sleep() {
  oled.fill(0x00); // clear screen to avoid show old time when wake up
  oled.off();
  delay(2); // wait oled stable

  run_status = sleeping;
}

void wake_up() {
  run_status = normal;

  delay(2); // wait oled stable
  oled.on();

  // update display timeout
  set_display_timeout();
}

void set_display_timeout() {
  display_timeout = millis() + TIMEOUT;
}

/*
 * UI related
 */

void draw_oled() {
  if (display_mode != last_display_mode) {
    oled.fill(0x00);
    last_display_mode = display_mode;
  }
  oled.set_font_size(1);
  if (display_mode == time_mode) {
    // 1st row: print info
    oled.set_pos(5, 0);
    oled.print("TIME");
    oled.set_pos(80, 0);
    oled.print("AcALARM=");
    oled.print(digitalRead(ACTIVE_ALARM));
    oled.set_pos(80, 1);
    oled.print("A_TIME=");
    oled.print(digitalRead(ALARM_TIME));
    oled.set_pos(80, 2);
    oled.print("ALARM=");
    oled.print(digitalRead(ALARM));

    // 2nd row: print date
    print_digit(7, 1, year(), (selected_field == YEAR_FIELD));
    oled.write('-');
    print_digit(7 + (5 * FONT_WIDTH), 1, month(), (selected_field == MONTH_FIELD));
    oled.write('-');
    print_digit(7 + (8 * FONT_WIDTH), 1, day(), (selected_field == DAY_FIELD));

    // 3rd-4th rows: print time
    oled.set_pos(30, 4);
    oled.print("SET ALARM");
    oled.set_pos(3, 5);
    oled.print("HH:MM-->ALARM MIN");
    oled.set_pos(95, 5);
    oled.print("ON/OFF");
    oled.set_font_size(2);
    print_digit(0, 2, hour(), (selected_field == HOUR_FIELD));
    oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 2, 2, 2, 0b00011000);
    print_digit(2 * FONT_2X_WIDTH + 5, 2, minute(), (selected_field == MINUTE_FIELD));
    oled.draw_pattern(4 * FONT_2X_WIDTH + 6, 2, 2, 2, 0b00011000);
    print_digit(4 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 2, second(), (selected_field == SECOND_FIELD));
    print_digit(0, 6, wake_HOUR, (selected_field == ALARM_HOUR_FIELD));
    oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 6, 2, 2, 0b00011000);
    print_digit(2 * FONT_2X_WIDTH + 5, 6, wake_MINUTE, (selected_field == ALARM_MINUTE_FIELD));
    print_digit(6 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 6, ALARM_TIME, (selected_field == ALARM_FIELD));
    print_digit(80, 6, ACTIVE_ALARM, (selected_field == SET_ALARM_FIELD));
  }
  else if (display_mode == debug_mode) { // debug_mode
    print_debug_value(2, 'I', get_wdt_interrupt_count());
    print_debug_value(3, 'M', get_wdt_microsecond_per_interrupt());
    print_debug_value(4, 'V', getVcc());
    print_debug_value(5, 'T', getRawTemp());
  }
}

void print_digit(uint8_t col, uint8_t page, int value, bool invert_color) {
  oled.set_pos(col, page);
  if (invert_color) oled.set_invert_color(true);
  if (value < 10) oled.write('0');
  oled.print(value);
  if (invert_color) oled.set_invert_color(false);
}

void print_debug_value(uint8_t page, char initial, uint32_t value) {
  oled.set_pos(0, page);
  oled.write(initial);
  oled.set_pos(14, page);
  oled.print(value);
}

// PIN CHANGE interrupt event function
ISR(PCINT0_vect) {
  set_display_timeout(); // extent display timeout while user input
}

void check_button() {
  int buttonValue = analogRead(BUTTONPIN);

  if (buttonValue < PRESSED_BUTTON_THRESHOLD) { // button down
    set_display_timeout(); // extent display timeout while user input

    if (run_status == sleeping) {
      // wake_up if button pressed while sleeping
      wake_up();
    } else { // not sleeping
      if (buttonValue > UP_DOWN_BUTTON_THRESHOLD) { // down button
        handle_adjust_button_pressed(-1);
      } else if (buttonValue > SET_UP_BUTTON_THRESHOLD) { // up button
        handle_adjust_button_pressed(1);
      } else { // set button
        handle_set_button_pressed();
      }
    } // not sleeping
  } // button down
}

void handle_set_button_pressed() {
  display_mode = time_mode; // always switch to time display mode while set button pressed

  selected_field++;
  if (selected_field > FIELD_COUNT) { // finish time adjustment
    selected_field = NO_FIELD;
    if (time_changed) {
      wdt_auto_tune();
      time_changed = false;
    } //time changed
  } // finish time adjustment
}

void handle_adjust_button_pressed(long value) {
  if (selected_field == NO_FIELD) {
    // toggle display_mode if no field selected
    display_mode = (display_mode == time_mode) ? debug_mode : time_mode;}
  else {
    long adjust_value;
    if (selected_field == YEAR_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY * (leapYear(CalendarYrToTm(year())) ? 366 : 365);
    }
    else if (selected_field == MONTH_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY * getMonthDays(CalendarYrToTm(year()), month());
    }
    else if (selected_field == DAY_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY;
    }
    else if (selected_field == HOUR_FIELD) {
      adjust_value = value * SECS_PER_HOUR;
    }
    else if (selected_field == MINUTE_FIELD) {
      adjust_value = value * SECS_PER_MIN;
    }
    else if (selected_field == SECOND_FIELD) {
      adjust_value = value;
    }
    else if (selected_field == ALARM_HOUR_FIELD)
    {
      if (wake_HOUR >= 23)
      {
      wake_HOUR=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       wake_HOUR--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       wake_HOUR++;
       }
        }
    else if (selected_field == ALARM_MINUTE_FIELD) {
      if (wake_MINUTE >= 59)
      {
      wake_MINUTE=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       wake_MINUTE--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       wake_MINUTE++;
       }
        }
      else if (selected_field == ALARM_FIELD) {
      if (ALARM_TIME >= 59) //MAX 1h
      {
      ALARM_TIME=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       ALARM_TIME--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       ALARM_TIME++;
       }
        }
      else if (selected_field == SET_ALARM_FIELD) {
      if (ACTIVE_ALARM >= 1)
      {
      ACTIVE_ALARM=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       ACTIVE_ALARM--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       ACTIVE_ALARM++;
       }
        }

    adjustTime(adjust_value);
    time_changed = true;
  }
}

```

I would like to reset timer then when wake\_hours&minutes and changeable alarm activation time `interval = ALARM_TIME*60000` have passed.

```
      if (ACTIVE_ALARM==1)
  {
    if (wake_HOUR==hour()& wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    new_millis = millis();
    }
    else if (currenTime -new_millis <= interval)
    {
    new_millis = millis();
    digitalWrite(ALARM, HIGH);
    }
    else if (currenTime -new_millis >= interval)
    {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
    }}
  else if (ACTIVE_ALARM==0)
  {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
  }

```

Any ideas what kind a timer/delay i could use to make my code work?

# Answer
> 0 votes
So i fixed my problem. I didnt use timer what i wanted in the beginning but as the code it self's running clock i used current clock as to activate output and then based on clock to turn off output. Not always the hardest way is better. Basically this is what i needed to change:

```
if (ACTIVE_ALARM==1)
{
if (start_wake_HOUR==hour()&& start_wake_MINUTE==minute())
{
digitalWrite(ALARM, HIGH);
}
if (end_wake_HOUR==hour()&& end_wake_MINUTE==minute())
{
digitalWrite(ALARM, LOW);
}
}
else if (ACTIVE_ALARM==0)
{
digitalWrite(ALARM, LOW);
}

```

# Answer
> 2 votes
As noted in the comment of IgnacioVazquez-Abrams, in the instances at hand you should be using the `&&` (logical AND) relational operator, rather than the `&` (bitwise AND) arithmetic operator.

That aside, you should separate things out so that instead of an ungainly `if - else` series you have some independent cases. For example:

```
if (wake_HOUR==hour() && wake_MINUTE==minute()) {
   digitalWrite(ALARM, HIGH);
   alarmMillis = millis();
}
if (millis()-alarmMillis > interval) {
   digitalWrite(ALARM, LOW);
}

```

This will do the job, as follows:

• During the match-minute, `ALARM` will be driven high over and over, and `new_millis` will update to the current `millis()` value over and over. Which is OK.

• After the match-minute but before the end of the timed interval, `ALARM` will remain high and `new_millis` will remain fixed with the time of the end of the match-minute. OK, that's as desired.

• After the end of the timed interval, ie, when `millis()-new_millis > interval`, `ALARM` will be driven low over and over. Which is OK.

Note, I don't see a declaration of `currenTime` or anywhere it is updated. Hence, it does not represent current time and should not be used as such.

Note, `interval` should be declared as something like a `const unsigned long int`, with a value that is a minute shorter than the total length of interval that you want. (`new_millis` represents the *end* of the first minute of the interval.)

Note, `new_millis` should *not* be zeroed at the end of the interval. If the original code were magically made to mostly work, because of `new_millis` being zeroed it still would have a bug. During the first few minutes after each `millis()` overflow, a false alarm would sound. `millis()` overflows are about 49.71 days apart.

---
Tags: arduino-uno, attiny, timers
---


title: Time.h rollover after 49.7 days

text:
# Question
Title: Time.h rollover after 49.7 days
I'm developing a arduino based system, which includes a alarm system.

Searching on the Internet, I found these lybraries "Time.h" and "TimeAlarms.h".

In the requirements, it says: *"Time does not require any special hardware. Internally, Time depends upon **Arduino's millis()** function to keep track to elasped time."*

Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?

I don't think that waiting 49.7 days to test it is the better way.

# Answer
> 2 votes
As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.

Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).

# Answer
> 1 votes
You should simply buy a real time clock such as the common DS3231. They work well and don't have any problems with resting or continuous data reading. It also dictates the date!

Hope I helped :)

# Answer
> 1 votes
I have a lengthy post about this.

To avoid going to the link if you don't want to, the simple answer is to subtract when calculating time intervals, eg.

```
unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

```

This *always works!* \- even after 49.7 days - because of the way that unsigned arithmetic works.

The only time it would fail is if you needed to time an interval of over 49.7 days - in which case a real-time clock is an obvious answer.

Another example:

```
startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }

```

---
Tags: c++, timers, millis
---


# Question
Title: Is there a portable timer interrupt library?
I have a need for timer interrupt (for the sake of this exercise - say I need to execute something every second)

I found code in many places on the internets that does this using ISR for 328/Uno. (or specifically for other chips) But of course that does not work on other chipsets.

Is there a **portable** timer library that works across many/most/all arduino boards/chipsets?

For now it is a simple project - I have no other motors or tones, etc.

In my current project I have conditional compiles for different chipsets, to set up a callback/interrupt but would rather use a library that hides this all.

# Answer
I think it would be hard, or impossible, to make such a library. Already there are problems with pin-change interrupt libraries, and Software Serial (which uses pin-change interrupts).

Plus, to have a generic "callback" might tempt people to do things which they shouldn't anyway in an ISR, like do serial printing.

Let's say you choose to use a spare timer (eg. Timer 1). You have the issue now that you won't be able to do (some) PWM output because that uses Timer 1.

The closest would be to lever off the existing `millis()` code and just have a test in `loop` to see if the time interval is up, and then call a function - however that wouldn't be an ISR.
> 1 votes

---
Tags: interrupt, timers
---


# Question
Title: The Arduino Sketch does not save in Arduino folder location
I have just installed Arduino on Mac OS. The Arduino folder is created under Documents. But whenever I save the sketch it gets stored in some ghost location and gives an error, the same name already exits. Upon finding the location of file. It gets stored under this directory(Hidden).

```
/private/var/folders/_v/nbrwcsh51wd2k07kfhy9vhjm0000gn/T/untitled1010592992.tmp/sketch_sep28a

```

How can I move this location to my documents folder. In Arduino preferences, I have also changed the location of sketch, still it does save in above location.

# Answer
> -1 votes
* Download the latest IDE from Arduino.cc
* Drag your Arduino application icon to the trash.
* Open up terminal and type `rm -r ~/Library/Arduino15`
* Delete the Arduino folder in your Documents folder for good measure
* Drag the newly downloaded Arduino application to your application folder and see how it goes from a clean install.

Failing that PlatformIO IMO is a much better IDE for developing on these platforms : http://platformio.org/

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


# Question
Title: Get pin input status without using the arduino library
I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

```
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

```

Following digitalRead back to pgmspace.h:

```
#define __LPM_enhanced__(addr)  \
(__extension__({                \
    uint16_t __addr16 = (uint16_t)(addr); \
    uint8_t __result;           \
    __asm__ __volatile__        \
    (                           \
        "lpm %0, Z" "\n\t"      \
        : "=r" (__result)       \
        : "z" (__addr16)        \
    );                          \
    __result;                   \
}))

```

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.

# Answer
For reading, e.g., PB2, you would test

```
PINB & _BV(PB2)

```

where PINB is the port input register and `_BV(x)` is a macro defined as `(1 << (x))`.

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on port manipulation.
> 1 votes

---
Tags: arduino-mega, programming, c++, c, signal-processing
---


# Question
Title: Arduino Uno R3 not working with Cytron shield GPS 53
My project is to find latitude and longitude of certain places. I am using an Arduino Uno R3 with a Cytron GPS 53 shield to get the position of places but, my device cannot run because COM4 already in use. How to fix this error?

# Answer
> 1 votes
Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port. The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).

The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.

If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).

Hopefully that should give you a start.

---
Tags: arduino-uno, gps, tinygps
---


# Question
Title: Having trouble using RTC if I set an ISR for a 1 second timer
I built a sketch using some timer ISR code to get a trigger every second. (for the Atmega328 chip I use the following code I got form the internets. It works)

It runs fine and I get a trigger/callback every second.

```
void setupAtmega328()
{
#ifdef __AVR_ATmega328P__

```

// traceDebug("setupAtmega328() entry");

```
    cli();  // stop interrupts

```

// traceDebug("setupAtmega328() 1");

```
            //set timer1 interrupt at 1Hz
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1 = 0;//initialize counter value to 0
              // set compare match register for 1hz increments
    OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
                  // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS12 and CS10 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
//  traceDebug("setupAtmega328() 2");
    sei();//allow interrupts
//  traceDebug("setupAtmega328() 3");

#endif
}

```

I also wanted to add the capability of a real time clock (RTC) so I got a DS3231.

I downloaded and ran the sample app from this RTCLib on github

The sample code works fine when running under the Arduino IDE

However, when I add the RTC code to my sketch I don't get the results I want/expect.

**Specifically, the program seems to hang/halt** at the call to:

```
cli();

```

I am new to the Arduino platform and not sure what I am missing.
What do I need to do to get the RTC to work in conjunction with an ISR?

I wired the RTC according to the directions from Adafruit's site

I have other arduino boards that use different ISRs, but I have not tried them yet with the rtc since the 328 seems to be the standard arduino boars that is used to do initial work/testing.

**How can I use the 3231 RTC AND a 1 second ISR/callback?**

**EDIT:** I removed the trace/serial output - I had originally added those to track the code to see where I got but i think I exacerbated or added problems in doing that.

for those interested the code is at https://github.com/tjurik/Intervalometer

# Answer
> 1 votes
In the Arduino you don't have control how are some essential parts implemented.

For example `delay` function requires interrupts to be enabled or it'll be deadlocked (for sure).

Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your `traceDebug` is little bit longer.

In general `ISR` should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.

```
volatile bool flag = false;

ISR(...) {
  flag = true;
}

int main() {
  init();

  while (1) {
    if (flag) {
      do_something();
      flag = false;
    }
  }
}

```

---
Tags: timers, rtc, isr
---


# Question
Title: Can I use the same Data Registry for both input and output pins?
This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:

```
//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (condition to turn on light) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   if (condition to turn off the light) {
     *portDataB &= 0x7F
   }
}

```

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

I am using the Arduino Mega ATmega2560 btw.

From the comments I have this:

```
//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (portPinB & 0x10) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   else {
     *portDataB &= 0x7F
   }
}

```

# Answer
> 1 votes
Assuming the button is connected between GND and pin 10, without any pull-ups or pull-downs.

```
void setup () {
    //For the led output I know that I would do this
    DDRB = 0;             // set all pins on port B to INPUT
    DDRB |= _BV(DDB7);   // set PB7 to OUTPUT
    PORTB = 0;            // set all pins on port B to LOW
    PORTB |= _BV(PORTB4); // enable the pull-up resistor on PB4
}

void loop () {
    if( PINB & _BV(PINB4) )
    {
        // if bit PINB4 is set, the button is not pressed
        PORTB &= ~_BV(PORTB7); // turn off led
    }
    else
    {
        PORTB |= _BV(PORTB7); // turn off led
    }
}

```

# Answer
> 1 votes
> When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

---

**Clarification**

I take that question to mean "When I *assign* the value to 0x80 to DDRB". For example:

```
DDRB = 0x80;

```

In the code above that question, you were not assigning, you were "or"ing the value.

---

Yes. Typically you would "or" in the value if you want to affect only one pin, eg.

```
DDRB |= 0x80;

```

The conventional way to make it an input again would be:

```
DDRB &= ~0x80;

```

That is, "and" in the negated bit pattern for that pin.

Remember, you have 3 registers (per port) where "x" is "A", "B", "C" etc.:

* DDRx - data direction - a 1-bit is output, a 0-bit is input
* PORTx - output value - a 1-bit is HIGH, a 0-bit is LOW

However, if the data direction is input, then a 1-bit is input-pullup, and a 0-bit is not input-pullup.
* PINx - read the input from the port - a 1-bit is HIGH, a 0-bit is LOW

Note that writing a 1-bit to PINx toggles the output value of that port.

---

These remarks apply to the AVR chips, not the SAM ones.

---
Tags: arduino-mega, programming, pins, input
---


# Question
Title: Code for activating a led after 2 minutes and will blink after 30 seconds interval
Can anyone help me to build a code which will activate a LED after 2 minutes when the power supply is cut off and blink that LED after a time interval of 30 seconds. I want to import the code on Arduino-Uno.

I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the Arduino will blink the LED after 2 minutes and will keep blinking at 30 seconds interval

# Answer
Use a commonly available USB power pack re-charging from mains and powering the Arduino. Use a light source directly powered by main and optically couple that to an Arduino. There are plenty of examples on the web where an Arduino is used to detect light. Once triggered, write some additional code to blink the led. Since you are not doing anything other than timing, you can use the delay Arduino library to time events.
> 2 votes

# Answer
The Blink example will tell you how to blink an LED, you just need to change the times in the delay statements.

You want to detect the failure of a power supply. You Arduino has a backup battery (cell) to power it when the power fails. Correct?

There are voltage sensor kits available that can monitor mains voltage, just search for "Arduino Voltage sensor". However there is a risk to you working with main voltages. So using optical isolation (as ST2000 says) is probably safer for you. There may be some optical isolator IC that can manage mains and 5V, they are usually white in colour.
> 1 votes

# Answer
I have a code edited by me

```
int pinButton = 8; //the pin where we connect the button
int LED = 2; //the pin we connect the LED

void setup() {
 pinMode(pinButton, INPUT); //set the button pin as INPUT
 pinMode(LED, OUTPUT); //set the LED pin as OUTPUT
}

void loop() {
 start:delay(120000);
 check:int stateButton = digitalRead(pinButton); //read the state of the button
 if(stateButton == 0) { //if not pressed

   digitalWrite(LED, HIGH);
   delay(250);
   digitalWrite(LED, LOW);
   delay(30000);
   goto check;
 }
 else { //if  pressed
  digitalWrite(LED, LOW);
  goto start;
 }
}

```
> 1 votes

# Answer
DISCLAIMER: This is just a suggestion. No hate for this anwser please.

You could use a capacitor. A super capacitor (high capacity) with a proper joule theft circuit for your project could power the arduino for propably another 5min even if main power is cut off, plus you do not need any extra power source once the main source is cut off. It can be useful if you need to change the battery or move it to an other location but you do not want the module to be turned off.

```
const int led = 13;    //led pin
const int sensor = A0; //connect this your power supply, use a voltage divider if necessary
                       //this will act like a volt meter

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(sensor, INPUT);
}

void loop()
{
  int V = analogRead(sensor);
  V = map(V,0,1023,0,5); // the 5 is replaced with the ammount of voltage that you supply the arduino

  if(V < 1) // when the power is below a point or simply disconnected, the capacitor
            //will kick in by itself because the Arduino will draw its power
    {
    delay(120000)
    while(V < 1)
    {
      V = analogRead(sensor);
      V = map(V,0,1023,0,5);

      digitalWrite(led, HIGH);
      delay(500);
      digitalWrite(led, LOW);
      delay(29500);
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno, led
---


# Question
Title: DC Motor Pinning the Ada Fruit Moto Shield with the Mega2560 R3
I picked up an AdaFruit Motor Shield V2.3 . The example on the site shows how to code the DC Motor connection

```
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2)

```

What I'm unclear about is how to connect the shield to the mega board. Which pin on the shield should connect to which pin on the board in order for `Motor 1` to run at that speed?

# Answer
> 1 votes
Well because an Arduino Mega2560 is pretty much and UNO with a longer rear end, try seeing the UNO in the MEGA if that makes any sense. Then just put the shield in like a normal shield that you would put on a UNO. Most UNO shields are compatible with MEGAs. Then you just use your shield like if it was on an UNO.

---
Tags: arduino-mega, adafruit, arduino-motor-shield
---


# Question
Title: Can the Adafruit PN532 NFC/RFID be used to read Gen-2 EPC class RFID Tags?
I used Mifare Classic cards on a previous project and it worked brilliantly with the RIFD/NFC shield and Arduino Uno. I came across a Gen 2 EPC Class 1 RFID tags. This tags are long range ones. They use an IC chip called Alien Higgs3. I know that the shield itself is not capable of reading from a long range. I would just like to know if the shield is just able to read this type of tag even in close contact.

Is there a UHF RFID Reader that I can use to connect it with the Arduino and read these tags?

Any advice or suggestions are welcome. Thank alot.

RFID Tag Specifications:

Protocol- EPC Class 1 Gen2 Frequency- 860-960 MHz IC Type (chip)- Alien Higgs3

# Answer
It can not. The frequencies are different: 13.56MHz vs.868–956 MHz.
> 1 votes

---
Tags: rfid
---


# Question
Title: Serial.read() is getting a whole string rather than just a character?
From the arduino documentation, the `Serial.read()` function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:

```
#include "SPI.h"

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

void loop() {
  if (Serial.available() > 0) {
    char data1 = Serial.read();
    Serial.print(data1);
  }
}

```

And I open the serial monitor and send `"Hello, World!"` I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?

# Answer
You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.
> 1 votes

---
Tags: serial
---


# Question
Title: Is analogWrite() inferior to writing directly into registers?
I'm trying to control a DC motor's speed with my Arduino Mega `analogWrite()`, but it doesn't seem to function properly. The motor never completely slows down, just slows down a bit (which is still pretty fast) and then stops spinning completely.

I'm trying to create a robot with different speeds, and it just has to have a slow speed. I know it isn't the code, since the relay and motor works just fine when I use the `digitalWrite()`.

Is it better to write directly into the timer registers to implement the PWM, OR what else could be causing the problem?

# Answer
> 1 votes
1. `analogWrite()` is already PWM, Arduino doesn't produce a true analog signal
2. Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET
3. If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.

---
Tags: arduino-mega, motor
---


# Question
Title: Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328
Is it possible to take a bare ATmega328 chip, and with an Arduino as ISP, burn a sketch directly to the chip (e.g. not needing a bootloader), or is the bootloader required to run Arduino sketches? I want to embed the ATmega328 into a different device, and do not want the overhead of the entire Arduino board.

I have looked at https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard and https://www.arduino.cc/en/Tutorial/ArduinoISP, and want to do the "minimal circuit" approach (as my application does not require 16MHz).

The tutorial described has steps to first burn a bootloader, then remove the chip from the Arduino, and then install the sketch. Ideally, I would like to skip the bootloader and removing the chip from my Arduino. Ideally, I would like to do it all from Arduino Studio (not AVRDUDE CLI).

I don't mind "dedicating" my Arduino to this (as I assume it's just burning the ArduinoISP sketch whenever I want to burn to a new ATMega328).

Thanks

# Answer
It is possible to skip the **Burn Bootloader** step. When you do **Upload Using Programmer** the bootloader is overwritten and thus serves no purpose. However, there is another reason for the **Burn Bootloader** step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the **Burn Bootloader** step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom **Tools** menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.
> 5 votes

# Answer
The bootloader only enables serial programming of the device; it is perfectly possible to run Arduino programs without it provided that the code is compiled with the same hardware options (MCU model, clock speed, etc.) that the standalone device/board uses.
> 4 votes

---
Tags: atmega328, isp, arduinoisp
---


title: Problem building a smart shopping cart

text:
# Question
Title: Problem building a smart shopping cart
I'm building a smart shopping cart with Arduino for my final year project.

The cart is supposed to be able to follow its user while shopping. I don't know of many feasible indoor positioning systems to use.

**Proposed solution 1**

I have recently seen some RF/ultrasonic positioning systems that make use of:

* one ultrasound transmitter and one RF receiver, carried by the person,
* and two ultrasound receivers and one RF transmitter carried by the robot.

The robots RF transmitter sends out a signal, which when received by the person's RF receiver, triggers the person's ultrasound transmitter to transmit a signal. This signal is received by the robot's two ultrasound receivers (with a distance, d between them), and the distance and angle to the target person can be calculated.

That sounds very feasible, but my question is, if the robot is in a crowded place, where the other people are also carrying ultrasound transmitters and RF receivers:

1. Will the RF signal meant for the owner of the robot be accidentally received by the RF receiver on another person, or is there some kind of unique ID shared between RF receiver/transmitter pairs that could prevent this problem, or maybe some kind of frequency hopping system, so there would be no mistaken identity.
2. How will the ultrasound receivers on the robot be sure that the received signal is from its matching ultrasound transmitter. Again, is there some kind of special ID systems employed by some ultrasonic transmitter/receivers.

**Proposed solution 2**

I have also read about this new device called Trackr, it makes use of bluetooth low energy to track objects based on their proximity to bluetooth enabled devices like smart phones.

Considering a scenario where various bluetooth devices (beacons) are placed at specific points in a room, and the target to be tracked is equipped with a bluetooth emitter/bluetooth chip/dongle.

When the target passes each of those beacons, the signal strength intensity is received and distance from the target is calculated.

I understand this concept, but have some questions:

1. When distance is calculated between beacon and target, what about the angle, how would the robot follow the target based on distance alone?
2. If this method is not accurate enough to be used in a crowded space, what other method can be used, I have checked out some indoor GPS devices and they are way to expensive (above $200).

Would a camera-based tracking system be better and how easy would it be for a non expert like me to implement.

# Answer
I have a couple of ideas for you but know these are only suggestions. No hate please.

Have you tought of IR following?

IR is a almost unique signal that only you have. You can either use multiple IR sensors to determine where the emitter is or you can use the servo motor to do it as a radar. Note that you have to isolate each sensor so it knows where you are and it doesn't captures the wave from a different angle by accident.

Extra safety?

You can also incorporate an untrasonic distance sensor so that the cart doesn't bump into you or any one. Like you can say, if the distance is smaller then 12 inchs / 30 cm, stop the cart. It is practically an extra safety feature.
> 1 votes

# Answer
Try keeping it simple. I'd have the person wear and infrared transmitter. Then on the cart have an array of IR-receivers pointing in all directions. That way the cart knows which direction to go.

Next you need to get the distance to the target using e.g. an ultrasonic distance sensor.

Lastly you need to add some bumper sensor, so the cart known when it's running into an obstacle.

Your camera solution might also work, combined with OpenCV. But you can't run that on a measly Arduino.
> 0 votes

# Answer
Another solution, along the lines of your camera option, would be to seed the store with Kinect (or Kinect-like) camera systems. These systems are already designed to track multiple people at once.

Using this method you don't need to equip the shopper with any device, which lowers logistics (how do I get that device back when the shopper exits the building) and tech support costs.

You *might* need to equip the carts with some kind of marker - I don't believe the Kinect systems are designed to track inanimate objects, but I could be wrong.

So challenges to overcome with this system would be:

1. How to track the carts?
2. Kinect doesn't have a very large focal distance so you will need some kind of system to hand shoppers off to the next Kinect when they pass out of range of the one currently tracking them.
> 0 votes

# Answer
I'm going to get a bit ambitious here and suggest something along the lines of what the Vive virtual reality system uses. You can see from some of the photos on that site that the headset has lots of sensors on it. Judging by this article they detect signals from two base stations. I presume the base stations send IR beams (because radio would not be directional enough). The sensors on the headset are recessed a bit, which would shield them from anything but a line-of-sight beam from a base station.

## The store

Now you don't need anything quite that sophisticated, but something like this might work. First, you have some IR transmitters located around the store, pointing in a criss-cross pattern, like this:

The green box is the cart and the bigger boxes the shelving. Now with sensors on the corners of the trolley, pointing in different directions, and with each transmitter sending a differently-coded IR beam, the trolley should be able to work out its position fairly accurately.

## The trolley

By a process of exclusion (if you don't see a particular base station then you are not near it) and inclusion (if you *do* see a base station from a certain sensor then you can deduce a possible area you are in) you should be able to work out your position.

In this case we might expect that the bottom-left-diagonal sensor would be picking up signals from station 1003, and the bottom-right-diagonal sensor would be picking up signals from station 1004. Plus the forward sensor may be getting signals from station 1000 (depending on the range) and the rear sensor from station 1005.

## The shopper

Now we also need to know where the shopper is. If you gave the shopper a vest or belt with sensors on it in a similar way (eg. front, back, diagonal) then similar calculations can work out where the shopper is. Let's assume that each shopper and each trolley are given a unique ID pair (that is, a trolley is associated with a vest). Effectively, each shopper would transmit, every second or so "shopper 5677 is at position x=543, y=666 in the store".

Now we can use radio transmission (from the shopper) to its paired trolley, to tell the trolley where its "owner" is. And assuming the trolley knows where *it* is, then it can work out if movement is required, and if so, in what direction.

## Collision detection

In addition to the above, you would need some proximity sensors on the trolley (eg. ultrasonic) to stop the trolley from driving into other shoppers, display cases, its owner, etc.

## Maze solving

The trolley could have software on it to solve the problem of reaching the shopper. For example, if its way is blocked for too long on the shortest path, it might take an alternative which would be to go to the end of the aisle, go down a different aisle, and then back to where its owner is.

## Extra credit

1. You could make a button on the trolley you push when you are finished. The trolley could then "lead" you to the checkout with the shortest queue at it (or an empty checkout).
2. You could have some buttons on the trolley with major grocery types on it (eg. dairy food, bread, frozen foods). When pressed the trolley could lead you to the appropriate aisle.
> 0 votes

---
Tags: arduino-uno
---


title: Can't get ESP8266 working

text:
# Question
Title: Can't get ESP8266 working
I have received an ESP8266 (ESP-07) Wi-Fi module from DealExtreme (Link: http://bit.ly/2dFJdxE).
It is a 4-pin module with the following pins: RX, TX, VCC and GND. The module has a switch so you can switch between the following modes: Program & UART. The module also has a RESET-button.
Here's a picture of my module:
I've connected the module to my Arduino Uno like this:
RX \> RX,
TX \> TX(TX\>RX & RX \> TX, like mentioned in manuals, results in no connection),
VCC \> 3.3v (not using any level shifters because the module has on board level shifters),
GND \> GND.

I found a lot of manuals to test the module, but apparantly I can't get my module working. I am using Windows with the Arduino IDE.
The boards mentioned on the manuals/tutorials also seem to differ from my module because most of the manuals are talking about a board that has 8-pins (with an extra GPO0, GPO2 CH\_PD and RST pin).
I've tried to upload the BareMinimum sketch to the module, which only finishes uploading if I disconnect and reconnect the 3.3v input that's feeded to the ESP-board when the Arduino IDE says "Uploading...... " while the ESP-board is in Program-mode.
I have installed the ESP8266 library within the Arduino IDE and the **Generic ESP8266 Module** is selected.
Then when I open the serial monitor in the Arduino IDE, to test the AT commands (on different BAUD values), it does not respond (neither in Program-, nor in UART-mode).
Strange thing is when I keep the serial monitor on at 74880 BAUD (and UART-mode on the module) and I push the RESET button on the module, it gives the following message:

```
ets Jan  8 2013,rst cause:2, boot mode:(3,7)
ets_main.c

```

I've tried several things. But none of them seem to work; like trying to flash new firmware (for example 'v0.9.5.2 AT Firmware.bin' and 'esp8266-2016-05-03-v1.8.bin') with **esptool.py** with the following command:

```
esptool.py -b 115200 -p COM3 write_flash 0 FIRMWARE.bin

```

It says that the writing is finished and no errors appear after running the esptool. This is what is printed + command that is used:

`esptool.py -p com3 -b 115200 write_flash 0 firmware.bin
esptool.py v1.2-dev
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0000
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 44.2 seconds (94.1 kbit/s)...
Leaving...`

A strange thing is when I open the serial monitor in the Arduino IDE after that moment (without resetting the module/unplug from 3.3v or change to UART mode), it keeps printing the following at 115200 BAUD:

`Fatal exception (28):
epc1=0x4000228b, epc2=0x00000000, epc3=0x00000000, excvaddr=0x000000b5, depc=0x00000000`

I even tried it with the erase\_flash before and 0x00000 instead of 0. Also tried to run the command with a variety of flash\_sizes (with the command --flash\_size=Xm).
Esptool looks like the only tool where I can flash new binaries successfully, tried some others that where on some manuals but without success.
When I run `esptool.py -p flash_id`

I get the following response:

`Connecting...
Manufacturer: e0
Device: 4014`

Who knows how to fix this problem so I can send AT commands to the module through the serial monitor in the Arduino IDE.
Thanks in regards (this is my first post so if some things are unclear, please let me know)
**Edit:** Note that I have to disconnect and reconnect the 3.3v to the module EVERY time to successfully run a command (like write\_flash, flash\_id et cetera).
Also tried connecting it to 5v and using an external power supply next to the USB.

# Answer
> 1 votes
Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.

I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board. I'm pretty sure that you have now shagged it totally by trying to write programs to it. However you might be able to recover it if you can find the original program and upload that to it. You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.

I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes. As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)

If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.

---
Tags: arduino-uno, esp8266
---


title: neopixel not blinking

text:
# Question
Title: neopixel not blinking
I have some neopixels, and I have one hooked up to my teensy. I want to have the color change, when the push button is pressed vs not pressed. The LED will change colour when I upload the code, if I have the button pressed, green, if the button is not pressed, red.

The serial monitor reports changing button press statuses, so I'm not sure why the neopixel isn't changing.

The adafruit website is confusing to me, they have wonderful and involved project examples, but they never have just a basic IO example.

I would appreciate it, if someone could point out where Im going wrong with this code:

```
#include <Adafruit_NeoPixel.h>

#define PIN            0

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      1

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
const int buttonPin = 2;
int buttonState = 0;

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(0,OUTPUT);
  Serial.begin(9600);
  pixels.begin(); // This initializes the NeoPixel library.

}

void loop() {

buttonState = digitalRead(buttonPin);
Serial.println(buttonState);

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
      if (buttonState == LOW) {
          pixels.setPixelColor(PIN, pixels.Color(0,33,0)); // green
          pixels.show();

      }else{
          pixels.setPixelColor(PIN, pixels.Color(66,0,0)); // red
          pixels.show();
        }
        delay(500);
  }

```

this code compiles, without errors, and uploads just fine, but pressing the button won't change the LED color.

# Answer
I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.
> 1 votes

# Answer
I had a wiring Problem, the device wasn't properly grounded, but still illuminating.

Its working now on pin0, but the idea to use PWM pins is valid. Duly noted.
> 0 votes

---
Tags: led, adafruit, teensy, neopixel, code-review
---


title: LCD not doing anything

text:
# Question
Title: LCD not doing anything
I just bought an LCD. I connected everything as explained in this sheet.

This is the code I am using:

```
#define RST 3
#define CE 2
#define DC 4
#define DIN 6
#define CLK 5

void LcdWriteCmd(byte cmd) {
  digitalWrite(DC, HIGH); //DC pin is low for commands
  digitalWrite(CE, HIGH);
  shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
  digitalWrite(CE, LOW);
}

void setup() {
  pinMode(RST, OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(DC, OUTPUT);
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  digitalWrite(RST, LOW);
  digitalWrite(RST, HIGH);
  LcdWriteCmd(0xAE); // LCD set display enabled
  LcdWriteCmd(0x21); // LCD set power COntrol
  LcdWriteCmd(0x14); // LCD bias mode 1:40
  LcdWriteCmd(0xA2); // LCD basic commands
  LcdWriteCmd(0xA9); // LCD all segments on
}

void loop() {
}

```

The commands I used are in the command table of this sheet. (page 12) It is supposed to turn all pixels on now. However nothing happens. All pixels are staying off.

Can you see a problem?

# Answer
I am not so sure the command that you used to turn all pixels on is right. It might say it in the document but you should try to manually turn a couple of pixels on yourself. check the link bellow if you need more assistance with LCDs.

Also be sure that you connected some power and a potentiometer to the contrast pin and/or backlight of the LCD.

https://www.youtube.com/watch?v=dZZynJLmTn8
> 1 votes

---
Tags: lcd
---


# Question
Title: How to get the rightmost four bits from a byte
I have a byte that I am looking to break into 2 nibbles. The leftmost nibble I can get easily via shifting right 4 times. However, I can't figure out how to get the rightmost nibble. Any ideas?

# Answer
> 2 votes
Just mask it with an AND operator:

```
val = var & 0xF;

```

---
Tags: arduino-uno
---


# Question
Title: Using SoftwareSerial to send data to itself
I'm debugging a project which includes SoftwareSerial. I'm not convinced the serial connection behaves as expected, so I came up with the following simple test:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void setup() {
  Serial.begin(4800);

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i=0; i <= 10; i++){
    delay(10);
    mySerial.write(i);
  }
}

```

I connected pin 11 to pin 1 (arduino Uno), hence forwarding the data of the software serial connection via the default (hardware) serial connection to my computer. But no data is coming through.

Am I missing something?

# Answer
> 2 votes
If you are hoping to see the results in the serial monitor, you need to read it in and send it back (so it ends up on the USB port). Like this:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(4800);

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);

    while (Serial.available ())
      Serial.write (Serial.read ());
  }
}

```

Now you have to connect pin 11 to pin **0** (not pin 1) because that will now be the Serial Rx pin.

I think your method failed because with Serial active the Serial hardware was trying to drive pin 1 high (ie. idle) which was conflicting with the data from pin 11.

---

An alternative is to not do a `Serial.begin()` \- which therefore does not initialize the serial hardware and it doesn't conflict any more. This also works:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);
  }
}

```

Now you connect pin 11 to pin 1 as you originally wanted.

---

Notice I changed your `mySerial.write(i);` to `mySerial.println(i);` so you get correct data output (numbers, not control characters).

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