title: do i need to also connect GND and 3.3v

text:
# Question
Title: do i need to also connect GND and 3.3v
I am trying to run this code: https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino

Using an ESP8266 based D1 board and an RFID-RC522.

I am not able to get it to detect the rfid tags ...
the serial monitor just shows:

```
 ets Jan  8 2013,rst cause:4, boot mode:(3,4)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

```

The "Typical pin layout used" section of the above document does not mention any connections on the 3.3V & GND pins of the RFID-RC522 card.

Does this mean that I do not need to connect them?
Or is is just so obvious that I should connect them that they did not bother to write it in that section?

# Answer
> 4 votes
It is just so obvious that you should connect them that they did not bother to write it down.

The reader needs power. That is taken as read. Without power it can do nothing. Why would they bother to waste time telling you to connect the things that you have to connect regardless? The only things that they tell you to connect are things that are specific to the sketch - i.e., which IO pins to connect to which function on the reader. Power doesn't change - it's the same from sketch to sketch and from person to person. The IO pins do, though, and need to be detailed. Power and ground don't.

---
Tags: library, rfid, wires
---


# Question
Title: Using Arduino Yún to send data through Ethernet
I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.

I've seen other tutorials but they use Uno with an Ethernet shield. Is it the same with the Yún too?

How can I send data through Ethernet using Yún?

# Answer
> 1 votes
There are three bits of information you need to know:

1. The Ethernet port is connected to a tiny Linux computer
2. On Linux you can do HTTP POST and HTTP GET using a program called cURL
3. The AVR chip can tell the Linux computer what to do using the `Process` library.

Putting all those together: You need to use the `Process` library to tell Linux to run `curl` with the right parameters.

Just like the tutorials show you:

---
Tags: ethernet, arduino-yun
---


# Question
Title: LED Strobe based on switch press through Arduino
I have a problem I can't see to solve. I'm trying to program my Arduino, which I just got. I have read a lot of programming scenarios, but can't seem to find one that fits my problem.

I can get the LED to turn off and on like I want.

Assume a switch is pressed or even two wires to the LED are put together. Once the switch is pressed I'd like the LED to flash briefly, even though the LED has power to it. Is there a way to do this with Arduino code?

(1) Press switch (2) Flash LED briefly (3) Switch is still being pressed (4) LED remains off until switch is pressed again (5) loop through routine again.

# Answer
> 1 votes
This is a modified Example program that i have tested and seems to do what you expect. I have used a 2 position switch instead of a button. using a pointer "ledState" to indicate that the LED has flashed and have then combined 2 conditions with the "&&" in the IF statement.

```
/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int ledState = 0;
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if ((buttonState == HIGH)&&(ledState == 0)) {
    // Flash LED:
    ledState = 1;
    digitalWrite(ledPin, HIGH);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);
  } else if ((buttonState == LOW) && (ledState == 1)){
    ledState = 0;
    delay(50);
    }
}

```

---
Tags: arduino-uno
---


# Question
Title: Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters
When I am using RF 433 MHz module with ARDUINO MEGA then it is transmitting any text or anything in ASCII values. Now how to decode those ASCII values to alphabets? If I use ASCII conversion programme then what if I send a number and that conversion program converts that number also to text or related ASCII character? please suggest any way.

# Answer
Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0. When 8 ones or zeros arrive you have a byte. A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.

In your case your sending program is sending a letter, lets say A. Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII \[code\] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65. Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.

To show that A you might need to cast the data you receive to a character i.e.

```
unsigned char rxData = 0;
Radio.ReceiveData (&rxData, 1);
Serial.println((char)rxData);

```
> 2 votes

---
Tags: arduino-mega, rf
---


title: Steppermotor+Arduino Mega+ Adafruit

text:
# Question
Title: Steppermotor+Arduino Mega+ Adafruit
I have 2 Stepper Motors (QMot stepper motor1 Amp, 5.3Ohms, 5.3 volts and 200 steps/rev.) , which are connected to the Adafruit shield2.4, they are mounted to Arduino Mega, the motors pull generally 2 A from external current from Adafruit. My problem is, they don´t rotate smoothly, clearly and fast at the same time. When I use DOUBLE to define my Stepps, speed is ok but rotation is lout and shaking. When I use MICROSTEP is more smoothly but too much slow. The program is running two stepper motors to roll up optical cables. The cables have to be really precisely come together and accurately be installed on pulley. Also I need a solution to run my Steppers Motors smoothly, clearly and fast. Incidentally, I want to know, do I need BigEasyDriver for that? If you need more info oder fotos feel free to ask

Regards,

Paria

# Answer
I'd look for a proper stepper driver, e.g. something based on A4988 or similar. I wasted a fair amount of time on the Adafruit motor-shield 2.3 until I finally abandoned it after failing to achieve higher speeds (I also had lots of issues with the motor getting hot). The A4988 takes care of step sequencing including micro-stepping and interfacing and programming is very simple. It only comes in surface-mount packaging but there are bread-board friendly carriers costing a few dollars available from multiple manufacturers.
> 3 votes

---
Tags: arduino-mega, adafruit, stepper
---


title: Declaring literal strings

text:
# Question
Title: Declaring literal strings
When I want to write a literal string in Python, I use `r` before the string (or `@` in C#):

```
in [1]: print r'\no esca\pe ch\ara\cters'
out [1]: \no esca\pe ch\ara\cters

```

In straight c++ I can use `R`, but in the Arduino IDE, this throws the following error:

```
Serial.begin(9600);
Serial.println(R"\no esca\pe ch\ara\cters");

<output> invalid character '\'in raw string delimiter

```

So how do I do the same in Arduino c++?

# Answer
> 3 votes
Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.

```
Serial.println(R"(\no esca\pe ch\ara\cters)");

```

---
Tags: c++, string
---


# Question
Title: How do I read numbers from a serial sequence
I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.

My challenge is this;

I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.

The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.

Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.

If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.

Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.

Thanks

Callum

# Answer
> I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a decimal point just after it. You can use `strchr()` to find them. Then, you will have to prepend a zero if needed, and terminate the string one character before the decimal point.

The following code does this by overwriting the original string. If you need to keep that string, you will instead have to copy the relevant characters to another buffer:

```
char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}

```
> 2 votes

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


# Question
Title: Arduino Micro: how to switch off its blue power LED?
everybody!

I have a genuine Arduino Micro ("designed with adafruit", made in Italy) which is working perfectly well.

One thing I'd like to do but cannot figure out how (or at all), is to turn off the blue power LED. I hate blue LEDs, they hurt my eyes, and this one is particularly bright too.

I could just paint it over with black paint but maybe there are programmatic ways to switch it off?

Regards

# Answer
> 2 votes
The Blue LED is permanently connected to +5 volts through R5.

You would have to either remove R5 or the LED from the circuit board.

# Answer
> 2 votes
Unfortunately the blue LED is a direct connection between 5V and GND. You can see below in the schematic exactly how it is connected

The only way to 'turn off' the LED would be to remove either the 1K resistor or LED with a soldering iron.

Another possibility is to take a sharp knife and make a cut in the track directly before or after the LED. I've marked the locations where to cut on the eagle screenshot.

# Answer
> 2 votes
There is not way to turn it off in software.

The only thing you can do is desolder the led, or it's resistor. Just add some solder to the joints on both sides. Then angle the iron, so it touches both side. The led/resistor will tend to get loose and stick to the iron. Cleanup the board, by removing the excess solder.

I tend to just destroy the led using a utility knife. Just try to lift the "glass" on top of the led with a bit of force. Scrape over the white remains to make sure there isn't any connection left.

---
Tags: power, led
---


title: Bluetooth radio control of a motor

text:
# Question
Title: Bluetooth radio control of a motor
I need to purchase the correct bluetooth module for interfacing some simple functionality between an arduino and a motor. The tricky bit is getting the bluetooth radio to play nice with android and apple ios. There are things like MIT App Inventor, but I'd love to hear from someone with experience how to reliably control arduino from tablets/phones. Preferrably in a way that lets me define the control on the arduino. I can build android apps (slowly), not ios apps, but I would then have to either ask users to install untrusted apks or get it out through the google app store, which would take too long. Any help on this would be great.

# Answer
> 2 votes
You may want to have a look at the Adafruit BLE modules: https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/bleuart?view=all

They have provided great examples of how to connect from Android and iOS devices, as well as providing apps or code to integrate into your own apps and you get to implement the motor controller code yourself on the Arduino so should have full control over that side.

They even have an example where they are controlling a motor using an Arduino and Bluetooth, it may not be exactly what you need but hopefully gets you closer to an answer: https://learn.adafruit.com/bluetooth-motorized-camera-slider/overview?view=all

---
Tags: c++, motor, bluetooth, arduino-nano, shields
---


# Question
Title: I2C communication between 2 Arduinos with updated wire library
I would like to enable communication between two Arduino 101. From what I have read, the best method is to use I2C using the wire library. However, it seems as though the newest Arduino IDE has an updated version of the Wire library that no longer includes the `begin(int)` and `onRequest` functions.

All of the tutorials for I2C communication use these methods, so I am unable to follow and use them. It looks like when I change the board to Arduino Uno these functions are found, but as soon as I change the board to Arduino 101 the following errors appear no matching function for call to `TwoWire::begin(int)`.

When I try replacing my wire library with the older version, I get other errors for missing libraries and if I replace everything it is unable to compile on Arduino 101.

Can someone please help me or direct me to a I2C tutorial that uses the most updated version of the Wire library?

# Answer
The problem I see is the Arduino 101 uses an Intel microprocessor (Curie) instead of an Atmel microprocessor.

The only information I could find is on the Arduino page for the 101, which mentions it has dedicated pins for I2C, but it also says that you can use the Wire library. Maybe you just need to update your IDE?

I'd help more, but I can't seem to find any useful information on the Curie...
> 1 votes

# Answer
Although I did not manage to get wire communication to work, I was able to get the Arduinos to communicate through serial port. You just need to ensure to use Serial1 rather than Serial.
> 0 votes

---
Tags: i2c, wire-library
---


# Question
Title: Nano onboard "test" LED blinks when powered via 5V pin
I have a Nano (clone) that I am powering from a regulated supply via the 5V pin; I have checked this at the board and my multimeter reads 4.92V, which seems close enough (?). The main reason I don't use the microUSB jack is a space constraint. In any case, thus far it does work fine.

*Except* the leftmost (considered with the microUSB jack as "top") of the four onboard LEDs, on the opposite side from the rx/tx lights, blinks at a steady one second interval. Searching around, the only association I've found for that LED is that it is connected to D13, which I'm not using for anything.

What does this indicate? I have not tried disabling it (by setting 13 low) but I am hoping to do so if it is a benign issue.

# Answer
So, as per the comments on the question here's what I think happened:

That "test" LED lights briefly when the board is first powered on, indicating I suppose that it's booted and `setup()` is either complete or about to run.

It also lights briefly when the reset button is released.

In the sketch I'm using one of the digital pins is connected to RST -- the arduino is being controlled via UART. I have swapped some of the pin numbers and wiring around, so I tried leaving the one driving RST low instead of high and indeed, this seems to be the issue: It's resetting at ~1s intervals.

(I honestly believe I checked this before by removing all connections, but since I did not note that in the question, perhaps I never did...)
> 1 votes

---
Tags: power, arduino-nano
---


title: Sensor for underground water tank level

text:
# Question
Title: Sensor for underground water tank level
In a similar way to the question "**best way to determine if a 5 gallon water jug is getting empty**", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting. But it's a very different container.

I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres). Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load). Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.

The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited. It's in a harsh desert environment, but the pump room and power are only a few feet away.

Some ideas I had:

* suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller. Hard to install, ugly, low tech. Or something similar on a vertical pole.
* contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable). Corrosion/anodes might be a problem, although power could just be a short pulse at times. Condensation, spiders webs and dead bugs may give false readings.
* run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.
* ultrasonic (or light?) distance finder mounted under the hatch. Range needs to be up to 2 metres (6 feet).
* depth finder (sonar) on a float. Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).

The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).

Any other ideas? Has anybody ever done this?

# Answer
I have a background working on ships where robust and workable tank level gauges are a huge part of instrumentation available to you. Water is the most forgiving and easiest liquid to measure - it's cool, not too viscous, not corrosive in itself, and easy to clean off. There are a lot of options available to you.

Personally I would avoid any system which involves immersing anything in liquid if at all possible. Waterproofing isn't easy. I would also try to stay with a tried and tested system.

So to run through your solutions:

1. Multiple float switches - has poor resolution. Would be reliable. You can buy assemblies with LowLow, LowHigh, HighLow, HighHigh float limit switches already on them for maintaining tanks levels, but these are industrial quality with industrial prices.
2. This would work, but corrosion is going to be an issue. Resolution limited by how many contacts you have.
3. Interesting idea, but would likely require a lot of DSP work. Not a tried and tested method.
4. An ultrasonic sensor would be my preferred method. Non-contact, high resolution, range of 2m is easy. Tried and tested system.
5. Interesting idea, would require a lot of work. Easier to measure depth of air as per 4 and do the simple maths.

A few other methods come to mind:

1. A pressure sensor at the bottom of the tank. This is often used on ships, works well but needs immersion which can be avoided.
2. Inflow/outflow monitoring. A flow meter on the output can tell you how much you have used. Inferring level like this is prone to errors though.

There are a million other methods, but they get more and more complex.

The ultrasound would be a great way to do this. The commonly available Parallax Ping sensor would do the job. Realistically, you would only need to make measurements at most once every hour, so you could achieve great battery life. The concrete is likely to present a wireless range challenge. Most RF transceivers will get through concrete though, so place the receiver nearby.

If you want ideas on how it is done, google for ultrasonic *oil* level monitoring - there are loads of wireless commercial solutions.
> 12 votes

# Answer
http://playground.arduino.cc/Main/Waterlevel

The above link had a nice approach.

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.

When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.

A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.
> 17 votes

# Answer
It's tricky when you only have a small hole to work with, so trying to get inside to install a series of floats or contact pins on the side is not ideal. The ultrasonic is a good idea, but I don't know how that would be achieved. Personally, I would try the cable, as it is simple enough to drop it in the hole, and wait for your results.

If you wanted to try running a cable through it, you might want to use this Water Level Sensor, or at least base your own project on it.

It is non-corrosive, and has no moving parts, which is supposed to lead to a heightened accuracy, and less chance of it failing or breaking down. The enclosure is water-proof, and you can buy one with a relay attached to fit your monitoring needs. The only issue that I see is that it isn't wireless, but other than that, it seems to be pretty functional.
> 6 votes

# Answer
I know you asked this a few months ago .. but sometimes with something technical the project never gets completed, or at least not in short order.

So while you're building your new-world-order with an Arduino, can I suggest you put a pipe down the dip hole and insert a floating dip stick? 1.5" pipe. 1/4" dowel glued to a ping-pong ball. Flag on top of the dowel. Now you'll see the level any time you walk past.
> 5 votes

# Answer
I've been using the Ultrasonic method for close to a year and the biggest problem is the sensor failing due to water infiltration(condensation). My latest attempt lasted for about two weeks. I used plastic spray like the stuff you use on tool handles. I also used the wireless shield to make a website that displayed the level on any device connected to my router. I would like to get it to email me when the level is below 10% but can't get it to work....It's not bad but still needs work for stability...
> 3 votes

# Answer
Id go with an ultrasonic detector as Cybergibbons suggests together with a usage/flow monitor (http://www.ebay.com/bhp/water-flow-sensor) so as to understand if there are any losses through leaks etc. I'd use a YUN or Ethernet or shield to call or email you a monthly report / fill a datbase as well as place the order directly to the water supplier as well as cc'ing you.
> 1 votes

# Answer
The bubble tube method (http://dexautomation.com/?p=9) springs to mind.

Also capacitive measurement is doable (http://olimex.wordpress.com/2012/02/02/duinomite-project-tank-fluids-level-metering-by-capacitance-measurement/) but more tricky. If you can use the steel inside the concrete it can be made completely contactless.

Please note, that if the water is meant for consumption without filtering or purification you may want to refrain from direct-contact methods.

Googling for "tank level measurement arduino" yields lots of potentially useful results.

Also, is consumption so erratic that you can't predict when the tank needs filling?
> 1 votes

# Answer
The limited access issue is tough... If you were going to use the float idea, it would be hard to difficult to actually install the thing. The other issue is waterproofing components and making sure that they won't corrode and cause false readings, which defeats the purpose of installing the system. Although it is a different scenario, i use this Water Level Sensor to moniter my home aquarium. the sensor is totally insulated, and is thus waterproof. also the sensor itself is aproximately 1 mm in width,so it probably fit into your reservoir. From what i've seen so far from my use is that it is pretty accurate, and it works in both my salt water and fresh water tanks. Hope this helps!
> 1 votes

# Answer
I have used FM antenna cable successfully as soil moisture sensor and as fluid level sensor. Dip the bottom end into melted glue stick to insulate. For permanent installation in a water tank I would also dip the cable into a paint tin and hang it up to dry for extra insulation. Antenna cable without any extra waterproofing was used for soil moisture measuring for 3 years with no problems. The top end is connected to two parts of a LM393. The first one is a Schmitt trigger with 470K feeback and 1M series. The neg side is fed back with 220K. The second one is simply an inverter, and the output feeds back through a 220K. The two 220ks get connected to the sensor cable, and a parallel 100pf cap.The cable is thus excited differentially. The ciruit oscillates according to the capacitance of the sensor cable. The frequency is measured by your favourite micro. The extra 100pf is only there to keep the frequency in a range where the oscillations can be fed over a line. A bucket of water is enough to calibrate the setup.
> 1 votes

# Answer
You could take a piece of 2 conductor wire in a U shape that is weighted at the bottom of the "U" to rest at the bottom of the tank. (The reason to use a U shaped wire instead of a straight wire is to prevent having to insulate one end from the water). You would then measure the capacitance of the wire, where some baseline capacitance is the wire when dry and any wire that is wet would increase the capacitance proportional to the length that is wet. Any wire that is rated for outdoor operation, i.e. does not absorb water would do and actually the thicker the jacket the better as the baseline capacitance would be lower.

The capacitance could be measured in the same way as a capacitive touch sensor or a capacitance to frequency converter (Sometimes called an "Oscillator").
> 1 votes

---
Tags: sensors
---


title: How to structure data for HTTP upload

text:
# Question
Title: How to structure data for HTTP upload
I'm building a GPS tracker using an arduino nano, Adafruit Ultimate GPS breakout, a SD card slot and a SIM800L module.

So far everything works, the tracker uploads the data to a server as well as saving an extra copy to the SD card. The problem is now, that I don't really think that sending a HTTP request every cycle (gps data point) is very efficient and I would also like to have a way of storing information if there is no GPRS reception.

The idea is to save the GPS data to SD card and bulk send it out every 5 minutes or so.

What would be the best way to set up the data structure? I'm saving the deta in a csv style file:

```
2016-8-2 22:23:44, 52.53251922, 13.31121666, 18.30, 7, 1.33;

```

Parsing that is not the problem, but rather how to keep track of what has been sent already and what not. I was thinking about Marking the lines that I sent with a # or something similar as first character.

The only problem I could see with that would be performance, since it could take a while to go though it every time once it's getting a bit larger.

Thanks!

Lukas

# Answer
The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with `file.write(&your_struct, sizeof(your_struct))` and read in a similar manner into a struct.

* This will reduce the number of bytes written or read for any data point, and
* Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python `struct` module is very capable.

However, if you wish to continue with your current format, you can keep track of your current position in the file with `file.position()`; no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, `curr_pos`, and the other to hold the position of the end of the file for writing new data, `end_pos`. Initialize the former to 0.

* You gather data as usual, and after 5 mins, you save the current file position to `end_pos` and seek to `curr_pos` with `file.seek()`.
* You read a line from the file and send it to the server.
* If it's sent successfully (use the return code), you update `curr_pos` with `file.position()` so that it's now pointing to the next line in the file to be uploaded and go to step 2.
* Else if the upload fails perhaps due to service, you stop uploading and *don't* update `curr_pos`. You seek to `end_pos` with `file.seek()` and go to step 1.

You will, of course, use `available()` to know when you've hit the end of the file to stop uploading, or you can compare `curr_pos` with `end_pos` for equality, whichever's more direct for you.

This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.
> 1 votes

---
Tags: sd-card, gps, datalogging, http
---


# Question
Title: Printing the messages having problem in SIM 900A to Arduino
I have added my Arduino code for reading messages from GSM SIM900A using Arduino. But the output is showing something different. Please help me.

```
#define SERIAL_BUFFER_SIZE 256

char msg;
void setup() {
  Serial.begin(9600);   // Setting the baud rate of GSM Module
  delay(60000);
  Serial.println("AT");
  delay(1000);
  Serial.println("AT+CREG=1");
  delay(1000);
  Serial.println("AT+CMGF=1"); // set SMS mode to text
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  while ( Serial.available() > 0) Serial.read();  // removing serial buffer values
  Serial.println("AT+CMGR=1");
  delay(2000);
}

void loop() {
  while (Serial.available() > 0) {
    msg = serial.read()
    Serial.print(msg);
  }
}

```

This is the output:

```
+CMGR: "REC READ","+91xxxxxxxxxx","","16/07

```

# Answer
Hello Guys i found the issue. Serial.read() function reads only 62bytes. After i have update the serial buffer size in library file C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.H ... It shows the messages which is stored in serial buffer.
> 0 votes

---
Tags: arduino-uno, gsm
---


# Question
Title: Software Serial and multiple shields for Arduino Uno
I have a SIM900 GPRS/GSM Shield (details here) and I am looking to stack a GPS shield (such as this one here).

My question is: I believe that they both require software serial, also it says to use software serial on D7 and D8 for both. Is this possible on an Uno?

I am a bit confused at if software serial has to have these two specific pins, or if these are just what is chosen on schematics?

What would be the most effective way to stack these two shields so they don't interfere with each other?

EDIT: Using a gps shield such as this gives the option of

> If you need to move the software serial port pins, they can be custom-routed to any other pin by cutting the solder jumpers between pins GPS-RX and D8 and/or GPS-TX and D9.

This isn't entirely clear to me, but am I right in thinking it means I can have multiple software serials on my Uno, just using different pins?

# Answer
> 0 votes
SoftwareSerial can use any pins. That's the whole point of it. However, some shields are wired to use specific pins. If two shields try and use the same pins then you can't use them together. Not stacked, anyway. You will have to use flying leads, or physically alter the shield (cutting tracks, soldering in "bodge" wires) to use them together.

That said, though, you can only use ONE SoftwareSerial port reliably at a time. That means, regardless of what pins they use, you can't use two shields together that require pins other than 0 and 1 (hardware serial).

To use them both you will need a board with multiple hardware UART ports and modify the shields (as mentioned above) to use the correct pins for those UART ports.

---
Tags: shields, gsm, pins, gps
---


title: Simple IR Receiver code

text:
# Question
Title: Simple IR Receiver code
Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.

# Answer
Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino

I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.

```
#include <IRLib.h>

#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca  //LED ON
#define BUTTON_1 0x00bca  //LED OFF

#define LED_PIN 13 //Pin to LED

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;

void setup() { //Code to run once
  My_Receiver.No_Output();//Turn off any unused IR LED output circuit
  My_Receiver.enableIRIn(); // Start the receiver

  pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
  digitalWrite(LED_PIN, LOW); //Start off in the off position
}

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode(); //Convert the values into types
       if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
          switch(My_Decoder.value) {
            case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
            case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
          }
       }
     My_Receiver.resume(); //Wait for next input
    }
}

```

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this

```
void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        digitalWrite(LED_PIN, HIGH); //Turn the LED on
    }
    My_Receiver.resume(); //Wait for next input
}

```

**Edit:**

A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote

```
    #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in

IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;

void setup()
{
  Serial.begin(9600); //Start Serial at 9600 baud
  pinMode(LED_DATA, OUTPUT); //Set LED pin to out
  digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    //We have recieved something... lets print it and turn on the LED
    digitalWrite(LED_DATA, HIGH);
    Serial.println(results.value, HEX); //Send line in ascii hex format
    delay(200); //Make the LED visible
    digitalWrite(LED_DATA, LOW); //Turn off data led
    irrecv.resume(); // Receive the next value
  }
}

```

**Edit #2**

Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.

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

#define TIMER_RESET  TCNT1 = 0
#define SAMPLE_SIZE  64
#defome LED_PIN 13

int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;

void setup() {
  Serial.begin(115200);
  Serial.println("Analyze IR Remote");
  TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
  // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
  // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
  TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
  // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
  // TOIE1=0 => Timer 1 Overflow Interrupt Enable
  TIMSK1 = 0x00;
  pinMode(IRpin, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  Serial.println("Waiting...");
  change_count = 0;
  while(digitalRead(IRpin) == HIGH) {}
  TIMER_RESET;
  TimerValue[change_count] = TCNT1;
  direction[change_count++] = '0';
  while (change_count < SAMPLE_SIZE) {
    if (direction[change_count-1] == '0') {
      while(digitalRead(IRpin) == LOW) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '1';
      digitalWrite(LED_PIN, LOW);
    } else {
      while(digitalRead(IRpin) == HIGH) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      digitalWrite(LED_PIN, HIGH);
    }
  }
  Serial.println("Bit stream detected!");
  change_count = 0;
  time = (long) TimerValue[change_count] * 4;
  digitalWrite(LED_PIN, LOW)
  Serial.print(time);
  Serial.print("\t");
  Serial.println(direction[change_count++]);
  while (change_count < SAMPLE_SIZE) {
    time = (long) TimerValue[change_count] * 4;
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count-1]);
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count++]);
  }
  Serial.println("Bit stream end!");
  delay(2000);
}

```

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.

best regards, David
> 1 votes

# Answer
I know you want code. However your question is how to light up an LED when an external remote control is transmitting. This can be done with the following hardware:

Many ASK sensors integrate an IR photo sensor, AGC & PLL into a 3 pin package that has an appearance of a transistor. Supply power and get back a signal when an ASK IR transmitter is detected. Check the current capabilities of the ASK receiver, you might have to add a transistor to drive an LED. No Arduino needed for detection.

Here is an example found on the web:
> 0 votes

---
Tags: ir
---


title: Error when using buzzer and IR sensor

text:
# Question
Title: Error when using buzzer and IR sensor
I am doing code for IR sensor. My problem is when I put this code (below) for buzzer, there will be error.

C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of \`\__vector\_7' IRremote\IRremote.cpp.o:

C:\Program Files\Arduino\libraries\IRremote/IRremote.cpp:312: first defined here collect2: error: ld returned 1 exit status

```
  tone(buzzer, 4000); // Send 1KHz sound signal...
  delay(500);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(500);        // ...for 1sec

```

# Answer
> 2 votes
Both the IRRemote library and the tone command use the same timer. You can't use them both together without modifying one of them to use a different timer. And that means looking at the source code for them both.

---
Tags: ir, buzzer
---


# Question
Title: Sending data using Bluetooth SPP-C Module without a Breakout-Board
## tl;dr

I can't send data using the raw SPP-C Bluetooth module without a breakout board. The communication via UART works fine as I am able to issue AT commands and get proper responses. But when connected over Bluetooth the data passed over UART does not show up on my computer while the other direction works fine. Has anyone tried that module yet without using a breakout board?

## The long story:

I started my project by using a regular HC-05 module on a breakout board. The prototype worked just fine as there are also plenty tutorials available. The drawback using that breakout module is that it works with two voltages, 5V for power and 3V3 for communication. I have also more components in my project that run best at 3V3. That is why it came to my mind to use 3V3 as the only voltage. The raw HC-05 module without breakout board is also powered with 3V3. So everything looked just perfect.

Looking at the specs to the HC-05 I noticed that there is also more on that module like SPI and USB (page 12 bottom). So I got curious and off track.

Anyway. Instead of ordering raw HC-05 modules without breakout board I ordered cheaper SPP-C modules that don't have all this fancy stuff but just UART communication.

Following the description from Martyn Currey I was quicky able to issue AT commands and receive data over bluetooth. But I am not able to send data over Bluetooth.

I am using the same setup as it is shown on page 4 in the Chinese datasheet. (no I can't read that crazy symbols but I can read and understand the images)

# Answer
I found a solution myself. The modules are working as they are supposed to and are not faulty. Also I did nothing wrong.

The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using `minicom`. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.

After that I turned over to my Windows and used Hype! Terminal. Everything worked!

Then I went to my Raspberry Pi and Linux. After pairing using `bluetoothctl` and issuing a few commands from Bluetooth as ttyUSB. Everything worked as well.

Then I tried BlueSPP on an Andriod phone. And again, it worked as it was supposed to.

So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.
> 0 votes

---
Tags: bluetooth, uart, hc-05
---


title: Parse HTTP Request Arduino

text:
# Question
Title: Parse HTTP Request Arduino
I am sending a HTTP Request to my WiFi module `http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123`

How can I parse above string in Arduino. First I need to check for `STA`, if it exists, continue to scan the string. Put Value of `ID`, in this case `HelloWorld` should be store in String data type `SSID` and Value of `Pass`, in this case `Testin123` should be store in String data type `Pass`.

How can achieve above using ARDUINO code! Please help.

# Answer
> 4 votes
Your incoming string, as Gerben has mentioned, will actually be more like:

```
GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1

```

My personal preferred method is to use `strtok()` to split the string up. I'd use a two-pass method for this.

First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything). Assume the string is in C string `incoming`:

```
char *get = strtok(incoming, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");

```

The request is now pointed to by the `*request` pointer and the string has been sliced up in-place. So now you can do something similar with the request, this time splitting on `/` instead of space:

```
String SSID;
String Pass;

if (request != NULL) {
    char *part = strtok(request, "/");

    bool seenSTA = false;
    while (part) { // While there is a section to process...

        if (seenSTA) {
            if (!strncmp(part, "ID=", 3)) { // We have the ID
                SSID = String(part + 3);
            } else if (!strncmp(part, "Pass=", 5)) { // We have the password
                Pass = String(part + 5);
            }
        } else if (!strcmp(part, "STA")) {
            seenSTA = true;
        }

        part = strtok(NULL, "/");
    }
}

```

---
Tags: arduino-ide, esp8266, string, http
---


title: Ethernet shield and IPv6 support

text:
# Question
Title: Ethernet shield and IPv6 support
Have you heard about support for IPv6 protocol for any Ethernet shield? As far as I know only IPv4 is supported. Maybe some one would like to write library?

# Answer
**There is no library, and there physically cannot be one.** IPv4 is built into the Ethernet shield itself. (It has a *Wiznet 510* chip.)

> Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

*Source: this tutorial. (You may find it useful, I'd recommenced reading it.)*

There is this library for IPv6 on *other hardware*, not for the official Ethernet shield.
> 2 votes

# Answer
I have been working on an IPv6 library for Arduino, called EtherSia, that works with the ENC28J60 chip, but with a lower overhead compared with libraries that use Contiki / uIP. It is comparable to the EtherCard library for IPv4.

https://github.com/njh/ethersia

While the Wiznet chips do not support IPv6 natively, they do have a MACRAW mode that allows you to send Layer 2 Ethernet frames directly. I have managed to get IPv6 working with the Wiznet W5100 and W5500 chips, which is what the official Arduino Ethernet Shield and Ethernet Shield 2 use.

So it is possible...
> 2 votes

---
Tags: tcpip
---


# Question
Title: Arduino Serial library (Synchronous or Asynchronous?)
On an Arduino 101, I have this code running:

```
void setup()
{
 pinMode(2, INPUT);
 Serial.begin(9600);
}

int counter = 0;

void loop()
{
 Serial.print(millis()/1000);
 Serial.print("\t");
 Serial.print(counter);
 Serial.print("\t");
 Serial.println(digitalRead(2));
 counter++;
}

```

A wire can be used to jump Pin2 between 3.3V and GND.

When running with the Serial Monitor on, I see the values increment at a rate where counter increases by the hundreds very quickly and steadily ticks through the thousands over time.

If I close Serial Monitor momentarily and re-open it, I notice that this counter value has increased dramatically (by the tens-of-thousands). Another sign of this is when starting the program and waiting a moment to start the Serial Monitor. As the Arduino 101 does not restart when the Serial Monitor is opened, I see a large initial value in the tens of thousands despite having just started the program.

My question is this: is the Serial library operating synchronously or asynchronously? I was led to believe that it was asynchronous; however, if that was the case, why should the Arduino execute any slower when the serial monitor is on?

While I understand that increasing baud rate will increase the speed at which counter increases, I still see the same dramatic increase in this code when the monitor is closed and then re-opened.

Another possibility I thought of was that maybe counter was being stored in a buffer and what I was seeing was not an up-to-date time or count. To check this, the program prints the digitalRead value of pin2 as I swap the jumper between 3.3v and GND. This change in value was reflected instantaneously on the Serial Monitor, and I believe this means I am not seeing past data slowly being printed out to the monitor.

One last attempt at understanding what was going on was executing this code:

```
void setup()
{
 pinMode(2, INPUT);
 Serial.begin(9600);
}

int counter = 0;

void loop()
{
counter++;
if (counter%1000==0)
 {
  Serial.println(counter);
 }

```

In this example, counter can be seen ticking through quite fast, by the hundreds of thousands, which indicates that the program is capable of running very quickly until a print statement is made. The effect is notably less when baud rate is increased to something like 115200 but is that saying that baud rate is literally slowing the processing speed of the controller?

Any kind of explanation as to what exactly is going on would be very appreciated.

Thank You for your Time.

Source of Arduino being supposedly Asynchronous: https://itp.nyu.edu/physcomp/lessons/serial-communication/serial-communication-the-basics/

# Answer
> 6 votes
The Arduno 101 doesn't communicate to the PC using a UART. It uses CDC/ACM over USB, which *looks* like a UART to the PC. But it isn't.

* USB sends packets of data, not individual characters
* It only sends if there is something to receive it at the other end
* There is no such thing as *baud rate* with USB.

Basically, when the CDC/ACM port has been opened by an application (e.g., the serial monitor) the Arduino 101 starts to send the data down the line. When the port is closed all data to be sent gets silently dropped by the Arduino since there is nowhere to send it to.

Hence when the port is closed it runs much faster since the data that would normally have to be packed into packets and sent down USB isn't. It's just thrown away.

---

To address your confusion:

You are misunderstanding the concept of synchronous and asynchronous with regards to serial. There are basically two types of serial communication: Asynchronous, where both ends have to (pretty precisely) agree on the speed of communication (baud rate), and synchronous, where one end tells the other end what the speed is by providing a discrete clock signal. UART (RS-232, RS-485, etc) is asynchronous. It sends at a specific rate and has to rigidly stick to that rate for the other end to be able to receive it properly. SPI and I2C are synchronous - they both (as master) provide a clock signal to the receiving end (slave) and the receiver *synchronises* its reading and writing of data with that clock signal (hence *synchronous*).

You are confusing those concepts with another meaning of synchronous and asynchronous - terms that could better be used would be *parallel* and *sequential processing*. If something happens *in parallel* then two (or more) things happen at once. This is the case of the hardware UART where you submit characters to be sent to the buffer and they get transmitted out by the hardware separately to the sketch - in parallel. Sequential would mean that one thing has to happen after the other. If the UART behaved like that your program would stall every time you wanted to send a single character.

So UART processing happens in the background, in *parallel* to your sketch. So does USB data processing for CDC/ACM. These things are generally coupled with interrupts to allow the CPU to handle tasks such as placing more data in the buffer or storing data that has arrived somewhere that you can get to it. Interrupts aren't strictly parallel, in that they do stall your program while they run, but they are kind of in a different thread, or *context*. So they appear to be parallel.

# Answer
> 0 votes
The Universal asynchronous receiver/transmitter (UART) is a chip that control the actual wires for serial communication. The UART operates independently and asynchronously.

As far as I know the UART (or USART) has a buffer, and the serial.print\* functions will write to this buffer, and if it is full will block until the buffer has room. The UART will consume the buffer and transmit it over the wire. So your code will run full speed until the buffer is full then it will have to wait for the UART to make space.

> ... but is that saying that baud rate is literally slowing the processing speed of the controller?

When the UART's buffer becomes full, the Serial API has no choice but to wait for the buffer to empty so it can fill it again. This makes it appear as if the code is running synchronously; waiting on the buffer is essentially acting as a synchronization device. So yes a slow baud rate can slow the micro-controller down since the code is forced to wait for the UART even though it is asynchronous!

You may not notice any of the above effects, since even 9600, a relatively slow rate, is much faster than humans can read. 300 baud is approximately the rate at which humans can read comfortlably. If you repeat your experiments with a higher baud rate you should see the text fly past on the serial monitor much faster than at 9600; if you lower the speed to 300 (the lowest supported by the library) you should be able to read along, and see that things do go slower. The buffer on the UART is rather small, and even when slowing down to 300 baud, it might be difficult to see the buffering behavior.

When the serial monitor is closed the serial communications are still happening, the UART on the receiving side is receiving the data, but it gets dropped on the floor since no one is reading it. If you were to disconnect the serial wires at some point this should stall the sending UART which should cause the serial.print\* functions to block (alternatively the UART could be configured to drop the data if it can't physically transmit it over the wire.)

---
Tags: serial, communication
---


title: Installing Pyserial

text:
# Question
Title: Installing Pyserial
I will be running my CNC Via Arduino UNO R3, so i have found out that it runs on GRBL and that i need to load Python and Pyserial and a graphic interface. Loaded Python 3.5.2, no problems, opened dos window typed Python, got the python \>\>\> prompt, so far so good, downloaded/unzipped/copy/paste Pyserial into c:/python35/lib/site-packages/pyserial. at this point, at the dos prompt i type \>\>\>python setup.py install. All i get is a syntax error.

I have included the dos script for comment

```
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Goblin>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> os.getcwd()
'C:\\Users\\Goblin'
>>> os.chdir("/users/")
>>> os.getcwd()
'C:\\users'
>>> os.chdir("/../")
>>> os.getcwd()
'C:\\'
>>> os.chdir("/python35/lib/site-packages/pyserial/")
>>> os.getcwd()
'C:\\python35\\lib\\site-packages\\pyserial'
>>> python setup.py install
  File "<stdin>", line 1
    python setup.py install
               ^
SyntaxError: invalid syntax
>>>

```

This is about the 7th attempt. I seem to be following the instruction correctly but it wont install ....HELP Please, this is so frustrating, what have I done wrong. Thanks in advance Doug

# Answer
> 2 votes
not exactly related to Arduino but here it goes...

First check if you have pip installed:

```
pip --version

```

**if not installed** go here and download the get-pip script. then on directory where you saved get-pip run on console:

```
python get-pip.py

```

this will install pip into your system which makes installation of packages in python way more easy.

if installed but not latest version ( at momment 8.1.2) do an upgrade before:

> On Linux or OS X:

```
pip install -U pip

```

> On Windows:

```
python -m pip install -U pip

```

after install pyserial using pip:

```
pip install pyserial

```

**Did it work?** If not, try:

```
python -m pip install pyserial

```

**if it still doesn't work** install from source. Get the latest version here extract it and in the dir where you extrated run:

```
python setup.py install

```

PS: change to dir first, no need to do it inside python.

# Answer
> 2 votes
I'm pretty sure that what you are trying to do is actually call 'python setup.py' within the python script itself. Which you cannot do. The easiest way to install pyserial is via pip like so. (Windows)

```
python -m -U pyserial --upgrade

```

Now if you still want to use setup.py or you don't have pip installed. Make sure that you meet all of the package dependencies. Which in pyserial there are no others. Try exiting out of the python interpreter and just running

```
python setup.py install

```

In the same folder location as the extracted zip (use cd to change directories)

# Answer
> 0 votes
Thanks All...by running the command at a std DOS prompt I was able to install the Pyserial.py file. i have since seen comments that some of the 3.x.x series Python has glitches,(I am running Windows7). I have gone to 2.7 Python as a program i would like to use doesn't appear to run under 3.x.x bCNC likes the earlier versions, not sure why, but it does run under 2.7 . for those interested JCNC, EFL CNC, Grbl Controller seem to run OK under 3.x.x

---
Tags: arduino-uno, programming, python
---


title: Frequency generator

text:
# Question
Title: Frequency generator
Can arduino generate the frequency with the resolution of 2 decimal places? i.e. 100.12 Hz, 98.23Hz, 1.92Hz...

recently I need to generate a frequency to allow a stepper motor to move accordingly. But to ensure the stepper motor to functions normally, frequency must be generated , and it must be of 2 decimal places.

Can Arduino do that? Or is there any specific product that may generate frequency resolution as such?

# Answer
The standard Arduino Uno is clocked at a nominal 16MHz, and has three timers: Timer0, 1 and 2. Timer1 uses a 16 bit counter (the others are 8 bit), and can be prescaled by 1, 8, 64, 256 and 1024. That lets you do *very* precise timings (assuming an accurate clock!), simply by choosing different prescaler values and the relevant values.

Using your example rates, and assuming that you want a square wave (hence the "Halved" column), here are the calculations:

```
 Hertz Prescaler  Calculated      Halved  Actual Hz
100.12         8  19976.02876548   9,988  100.120144173...
 98.23         8  20360.3787      10,180   98.231827112...
  1.92       256  32552.08333333  16,276    1.9200049...

```

Note that to do this, you need to program the Timer yourself - the standard Arduino library sets Timer1 to a default setting, which won't do what you want.
> 1 votes

# Answer
I happened to do a similar analysis for Timer 1 on 328 / 32U4 clocked at 16MHz the other day and produced this plot:

This shows the frequency resolution as a proportion of frequency in red assuming optimal prescaling (the jumps are where prescale changes). The blue markers are realized frequency errors at frequencies drawn at the E12 series in magnitudes from 0 to 5. Unsurprisinly these are half or better than the resolution.

As a conclusion, you get a relative error of around 5e-5 for frequencies up to about 1kHz. After that you loose an order of magnitude per order of magnitude (which of course makes perfect sense).
> 1 votes

# Answer
The other answers about the way you can configure the timers are very good, but Edgar Bonet's comment goes to the heart of the matter. Do you need accuracy?

Your example of 98.23Hz suggests that you want 98.23Hz and not 98.22Hz or 98.24Hz. That means therefore that you require an accuracy of around 1 in 10000 (0.01%).

> Can arduino generate the frequency ...

You haven't said *which* Arduino, but assuming one of the basic models, like the Uno, they come with a *resonator* which will have an accuracy of around 1%.

If the system clock is only good for 1% accuracy there isn't much point worrying about trying to get a frequency within 0.01%.
> 1 votes

---
Tags: pwm, frequency
---


title: IR basic connection

text:
# Question
Title: IR basic connection
Can I know how to change or connect from this circuit (three pin IR receiver) to two pin IR receiver because when I change the connection (3 pin to double pin), my arduino cannot receive the signal from transmitter.

I dont know because of my connection or because of there are different between tree and double pin IR receiver. Can anyone help me.

My code too long, so I just paste IR sensor for detect signal from transmitter.

```
{
  indicator();
  irrecv.resume();
  while(1)  //-------loop M1
  {
      HM_1();
      if(irrecv.decode(&results) >0 || digitalRead(SBB) == HIGH )
      // if IR receiver detect signal or button pressed
      {
         indicator();
         break;
        //irrecv.resume();
      }//
      else
      {    //-------else "if(sensor 2)"
          //go back to else "if(sensor 1)"
      }//-------else "if(sensor 2)" end
      //nothing
    }//-------while end
}

```

# Answer
From what you have described, i think you are getting confused between the function of the two types. The 3 leg style is designed to receive coded pulses from remote controls (TV,Video, etc) where as the 2 leg is typically used, but not limited to, IR switching, where a signal is generated when the light path between the sender and receiver is broken with an opaque blade or similar or a beam is reflected back from an object as it passes. So trying to use the same code for the two types is provably where you are having problems.

Two example of this are here this uses a reflected IR beam where as this slot sensor is the break a beam type, often used in a limit or timing situation. One half of this is similar to the 2 leg diode you show.

It just depends on what situation you are using it in as to which is appropriate.

Without seeing your code, this is about as far as i can go, post your code so the forum can view it and make suggestions.
> 3 votes

# Answer
To expand on Doug's answer:

There are two types of IR receiver. The two-pin one you have is basically a photodiode with infra-red filter. When infra-red light hits it the transistor gets biased and turns on. This is the most basic type you can get and is very hard to work with for anything other than simple on-off signals.

The second type is the IR receiver *module*. This contains a photodiode as above, but also contains extra circuitry. It receives IR light on the photodiode and filters it through a band-pass filter. A remote control sends a sequence of pulses of light which itself is further made up of high frequency pulses (36KHz square wave, for example). It's this high frequency pulsing that is allowed through the band-pass filter. The internal circuitry then turns these pulses of high frequency square waves into pulses of ON or OFF signals by low-pass filtering them to remove the high frequency component.

This latter type of receiver is far easier to work with for sending of data or commands from (eg) a remote control. But it can't detect a steady-state IR signal. The modulation and filtering means that a much weaker signal can be extracted from the background IR light meaning much greater distances can be achieved using much weaker transmission LEDs.

So while it is possible to use the former type with an Arduino you have to realise that the software required to do all the filtering and detection, as well as the extra hardware required to interface it, makes them considerably harder to use. That is why almost everyone uses the three-pin versions that do all that for you.

One thing to note with the three-pin versions: they have to match the carrier frequency of the transmitter. So a 36KHz transmitter has to be paired with a 36KHz receiver. Otherwise it won't be able to detect the signal. Just like a radio - it has to be tuned to the right band.
> 3 votes

---
Tags: ir
---


# Question
Title: NRF24L01 Direct Communication Library Logics
Actually I'm using the RF24 Library mantained by TMRh20 (https://github.com/TMRh20/RF24). I'm trying to get some type of direct communication between multiple modules working, but I don't want to use the RF24Network Library (https://github.com/TMRh20/RF24Network) which creates a mesh of connections.

I currently have several arduinos that have to communicate between them. Every arduino has its own address starting from 0x0001 (0x0000 is for a main module that manages everything) and finishing to 0xFFFF. I want to directly communicate between the two NRF24L01+ modules without any intermediator, because I don't have problems of distance.

The main thing that I want to be able to do is communicate directly not with just one module, but choose if I want to broadcast to all the modules in an area (I know that it can be done with range power modifications in the code) or talk with just one module.

What is the best way to do this type of communication?

# Answer
> 1 votes
Both of the Libraries you mentioned are well written. I've used both, but decided to write my own based those libraries. For me, the network libraries were written for their project and didn't really fit my needs. So I decided to write my own. I combed the internet for a bare bones NRF24 Library and found this one. This was my starting point. It didn't need the Arduino Core Library and handled all the SPI functions. Then I read the NRF24L01 datasheet several times, then read it again.

With that said, you can broadcast up to 6 radios at a time. Per the datasheet, the receiver knows which radio sent the packet. The STATUS register (0x07), should tell you who sent the packet:

I was unable to get this working (I am still working on it), so for now, I send my packet as a struct:

```
typedef struct  {

uint8_t id;
uint32_t data;

}
Packet;

Packet pck;
pck.id = 2; // id of my second radio

```

Keep in mind when you program your Arduino as the receiver, you have to tell it who it will be receiving from. The transmitter and receiver have to be on the same RF channel, speed and same pipe. To choose who receives the packet may not work the way you think, but as I mentioned you can program the receiver to know who the transmitter was and code around it.

I would suggest you dig into the datasheet.

# Answer
> 0 votes
If you set pipe 1 to a common address (let's call it the broadcast address) anytime you send a packet to that address all the modules will receive it on that pipe! It's as simple as that, but you will not be able to use auto-ack (you will receive multiple acks, one per each receiver) and you can't also use ack payloads.

I wrote a series of blog posts on this modules and I'm going to keep writing on the topic.

# Answer
> 0 votes
You need to dig into the datasheet and read about ESB (Enhanced ShockBurst). This is technology that is integrated into the radios and allows for broadcasting and direct pipes. One of the limitations is that the mesh only works for up to 6 pipes, so be aware that this limits the number of devices that will be able to hear your transmission.

Another option is to have all the nodes listening on the same pipe, and then when node x wants to talk, he stops listening on pipe 1234 and starts writing to it. You would put some sort of addressing header in the payload section of the packet, then when all of the nodes receive that packet, they can check that address and see whether or not to process it. This might work well in your situation.

For example, if you have a packet that is sent on the communal pipe with a payload of \[broadcast address,data\] then your receiving nodes (those within "earshot") can receive the packet, see that it is a broadcast, then process the data. If you want to send to a single node, create a packet that has a payload of \[destination node id,data\]. When each node receives that packet on the communal pipe, they will check the destination, and when it doesn't match either their own address or the broadcast address, then they dump it. Only the intended receiver will actually process the data.

---
Tags: arduino-uno, rf, nrf24l01+, communication
---


# Question
Title: Arduino Due - using built in ADC as a DSO causes issues at high frequencies (kHz)
I am trying to use the inbuilt ADC of the Arduino Due to measure voltage signals. The frequency range I'm interested in measuring is up to about 30 kHz.But I'm observing a strong capacitor behaviour as I increase the frequency ( from 10kHz onwards this is quite visible).

This is most visible when measuring a square wave. When I get close to 30 kHz the signal looks exactly like the text book capacitor charge/discharge wave and nothing like a square wave. Even at around 15 kHz, the square wave looks more like a sine wave/ ramp signal than a square wave.

Based on the behaviour my guess is that a capacitor in the Arduino Due ADC is causing this (as the frequency increases, the capacitor cannot charge/discharge fast enough). But I'm not sure whether I'm correct about this. Even if I'm correct, how can I fix this?

Any help would be much appreciated.

Thanks.

I don't have screenshots for the behaviour for a range of frequencies, but I will attach a hand drawing of what it looks like.

Also NOTE that As the frequency increases, the amplitude of the observed wave decreases ( I couldn't show this in my drawing). Think this again links back to the capacitor charge/discharge speed behaviour.

My Vin circuit : I tested by adding a voltage follower at the right most end(not shown on the schematic), but that made no difference.

# Answer
> 1 votes
Fixed : The issue was with the LM324 op-amp. It has a small slew rate (0.5 v/uS) which was causing the signal to flatten out at high frequencies. So had to change to an op-amp with a better slew rate.

# Answer
> 1 votes
Well, if you have source output impedance about 1k and Sample-And-Hold capacitance is 14pF, then RC time constant is about 14us.

You need something with low output impedance. Non-inverting Voltage Follower would be perfect for this (see source):

---
Tags: arduino-due
---


# Question
Title: ESP8266 does not respond after changing baud rate to 9600
I have ESP8266 WiFi module and Arduino Mega Board connected. I use external 5 to 3.3 V regulator to power up the module. Common (-ve) line on the external power source and Arduino Mega GND is connected. Then I used 1K and 2K voltage divider for WiFi module RX and TX use as same. I am sure my circuit is well works.

Then I connect RX0-RX and TX0-TX. Then i put CH-PD to 3.3v

Then I opened the Arduino IDE and upload the Blink sketch. Done.. Then I opened Serial Monitor and set baud rate to 115200. Then power up the module. It gave me a lots of garbage values and ready. Fine.

Then I downloaded the FLASH\_DOWNLOAD\_TOOLS\_v0.9.5. configure the 0x0000, 0x1000 and 0x7c000

1. SPI speed = 40MHZ
2. SPI mode = QIO
3. FLASH size = 4Mbit
4. 0x1000 = ai-thinker-0.9.5.2-9600.bin

Then O power off the module and connect GPIO0 to ground and again power on.

Then push start button. Then it downloaded to the chip. It worked. Done. Success fully uploaded. Then I again disconnected the GPIO0 and power on. Then I put AT and it results OK.

AT+GMR gives version 0.9.5 updated.done.

The problem was the module was responded for 115200 baud rate, not 9600. Then I:

```
AT+IPR=9600

```

it gives me nothing.

Now I can't communicate with it at either 115200 or 9600 baud. No respond whatever baud rate I put. Sometimes I am having same garbage values.

# Answer
> 1 votes
This is a common issue. Using the `AT+IPR` command seems to brick the module. Try to re-flash your module, like you did the first time. If it works, use this command: `AT+UART_DEF=9600,8,1,0,0` instead to change the baud rate.

---
Tags: arduino-mega, esp8266
---


# Question
Title: What are the Ramps pins on my Arduino mega?
I've been working on a 3D printer and I've come to the last step, which is wiring it all up.

The 3D printer I'm making works ONLY with the Arduino Mega. No Ramps. If I need to get Ramps later, I will, but for now, can someone please help me understand which of the Ramps pin goes with which Arduino pin. For example, in the Repetier firmware, the code is like this:

```
#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38
#define X_MIN_PIN           3
#define X_MAX_PIN           2

```

But Arduino doesn't have a 54 and a 55 pin. I've been googling this and I found that Ramps pins 54 - 69 are the same as pins A0 - A15 on the Arduino Mega.

I know this but not for the other pins...

Can someone please tell me the connection of all the Ramps pins to the Arduino pins?

Like: pin 54 on Ramps = A0 on Arduino. I need this for all of the pins.

# Answer
You are right, your have all the information in your question.

Pin 54 Refers to the Arduino PIN Number, nothing to do with RAMPS. 0-53 are the digital pins and the 54 is A0, etc. So the pin numbers should go higher than 69, which is A15.
> 1 votes

# Answer
You're very close to your answer. Here are the specifics:

```
Name      software pin  Mega2560 board label
X_STEP_PIN    54         Analog A0
X_DIR_PIN     55         Analog A1
X_ENABLE_PIN  38         Digital 38
X_MIN_PIN     3          PWM 3
X_MAX_PIN     2          PWM 2

```

http://reprap.org/mediawiki/images/3/3f/Arduinomegapololushieldschematic.png shows the mapping.
> 0 votes

---
Tags: arduino-mega, hardware
---


# Question
Title: analogRead values all over the place, while measuring light
I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.

Minimal sketch:

```
while( true )
{
    int photoValue = 0;
    analogReference(INTERNAL);
    photoValue = analogRead(A5);

    Serial.println(photoValue);

    delay(300);

}

```

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:

```
0
0
4
4
0
16
15
22
21
25
20
36
40
34
36
24
5
0
3
6
0
0
0
0

```

That would translate to values between 0 and 43mV.

When I disconnect the multimeter only get `1023` printed.

I don't get how the values from the ADC and the multimeter, totally don't match.

# Answer
> 1 votes
The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.

Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.

The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.

By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.

---
Tags: adc, analogreference
---


title: pH ORP sensor esp12 esp82666

text:
# Question
Title: pH ORP sensor esp12 esp82666
I need to know if there is a sensor that mesure pH and ORP, I have already googled about this type of sensor but i found only AtlasScientific that commercialise this kind of sensor

thanks

# Answer
> 0 votes
Yes there are lots. You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226. This might be useful: http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS

---
Tags: esp8266, hardware
---


# Question
Title: Pros and Cons of using a non-pointer class object
In this example I have an one object which uses a pointer and one object which does not.

```
class MyClass {
  public:
    void myMethod() {
      // do nothing
    }
};

MyClass* mc1;
MyClass mc2;

void setup() {
  mc1 = new MyClass();
}

void loop() {
  mc1->myMethod();
  mc2.myMethod();
}

```

Is one implementation better than the other? Why?

# Answer
In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.

The static declaration (`MyClass mc2`) will reserve space in the BSS. The dynamic allocation (`mc1 = new MyClass()`) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).

The only trouble starts to come when you want to free (`delete`) the object created with `new`. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.

For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.
> 1 votes

# Answer
It depends on what you are trying to do and partly a matter of taste but I tend to take this one step further when the class corresponds to a specific hardware resource. In this case you can use static methods exclusively to guarantee a 1 to 1 correspondence. Templates come to rescue when you want to bind a specific physical instance of some finite resource (e.g. one of the timers) and this can be further refined using specialization and traits (each timer has different characteristics).
> 0 votes

---
Tags: pointer
---


# Question
Title: Uno R3's a4 and a5 not working after installing itead SD Shield 3.0
I'm working on a data logging project and would like to use all six analog inputs on my Arduino Uno R3. I've been able to get everything working, including writing to the SD card. However, with the shield installed I'm getting junk readings from a4 and a5. They work fine without the shield.

# Answer
The shield has pull-up resistors for I2C/TWI on pins A4 and A5. Special care (resistor bridge) needs to be taken if using these as analog pins. Please see the schematics for more details.

https://www.itead.cc/wiki/images/4/46/Sch\_sd\_shield\_3.0.pdf

Cheers!
> 1 votes

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


# Question
Title: Arduino Mega 2560 Only Powers on with USB
I have an Arduino Mega 2560 board running a ramps 1.4 shield for a 3D printer. For some reason, I can only power the Mega with USB. It does not get power from the ramps shield and it also will not power on when plugged in to a 12v wall adapter. I know all power sources are working because I have a second Mega that works fine on all. What could I check on the Mega board to help figure this out. Other than being powered only by USB, everything else works as expected with no problems.

# Answer
> 2 votes
Looking at this Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.

Looking at this ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560. And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results. Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.

If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.

---
Tags: arduino-mega
---


# Question
Title: Atmega328p - PCB ISP pins for bootloader and sketch upload
I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.

I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.

# Answer
> 2 votes
Realistically, you should design ATmega boards to support both ISP and bootloader pins. The logic is simple:

* Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.
* Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.
* You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.

---
Tags: atmega328, pcb-design
---


# Question
Title: Arduino Saint Smart Chapter 7 Tri Color Module
I am very new to Arduino, I bought a starter's kit and I am working with the user manual that is available. I am in chapter 6 Tri Color Module

I am using the following code:

```
// Defining the LED driver pins and some other
// variables.
const int numLEDs = 3;

int blueLEDPin  = 3;
int greenLEDPin = 4;
int redLEDPin   = 5;
int ledPin[3];
int ledPinIndex = 0;

// the setup routine runs once when you press reset:
void setup() {

  Serial.begin(9600);

  // initialize the digital pin as an output.
  ledPin[0] = blueLEDPin;
  ledPin[1] = greenLEDPin;
  ledPin[2] = redLEDPin;

  for (int i=0; i < numLEDs; i++)
     pinMode(i, OUTPUT);

}

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

  digitalWrite(ledPin[ledPinIndex%numLEDs], HIGH);
  delay(1000);
  Serial.println(ledPinIndex%numLEDs);
  delay(2000);
  digitalWrite(ledPin[ledPinIndex%numLEDs], LOW);

  ledPinIndex++;
}

```

My problem is that in the setup() method where the following code is

```
for (int i=0; i < numLEDs; i++)
         pinMode(i, OUTPUT);

```

From my understanding pinMode OUTPUT is use to send power out of the specific pin. As the code displays pin 3, 4, and 5 are used but the above code is setting pinMode for 0, 1, 2. Is this write? And even if I comment out the two lines up my project no differently as to the previous code.

Can someone verify if the above code is correct, or should it be setting pinMode for 3, 4, and 5.

# Answer
> 2 votes
This line `pinMode(i, OUTPUT);` should probably be replaced by `pinMode(ledPin[i], OUTPUT);` Otherwise it won't make sense.

---
Tags: arduino-uno
---


title: Testing Logic Gates using Arduino

text:
# Question
Title: Testing Logic Gates using Arduino
hello guys is there someone who can help me with my first project. its basically about logic circuits.

by using tact switch and pull-up resistor to set the values to logical 1 or 0. the output can be verified by using a LED as an indicator. so the code goes like this:

```
//AND GATE
int pin2=1;         //set pin2=1
int pin3=1;         //set pin3=1

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)            //turn led on pin11 when pin2 =1
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)          ////turn led on pin12 when pin3 =1
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF AND

  if(pin2 && pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//OR GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF OR

  if(pin2 || pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//NAND GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF NAND

  if(!(pin2 && pin3))
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

```

can you guys help me to run this in one sketch by using tact switch to select the logic gate to be tested or run? thank you in advance

# Answer
What about something like this:

```
const uint8_t    inA =  2;
const uint8_t    inB =  3;
const uint8_t   outA =  4;
const uint8_t   outB = 11;
const uint8_t   outY = 12;
const uint8_t button =  5;

void setup() {
    pinMode(inA, INPUT_PULLUP);
    pinMode(inB, INPUT_PULLUP);
    pinMode(outA, OUTPUT);
    pinMode(outB, OUTPUT);
    pinMode(outY, OUTPUT);

    pinMode(button, INPUT_PULLUP);
}

uint32_t check_time = 0;

uint8_t     counter = 0;
uint8_t       funct = 0b0110; // start with XOR

void loop() {
    // active low: (for usage with buttons connected to ground with internal pullup)
    // uint8_t state = (digitalRead(inA)==LOW) | (digitalRead(inB)==LOW)<<1;

    // active high:
    uint8_t state = (digitalRead(inA)==HIGH) | (digitalRead(inB)==HIGH)<<1;

    digitalWrite(outA, (state & 1) > 0);
    digitalWrite(outB, (state & 2) > 0);

    digitalWrite(outY, ((funct >> state) & 1) > 0);

    // button handling
    uint32_t actual = millis();
    if (actual > check_time) {
        check_time = actual + 4; // check every 4ms

        if (digitalRead(button) == LOW) { // expects pull-up and active low
            if (++counter == 4) { // debounce - confirmed after 16ms (4*4) and every 256*4 ms again
                funct = (funct + 1) & 0xF;
            }
        } else {
            counter = 0; // reset counter
        }
    }
}

```

It uses push button to cycle through all 16 possible functions of two inputs. Default is XOR. Assumption is Active HIGH inputs (you can use INPUT instead of INPUT\_PULLUP).
> 1 votes

# Answer
For simulating different gates with the same program, an option is to use the serial port to tell it what gate you want it to simulate. Here I am also using a function pointer (called `gate`) to represent the selected gate:

```
/* Wiring. */
const int inputA    = 2;
const int inputB    = 3;
const int outputA   = 11;
const int outputB   = 12;
const int outputRes = 4;

void setup()
{
    pinMode(inputA,    INPUT_PULLUP);
    pinMode(inputB,    INPUT_PULLUP);
    pinMode(outputA,   OUTPUT);
    pinMode(outputB,   OUTPUT);
    pinMode(outputRes, OUTPUT);
    Serial.begin(9600);
    Serial.println(F("Type 'a'(for AND), 'o' (OR) or 'n' (NAND)."));
}

/* Available gates. */
bool AND(bool a, bool b)  { return a && b; }
bool OR(bool a, bool b)   { return a || b; }
bool NAND(bool a, bool b) { return !(a && b); }

/* The gate we want to test. */
bool (*gate)(bool a, bool b) = AND;

void loop()
{
    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    digitalWrite(outputRes, gate(a, b));
}

```

Here is another version, that uses an `enum` instead of a function pointer to identify the gate. The constants and the `setup()` are the same as before, then:

```
void loop()
{
    // The gate we want to test.
    static enum { AND, OR, NAND } gate;

    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    bool res = false;
    switch (gate) {
        case AND:  res = a && b;    break;
        case OR:   res = a || b;    break;
        case NAND: res = !(a && b); break;
    }
    digitalWrite(outputRes, res);
}

```
> 1 votes

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


# Question
Title: How do I split a number into individual digits?
How would I split `part1` into 2-3 digits and put them into `num1`, `num2`, and `num3`?

```
int FMSTATION = 10250;

int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;

  part1 = (FMSTATION / 100);
  part2 = (FMSTATION % 100);
  part2 = (part2/10);

  int num1 = ;
  int num2 = ;
  int num3 = ;
  int num4 = part2;

  matrix.writeDigitNum(0, num1, false);  //1st number on lcd
  matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
  matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false);  //4th number on lcd

  matrix.writeDisplay();
}

```

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is `102.5`.

# Answer
> 9 votes
`% 10` returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.

So if you have the number 10250 as an integer you can get at each number with:

```
10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

```

So your code could be written as:

```
num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

```

No need to mess with "part" variables.

# Answer
> 1 votes
I think this will help you:

```
int FMSTATION = 10250;
int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;
  part1 = (FMSTATION / 100); //102
  part2 = (FMSTATION % 100); //50
  part2 = (part2/10); //5

  int num1 = part1/100; //1
  int num2 = (part1 % 100)/10; //0
  int num3 = part1%10; //2
  int num4 = part2; //5

  matrix.writeDigitNum(0, num1, false); //1st number on lcd
  matrix.writeDigitNum(1, num2, false); //2nd number on lcd
  matrix.writeDigitNum(3, num3, true); //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false); //4th number on lcd

  matrix.writeDisplay();
}

```

---
Tags: programming
---


# Question
Title: How to control 12v water pump by arduino?
I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?

# Answer
It's not possible to control it directly. You need relay module (better one is with opto coupler).

Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.
> 0 votes

---
Tags: arduino-uno
---


title: Burn arduino bootloader using ubuntu 16

text:
# Question
Title: Burn arduino bootloader using ubuntu 16
I get the following error when I try to burn the arduino bootloader on an atmega328 mcu:

```
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05

```

I am using an Arduino as ISP programmer. My computer runs Ubuntu 16.

This did not happen when I was using Ubuntu 14. I also tested it on another machine with Ubuntu 14 and this error does not appear. Seems to be something with Ubuntu 16. I installed Arduino IDE using the out of the box repo.

The avrdude command launched by the IDE is:

```
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xde:m -Ulfuse:w:0xff:m

```

Am I safe replacing the -Uefuse:w:0x05:m with -Uefuse:w:0xfd:m ?? If answer is yes how can I get the IDE to do this correctly?

Uploading a sketch works pretty well.

# Answer
> 1 votes
I had same problem and I think I have solved it.

In boards.txt file, I had:

```
##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino diecimila.build.variant=standard

## Arduino Duemilanove or Diecimila w/ ATmega328
## --------------------------------------------- diecimila.menu.cpu.atmega328=ATmega328

diecimila.menu.cpu.atmega328.upload.maximum_size=30720
diecimila.menu.cpu.atmega328.upload.maximum_data_size=2048
diecimila.menu.cpu.atmega328.upload.speed=57600

diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05
 diecimila.menu.cpu.atmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

diecimila.menu.cpu.atmega328.build.mcu=atmega328p

## Arduino Duemilanove or Diecimila w/ ATmega168
## --------------------------------------------- diecimila.menu.cpu.atmega168=ATmega168

diecimila.menu.cpu.atmega168.upload.maximum_size=14336
diecimila.menu.cpu.atmega168.upload.maximum_data_size=1024
diecimila.menu.cpu.atmega168.upload.speed=19200

diecimila.menu.cpu.atmega168.bootloader.high_fuses=0xdd
diecimila.menu.cpu.atmega168.bootloader.extended_fuses=0x00
 diecimila.menu.cpu.atmega168.bootloader.file=atmega/ATmegaBOOT_168_diecimila.hex

diecimila.menu.cpu.atmega168.build.mcu=atmega168

##############################################################

```

I have replaced the line containing:

```
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05

```

with:

```
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0xFD

```

Everything is ok now.

I can install boot loader on an ATMEGA328P (with an usbasp programmer), and I can install sketchs after that (via usb serial).

I don't know if it's the best way to solve the problem, but it works. Hope this will help you, if not already solved.

---
Tags: arduino-ide, bootloader, ubuntu
---


title: Connecting external mic to the Teensy

text:
# Question
Title: Connecting external mic to the Teensy
I have a Teensy 3.2 and the Teensy audio board.

I was going to connect lavalier microphone to its audio jack but learned that it's only for output. There are line-in pins though (see "Back Side" scheme). And MIC+GND pins, but these are for, ehm, radio parts microphones, I guess?

Being a complete novice I have no idea how to connect microphone jack (or audio connector) to line-in pins and whether I would need an amplifier between microphone and pins. If so then probably I just can't do it.

I would be grateful for detailed instructions.

# Answer
It is easier than I thought! I soldered audio jack to MIC+GND, inserted microphone in and it works! And pretty well :-) Cheap random lavalier model: Panasonic RP-VC201. I guess any consumer model will do.
> 0 votes

---
Tags: teensy
---


# Question
Title: Arduino servo seems to time out after code runs for some amount of time
I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?

Here is my code:

```
#include <Servo.h>

int servoPin = 9;
Servo servo;

int servoAngle = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    servo.attach(servoPin);
}

void loop() {
    // put your main code here, to run repeatedly:

    int randnum = rand()%(40000-1000 + 1) + 1000;
    int randnumreturn = rand()%(600-350 + 1) + 350;
    servo.write(45);
    delay(randnum);
    servo.write(22);
    delay(randnumreturn);
}

```

# Answer
> 2 votes
`int` in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is `> 32767`, you would get a minus value, which may cause delay not to work properly.

In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.

**Edit:** I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.

---
Tags: arduino-uno, servo, time
---