text:
I need 70 or more input pins for the Arduino -how to do this?
I have some SN74HC165N, CD4021B chips. How many (minimally) such ICs would I need to get 70 inputs to an Arduino Uno? What is the exact circuit diagram and the code? Im not sure how the wring cascades into each of the chips to make it grow to over 70 inputs, or what the code is for the 70 input circuit. I do understand how to use one of those ICs though. My second easier question is -is there an development board with 70 or more inputs?
CD4021B,SN74HC165N are the chips, you know the ones, that has a parallel input pins that are listened to by latch pin, and the clock pins such outputs the parallel data into the serial data-so I am interested with solution with this pin because I know how it works.
It is for sure 70 pins that are required -not any less-I am sure of that. Because the inputs cannot be further simplified to less than 70. The reason the inputs are 70 is because the algorithm used has 70 free variables in it. Hence by definition it uses 70 or more variables. The input for each of the 70 inputs can be a digital high or a digital low but this is not known before hand. So it cant be simplified because it like saying you can simplfy the information from 70 or more sensors at runtime, and each sensor has an unpredictable value. Anyway this explanation is moving away from the point of my question. I just want to know the circuit that does 70 inputs or more using the mentioned IC-I can live with that answer even if its not the most efficient.

"is there an development board with 70 or more inputs?" Possibly. The ATmegaXX0 has enough GPIOs, but the Mega doesn't expose all of them.

Are your inputs digital-logic-level signals, or switch contacts, or what?  It makes a difference, eg matrix techniques and multiplexers are relevant in some cases but not others.  What response times are needed?  Polling, or interrupts?  Is this a one-off project, or will you make multiple copies?  (Please edit question and add that info)

Two of these could do the trick; http://anarduino.com/gpio-expander/

The best way I know to do it is by using the MCP23017, which gives you 16 extra GPIOs via I²C communication. They can be configured for both input and/or output. I've done it myself and it worked like a charm. It has 3 pins for dynamic addressing (3 bits), which allows you to use up to 8 (0..7) MCP23017 for a total of 128 extra GPIOs.
This is the chip datasheet:
(http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf)
There's a lot of examples about its use on the internet. Just google for "MCP23017 arduino" and you'll find them. For example:
http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

Personally I prefer the MCP23S17 - the SPI version. Faster communication, and as many groups of 128 GPIOs as you have spare IO pins for CS.

That's another good option. At the time I chose the I²C version because I was working with the ESP8266 (ESP-12) and I didn't have the driver for SPI comm, only for I²C. For Arduino you can easily use the SPI version indeed.

Just with that number of chips you want to watch your pin capacitance - you may want to boost the signal strength with some IO drivers.

@Vinicius I'm thinking about your answer which I never considered before. Can I get the MCP23S17 to work with Arduino Uno I2C bus? Using I2C bus do I use wire library to set up what input and out port? and to write values? to get it to work

There are libraries available to do all the work for you. Google for them.

You probably mean MCP23017?

I have some 74HC595 chips. How many (minimally) 74HC595 would I need to get 70 inputs to an Arduino Uno?

None. Those chips are for output, not input.

I do understand how to use one 74HC595 though.

Evidently not, since you don't even know what they do.

My second easier question is -is there an development board with 70 or more inputs?

Yes, there are. None made by Arduino though, but there are plenty of other options. Myself I work with microcontrollers with hundreds of IO pins.
However, I think you need to re-think what you are trying to achieve. There are many options for reducing the number of inputs you need to use depending on what it is you are doing. Maybe if you told us a little more about what you want to do, not how you think you want to do it, we can help you a little more.

It sounds like youve got "fire in your belly" about the 74HC595 typo

@Rosemary he means no harm ;) It may be interpreted as so, but at the point of writing he didn't know it was a typo. He was pointing out it was unlikely that one knows how to use output IC's for input signals, nothing personal I believe.

Agreed, it's not personal. I'm snarky to all people equally ;)


text:
delete the memory or re-upload a program
At the moment I am following the instructions of this project https://github.com/JoernL/LimiTTer. Besides the peripheral parts like a Bluetooth module and an NFC module, the central unit is an Arduino Pro Mini.
I am a bloody novice with Arduino and just taught myself how to solder stuff. So far, I successfully uploaded the program from the project above to the Arduino Mini Pro and will continue as soon as the other parts arrive.
Anyhow, since I am strictly following the instructions I have some serious knowledge gaps and hope you can help me out. So, for instance.

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?
How can I delete a program from the Arduino board?
When I upload a program, will the program that is already on the Arduino been overwritten?
Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

The arduino work like the way you think it does regarding-when a new program is uploaded - it replaces or deletes the previous one when uploaded. This is because the arduino is a general stored program computer -though it doesnt hold a set of programs in memory just the last one that was uploaded last. You may need to clear the EEPROM with code though.

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.
In purple is how much bytes are available on your board.
In green is how many bytes does your global variables take.
In orange is how many bytes are left for local variables.
In blue is how many bytes are available for all of your variables.
In red is the general specs of your board and to which COM port it is connected to.

How can I delete a program from the Arduino board?

Once  a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Is there a counter library in Arduino?
I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

Use unsigned integers. If you need a specific size, use uint8_t, uint16_t, uint32_t or uint64_t. They are respectively 8, 16, 32 and 64 bits wide.

For reference, all integer types can be incremented and will overflow with predictable behavior.  What kind of weird overflow issues were you getting with ints?  What are you trying to do?

@mwwalk: What you say is absolutely wrong! Please, do not spread such nonsense over the Internet. Signed integer overflow is undefined behavior in C and C++. In some sense, it is considered “illegal”. Technically, it means the compiler will assume your signed integers do not overflow, and optimize your code on the basis of this premise, completely disregarding the possible consequences of the premise possibly being wrong. Then, any kind of weird behavior can happen if you overflow a signed integer. Unsigned integers, on the other hand, have predictable overflow behavior.

@mwwalk: Here is a good read about undefined behavior in C and C++, with some enlightening examples related to signed integer overflow (see part 2): A Guide to Undefined Behavior in C and C++.

Yeh, I take it back and I was obviously wrong.  But you could calm down a little, I obviously didn't mean to be wrong and I'm not trying to push some alternative overflow agenda.  I just made a mistake.  Literally every time I've ever had an integer overflow, it has done so in the predictable and expected manner.  Apparently I've just gotten lucky so far.

Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.
https://forum.arduino.cc/index.php?topic=85692.0
a library by Nick Gammon.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Wiring and Connecting WS2801 to NodeMCU ESP8266
After hours of searching for a solution and try many ways of wiring, I must asking here for Help:
I'm using a ESP8266 (ESP-12E) with a WS2801 - 4 Wire LED Strip and using this Pinout-Diagram to connect WS2801 wires to NodeMCU.
https://alexbloggt.com/wp-content/uploads/2015/10/nodemcu_pinout_700.png
Here is my Wiring:
LED     ESP
====   =====
5V --> Vin
GND --> GND
CK --> GPIO2 (D4)
SI --> GPIO3 (RX)

I have found this sample Program which should turn on and off all LEDs one after each other for 100ms. But it happens nothing after compiling and uploading it to NodeMCU board using Arduino IDE. Any help is highly appreciated.

//This program was taken from the FirstLight.ino supplies with the FastLED library
// It has been modified for use with a NodeMCU for use in a tutorial by NQMakerSupplies.com.au
// Hosted at theMakers.org.
//
// Special thanks to the people behind FastLED.io and all the contributors :)

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER   // map output pins to what they are called on the NodeMCU
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 10

// Data pin that led data will be written out over
#define DATA_PIN 3

// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define CLOCK_PIN 2

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
   delay(2000);
   FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

// This function runs over and over, and is where you do the magic to light
// your leds.
void loop() {
   // Move a single white led
   for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) {
      // Turn our current led on to white, then show the leds
      leds[whiteLed] = CRGB::White;
      // Show the leds (only one of which is set to white, from above)
      FastLED.show();
      // Wait a little bit
      delay(100);
      // Turn our current led back to black for the next loop around
      leds[whiteLed] = CRGB::Black;
   }
}

Are you sure the VIN pin is providing 5V? It looks like it's only for powering the board. If you have LoLin's V3 board, it has a USB power out pin marked as VU.

I have a Amica (V2) and pretty sure that Vin outputs 5V. Because once I connect the led strip to Board all leds turn white and remain. If I connect CK to CLK and SI to MOSI, I can see a fancy blinking christmas lights during the Upload. Is DATA_PIN 3 --> GPIO3 and CLOCK_PIN 2 --> GPIO2 correct?

Just to make sure, NodeMCU has a different/weird numbering compared to all other ESP modules for the GPIO pins, you are aware of this? Just google 'nodemcu pin' or so, plenty of images.

The second thing to consider is voltages, ESP8266 GPIO voltage is 3.3V, if WS2801 is powered from 5v, I'd guess that it also expects a 5v data signal, so you might need a level converter of some sort. Again google, people would have already documented this :)

Also, this might be usefull, a bit, mayby https://github.com/FastLED/FastLED/wiki/ESP8266-notes

Thank you for your suggestions @cranphin, but as I mentioned before, I have googled many hours before giving up and ask my question here. So providing tip how can I google my problem does not really help forward. What I need is a concrete tip for wiring the NodeMCU and know if my wiring is wrong.

Changing the first line from
 #define FASTLED_ESP8266_NODEMCU_PIN_ORDER

to
 #define FASTLED_ESP8266_RAW_PIN_ORDER

has solved the Problem.

Had the same problem, and this was the solution for me as well, thanks for posting!


text:
Unexpected Delay Between For Loops
I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:
int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < sizeof(leds); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

Please include the FULL code. Yes, including the setup even though it is not really relevant for you.

Alright, I edited it. Does that help?

The cause it that your 3rd led (2nd element in the array) is repeated twice.
Try this instead:
int leds[3] = {13, 12, 11};

void setup() {
  for (int i = 0; i < 3; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 2; i++) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
  for (int i = 2; i > 0; i--) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
}

Thank you! I thought that I wouldn't have to decrement the length of the array, guess I was wrong.

The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.
Apparently that sentence is supposed to mean that the long delay is due to i being one too large, coming out of the first loop and entering the second one.  Indeed, i is too large, but that's because each element of the array is a 2-byte int, so that instead of for (int i = 0; i < sizeof(leds); i ++) being equivalent to for (int i = 0; i < 3; i ++), it is equivalent to for (int i = 0; i < 6; i ++).
Thus, one second goes by with an extra 4 occurrences of delay(250); in the first loop, and another one second with 4 extra occurrences of delay(250); in the other loop.
To correct the problem, write sizeof leds/sizeof leds[0] instead of sizeof(leds), and write for (--i; i > 0; i--) instead of for (i; i > 0; i --).

The problem is on "for loops" condition,
Try this:
int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < (sizeof(leds)/sizeof(leds[0])); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < (sizeof(leds)/sizeof(leds[0]); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i=((sizeof(leds)/sizeof(leds[0])-1); i>=0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

This is not true. It depends on the persons intention.

Well my friend, the "intention" is to blink a LED. (1) You turn on a LED, (2) put it on hold by using delay, (3) You turn the LED off, (4) loops, the LED is turned on again. Well, if by "blinking" you mean its turn off for less than 10 clocks instruction, I accept.

You turn it off then change leds so there is a delay anyways.

ah you are right. Sorry my bad.

You mean sizeof(leds)/sizeof(leds[0]).

wow thanks, another mistake. forget about the byte size

Still wrong. Why don't you just const int LED_COUNT = 3;?

well, maybe its personal preference to prepare "ifs..", maybe reducing or increasing the number LED. May i know why it still wrong?

Because 1) you forgot to divide the first sizeof, 2) sizeof(int) is 2 on the Uno, not 8, 3) using an explicit integer instead of sizeof(leds[0]) makes the code non portable to, say, an Arduino Due.


text:
RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h
I use  RH_RF24.h to control Si4463, and realize some simple communication between two Si4463 . But I don't know the mean of RH_RF24_MAX_MESSAGE_LEN in this example.
RH_RF24_MAX_MESSAGE_LEN is a constant ? If so , what decides it ? And if I need to sent and receive  a long  char string , how to do it ?

RH_RF24_MAX_MESSAGE_LEN is probably defined in the header file RH_RF24.h.
It doesn't matter what size it is, you should always use RH_RF24_MAX_MESSAGE_LEN rather than the number because the value might change in the library and this will break your code if you have used the number.
If you want to send a message that is larger than RH_RF24_MAX_MESSAGE_LEN then you will need to 'fragment' the message (unless the library supports that).
I would use the first byte of the message as the type of message and define one of those types as a multi part string.  Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.


text:
Arduino Pro Mini automatically resetting
I have an Arduino Pro Mini 3.3v in a robot. The problem is, the Mini would automatically randomly overwrite the uploaded sketch with the default blink sketch... And this is becoming quite a problem.
I have connected the Arduino to a L293D Motor Driver and the Arduino gets its power from the motor driver only. It will work just fine, but randomly will reset to the blink sketch...
Please help
P.S- It automatically corrected after a while

I think you are seeing the bootloader, not the blink sketch.

@Gerben whatever it is... My sketch isn't running!

The most obvious cause for a reset is pulling to much current from the Arduino.  I have never heard of an Arduino downloading a new sketch to itself.  Is it possible you are seeing the board booting up and flashing the LED as its doing so?
If you are getting the power from the motor driver its possible you are either giving the board noisy/dirty power or the motor is pulling to much current and depriving the board of power.  I would run them on separate supplies (with a common ground) to avoid this.

I am providing ~18V (2 9v batteries connected in series) to the Motor driver. The motors can easily run on single 9v battery. I am clueless about what to do

Thats overvoltage, not over current. Connect the batteries in parrallel

The board may be resetting itself due to the overvoltage. Running the batteries in parallel should eliminate that as a suspected cause.


text:
Host name is unvalid
I am trying to call a web service from a server but didn't get the correct response on Serial Monitor arduino, i get the error "hostname is invalid". Below is the code along with the result:
Thanks @Edgar Bonet, i have tried as you suggested. Following is the correction and the result, now the error is "The request verb is invalid"
    {
EthernetClient client1;

//second
int inChar;
char outBuf[64];
char params[65];

Serial.print(F("Method 2 connecting..."));

if(client1.connect("198.38.93.76",807) == 1)
{
Serial.println(F("connected"));

// send the header
client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1"));
client1.println(F("Host: 198.38.93.76"));
client1.println(F("Content-Type: text/xml; charset=utf-8"));
client1.println(F("Content-Length: 315"));
client1.println(F("Connection: keep-alive"));
client1.println(F("SOAPAction: \"http://jbscrms.com/GetThresholdOfDeviceForSaud\""));
client1.println();

client1.println(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
client1.println(F("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
client1.println(F("<soap:Body>"));
client1.println(F("<GetThresholdOfDeviceForSaud xmlns=\"http://jbscrms.com\">"));
client1.println(F("<Device_id>2</Device_id>"));
client1.println(F("</GetThresholdOfDeviceForSaud>"));
client1.println(F("</soap:Body>"));
client1.println(F("</soap:Envelope>"));

Serial.println(F("Done Calling New Web Service"));

}
else
{
Serial.println(F("failed"));

}

int connectLoop = 0;

while(client1.connected())
{

if(client1.available())
{
inChar = client1.read();

Serial.write(inChar);
connectLoop = 0;
}

delay(1);
connectLoop++;
if(connectLoop > 30000)
{
Serial.println();
Serial.println(F("Timeout"));
client1.stop();
}
}

Serial.println();
Serial.println(F("disconnecting."));
client1.stop();
}

Following is the result on Serial monitor arduino
Ready
Entered<R_TempData>29</R_TempData>
<R_smokeData>226</R_TempData>
<R_humidityData>36</R_TempData>
Method 2 connecting...connected
Done Calling New Web Service
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/xml; charset=utf

-8
    Server: Microsoft-IIS/8.5
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Date: Fri, 11 Nov 2016 07:23:28 GMT

Content-Length: 0

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 11 Nov 2016 07:23:28 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

disconnecting.

Either print("Foo: bar\r\n"); or println("Foo: bar");. println adds the "\r\n" for you.

You need to remove the port (:807) from the Host entry. You can probably remove that entire line. PS. there should be only one space before    HTTP/1.1, not three.

Also, remove protocol, host and port from the POST line: client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1")); And your SOAPAction line is incomplete: the code as posted cannot compile. Please, post here the actual code you are using.

Your Content-Length header is wrong. You are not sending 1000 bytes of data.

I think you need a \r\n between the Post statement and the HTTP statement.
Why are you including the Port number in the Host name?
Your SOAPAction line is wrong, but I guess that's a typo in the post.

Thanks @Matt . You suggested the same as Edhar Bonet. I tried but didn't get a correct response. I have posted the error above.


text:
Read/write data from 2 Arduinos simultaneously with Python
So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.
If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like pin.write(1) to turn on or pin.write(0) to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.
The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.
At the moment I have custom code on My Arduino Mega and a StandardFirmata on the Arduino Uno, but I am open to other suggestions that could work.
Arduino Mega code:
/*
by Ben-Tommy Eriksen
https://github.com/BenTommyE/BenRotaryEncoder
*/

// Encoder connect to digital pin 2 and 3 on the Arduino.

int counter = 0;
//This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (4600);
  //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  Serial.println (counter);
}

void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
    counter--;
  } else {
    counter++;
  }
}

Python code:
import pyfirmata
import serial
import time

#Associate pyfirmata with python for my UNO board
port='COM5'
board= pyfirmata.Arduino(port)
#Use iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start()

#Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
outPin1 = 12 #passes the signal to the valve

s = serial.Serial('COM4',4600)
while time<60s #generalized:
    rotary = s.readline() #reads the counter of the rotary encoder form arduino

    #convert the rotary to an integer try/except is needed to work
    try:
        var = long(rotary)
        last_var = var
    except:
        var = last_var
        pass

    value1 = lickpin.read()

    # Here I move the cursor up and down depending on the rotation of the encoder
    # if the cursor moves above a certain value
    if y>-18:
        board.digital[12].write(1) #should open the valve

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

If you really like Python, simply consider using a RPI instead.

Add a bunch of print()s. Verify that you're even receiving the right value through the serial port.

I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).
Here is the pinout:
ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :
/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}

What relevance does this have to the actual problem of the question?

This sketch is the best I know to read KY-040 encoders, so I guess it is pretty relevant.

No, the poster had already solved that problem.  The question concerns a different problem.

OK, never mind. At least you know where to find a good solution to read KY-040 encoders if you need that in the future.


text:
Gui Scale on Linux HD display
I use Fedora 24/25 and now Ubuntu 17.04 Gnome on my Lenovo Yoga 900, which has an extremely high pixel density display. For these situations on Mac and Windows, I find a gui.scaling option in the Arduino settings. However, on Linux there is no such option, and entering it in ~/.arduino15/settings.txt does not have any effect.
The version I use is Arduino 1.6.4 (now 2.1.0.5) from the Fedora (Ubuntu) repos. Is the scaling gui option not implemented on linux? Or is there some fix for this?
On the physical display the following screenshot has an approximate width of 4cm -> the green buttons are not usable at all!

Maybe related to this issue.

Not really, as the user there asks for buttons to customize the UI. I am missing the buttons, which should already be there! Or similarly, I've tried modifying the uiscale via the preferences file, also with no result.


text:
Arduino creating delay function
I am trying to make my own delay function. Briefly mydelay function is calling toggled function every secs seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in x function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in x. The second time when it loops. It enters the mydelay function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.
Here is the code:
#include <Arduino.h>
int led = 7;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  x();
  Serial.println("Im ending main loop");
}

void x() {
  for (int i = 0; i <= 10; i++) {
    mydelay(led, 0, 1);
    mydelay(led, 1, 1);
  }
}

void mydelay(int pin, int hol, int secs) {
  int starttime = millis();
  while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
  toggled(pin, hol);
  Serial.println("Im ending mydelay");
}

void toggled(int pin, int hol) {
  digitalWrite(led, hol);
}

starttime should be unsigned long. 2) it is a bad idea to Serial.println() inside a tight loop: you will fill the output buffer and be slowed down by the prints.

You already asked this exact question on Stackoverflow.

As mentioned in the comments, your main problem is you declare starttime as an int. This is a signed value with a range of -32,768 to 32,767. You will quickly overflow - in about 32 seconds.
The solution is to use an unsigned long which has a range of 0 to 4,294,967,295.

Yeah,actually i asked the exactly the same question on stackoverflow.And got my answer.But anyways i appreciate the answer.

Btw,Isnt range of int on arduino 65536-1 ?

@MuhamedCicak That would be for unsigned int. Without specifying unsigned you get a signed int.

True... I forgot that,i am pretty new to C so yea.I am reading this K&R Book.I dont know if you know it.

You can try something along these lines:
void verboseDelay(unsigned long ms)
{
    unsigned long now = millis();
    Serial.print(F("delaying"));
    unsigned long start = now, lastPrintTime = now;
    do {
        now = millis();
        if (now - lastPrintTime >= 20) {
            Serial.write('.');
            lastPrintTime += 20;
        }
    } while (now - start < ms);
    Serial.println();
}

The trick is to used unsigned long for all the time-related variables,
and also to avoid printing too fast.


text:
I2C to UART bridge as breakout or in DIP package
For a project, I need to connect more than one device to an Arduino through a serial port with hardware flow control (RTS/CTS).
Sparkfun used to make breakout boards for the SC16IS750, but this product is discontinued and I can't find any place to order it. There are also plenty of ICs doing what I need, but I am not keen on soldering SMD components and I cannot find any products coming in e.g. an old fashioned DIP package.
Does someone know about an available breakout board or a DIP packages I2C to UART bridge? Since the device will be battery powered, I would prefer a dedicated low-power circuit instead of a programmed microcontroller as suggested by majenko.

How about an ATMega328P programmed to do what you want...?

@Majenko Why didn't I think about that. It would actually work, but since I need the bridge to be always on in a battery-powered device, the power consumption of the ATMega328P is at least disadvantageous. I would prefer a dedicated circuit. I'll edit my question and add the power requirement.

An ATTiny would reduce the power a little - so would employing sleep modes and wake on I2C or UART interrupts.

Yes, sleep modes should do it.  Note that hardware flow control is not incompatible with software serial in concept, though there might be a few details to work out.  There may also be dual-UART ATmegas available in large DIP packages.

You really should invest an hour or two in learning to solder SMD device though - it is not hard at all, and will remove these extreme limitations you face.

According to what I read, a 'wake on UART activity' concept won't work. After waking up, the ATMega will take some time to resume normal operation and at least the first byte of the UART transmission will be lost. Using such an approach requires control of the transmitter. which must first send a dummy 'wake up byte' on the UART, delay for a short period to wait for the ATMega to run properly and then start the real transmission. Since I cannot change the protocol used by the connected devices, this will not work.

Less expensive option?
Have no personal experience, but was Googling for a way to add second hardware UART to Arduino Uno. https://www.embeddedadventures.com/i2c_to_uart_mod-1025.html

Perhaps what you're looking for:
http://sandboxelectronics.com/?product=sc16is750-i2cspi-to-uart-bridge-module

From that page:

SC16IS750 I2C/SPI to UART Bridge Module
This module is designed to enable I2C/SPI to UART conversion. It works in I2C/SPI slave mode and interfaces with devices working in I2C/SPI master mode. There are also 4 extra GPIOs for IO expansion. NXP SC16IS750 is used as the key component on this module. Flow control and modem signals are also supported.
This module is useful when extra UART interface is needed. Due to the multi-slave characteristics of I2C and SPI, many UART interfaces could be added to the system at the same time.

@MichaelWilkinson Please consider posting a little summary, because your post will be worthless when the source you are linking to changes or is deleted.

Agreed - links go dead in time. Please summarise your answer so that it stands on its own. At least mention the part number, and maybe post a photo of it.


text:
How can I deal with rapid fluctuation of Anemometer readings?
In my little weather station I collect temperature, humidity, MQ-2 smoke sensor, and wind speed readings for display on a 20x4 LCD display, every 500 ms.
The Anemometer readings jump up and down by quite a bit.
Initialization of variables before Setup is like so:
// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

// 20 x 4  LCD Display
#include <LiquidCrystal_I2C.h>
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Then in Setup I initialize the LCD and flash the backlight.
lcd.begin(20,4);
lcd.clear();
for(int i = 0; i< 3; i++) {
  lcd.backlight();
  delay(250);
  lcd.noBacklight();
  delay(250);
  }
lcd.backlight(); // finish with backlight on

In Loop, I paint the initial screen then take readings and display them
void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Weather");

  ...etc... to display time and show temp and humidity

  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);
  lcd.setCursor(0,3);
  lcd.print(windSpeed);
  lcd.print(" MPH  ");

  ...etc... to display smoke detection...

  delay (500);
  }  // end loop

So the question is:  How can I slow down the Wind Speed fluctuations?  It jumps up and down quite widely.

A:  Use a running average
In the initialization I include an array to hold 10 values
// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

float ws[10] = { };      // (initializes all to zero)
int wsIndex = 0;
float wsTot = 0.0;
float wsDisplay = 0.0;

Then in the Loop I fill the array with values and display the average of the 10 readings stored there
  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

  if (wsIndex<9) {
    ws[wsIndex] = windSpeed;
    wsIndex++;
    }
  else {
    wsTot = 0.0;
    for (int i=0;i<=9;i++) wsTot = wsTot + ws[i];
    wsDisplay = wsTot / 10.0;
    lcd.setCursor(0,3);
    lcd.print(wsDisplay);
    lcd.print(" MPH  ");
    wsIndex = 0;
    ws[wsIndex] = windSpeed;
    }

Depending on the nature of the fluctuations, a median filter may be way more efficient than a running average. 2) An exponentially weighted running average is simpler and less resource intensive than the “flat” average you are doing.

Interesting comment.  Median is interesting but takes more code.  In your #2 part I am not sure how you would decide to weight it.  And again, it would take more code.  I like how my averaging algorithm is implemented in two lines of code.  It is easy to read.  My favorite code is of the self-documenting type.

Median is indeed more complex, but it's worth the trouble if you have “spiky” noise. It is no better than averaging if your noise is white and Gaussian. The exponentially weighted running average takes less code and less memory: output += constant * (input - output). It's the standard low-pass filter for when you want simplicity and efficiency. You choose the constant as a function of how much smoothing you want. constant = 1.0/N; is roughly equivalent to an N point running average.

Ah.  Thank you for explaining that.  I see your point.  I will remember this.  My original readouts were wildly variable and I would say they are white and Gaussian.        btw, I have doubled the length of my array to 20 and it is very nice to see a good stable readout with much less variability.

How about this one, it supposed to press fluctuations of your sensors reading
void loop(){
..
...
....
last_reading = sensorValue2; //

sensorValue = analogRead(sensorPin);
sensorVoltage = sensorValue * voltageConversionConstant;
if (sensorVoltage <= voltageMin) windSpeed = 0;
else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

sensorValue2 = (sensorValue+last_reading)/2;
....
...
..
}

That certainly is less code - very readable.  It would be like my solution but as if I had an array of 2 entries.  If this works for you, then that's great.

you can also combine it with averaging method, but it will lessen the sensitivity. Not advised if used in quickly changing environment


text:
Why is my radio circuit working with other arduinos but not the Pro Minis?
I have some Arduino Pro Minis. I have both the 3.3V/8MHz and 5V/16MHz versions. I'm trying to get them to work with the nRF24L01 RF modules.
I've lightly modified some example code from the RF24 library, and gotten it working with an Arduino Micro and Nano. Basically, I just send an increasing integer from one to the other, and the receiving one displays on an LCD the latest number it received, which lets me know if a transmitter is working.
So that all works. Now I'm trying to use a Pro Mini (tried both 3.3V and 5V versions) to transmit instead of the Nano I was using before. The regulator is a 3.3V LDO. The battery is supplying that LDO and the RAW pin of the Pro Mini with ~8.5V, which should be good. Measuring the voltage out of the LDO gives 3.3V.
I looked at the pinout of the Pro Mini, and I believe I've hooked up the module to the correct MOSI/MISO/SCK pins, as well as pins 7 and 8 for the module's CE and CSN pins.
Buuut... it's not working. Nothing is appearing on the LCD. I know the nRF and its header thing work fine, because I can pop the exact one into the circuit with the Nano that works.
Even more strangely, I'm pretty sure the Pro Minis are getting programmed successfully. I can upload the Blink example to them, and that works. I'm using an Adafruit FTDI friend to upload, and that appears to be working (compiles, uploads, etc without error).
Here's the code I'm using for the transmitter, it's pretty simple. Does anyone have any suggestions? Thanks in advance. Let me know if there's anything I forgot to include.
edit: It won't let me include more than two links because of my low rep, so I can't include images of my ciruit/wiring. But I'll manually write it out here:
The numbering here is with respect to the pins in the nRF link above.
nRF module pin           Arduino Pro Mini Pin
1 (GND)           GND rail (not on Arduino)
2 (VCC)           3.3V rail (from external regulator)
3 (CE)           Digital pin 7
4 (CSN)           Digital pin 8
5 (SCK)           Digital pin 13
6 (MOSI)           Digital pin 11
7 (MISO)           Digital pin 12
8 (IRQ)           Not connected to anything

Can you also show us the wiring diagram / schematic?

@josecanuc ahh I originally included it in my OP but it didn't let me include more than two links... I'm following the stuff in the 1st link, but I'll edit it explicitly in my OP, thank you.

@josecanuc I've edited it, let me try including an image here though, of my wiring: http://i.imgur.com/c7TF64M.jpg


text:
Arduino Pro Mini Serial Monitor garbage
This is my first post. I hope that I am posting in the right section of the forum. Otherwise, could an admin move this topic to the appropriate section please?
Board : Arduino Pro Mini 3.3V 8MHz
Arduino IDE : 1.6.12
Arduino is powered by a FTDI Board and USB Mini-B cable from the computer USB port in the following order :
Arduino        FTDI
BLK              GND
GND             CTS
VCC             VCC
RXi              TX
TXo             RX
DTR             DTR
Also, I have connected a HC-06 bluetooth module in the following order :
Arduino    HC-06
GND         GND
VCC         VCC
D10         TXD
D11         RXD
The Serial Monitor is open on COM4, Newline, 9600 baud.
The code that I'm trying to run is :
#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11);
void setup()
{
  pinMode(13, OUTPUT);
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from BTSerial");

  Serial.begin(9600);
  Serial.println("Hello from Serial");
}

char a; // stores incoming character from other device
void loop()
{

  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    Serial.println(a);
  }
}

I am trying to communicate with the HC-06 from an Android phone.
I am posting in this section of the forum because when I send a message from the phone to Arduino the following is printed in the Serial Monitor :
à„…€ƒ¦¤„„‡…§¤¦„‡Å„EóAãbBãbHãb

When I am trying to send a message from Arduino to the phone, nothing is received on the phone.
Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window?
Is there a problem with the Arduino IDE?
Edit 12.11.2016
This is what I get when I open the Serial Monitor in the Arduino IDE with this code :
Newline, Baud rate 9600
‚Æ‡¥Ç$¤†Fó

If I change the Serial Monitor properties to Newline, Baud rate 19200 this is what I receive :
Hello from Serial

On the Android phone application I do not get anything printed.
Also, please note that this question is also addressed on the Arduino forum at the following link :
http://forum.arduino.cc/index.php?topic=434623.0
I will try and answer in both places as I am not sure that everybody has an account on the forum

Is there any possibility that your HC-06 have not configured to run at 9600  baud?

Was about to say the same thing as @dpw, there's a huge chance the HC-06 runs at a different baud rate. A simple Google search shows that 38400 is a common (or even default) baud rate of the HC-05 and HC-06. This definitely would explain the gibberish you're receiving.

Changed this through TeraTerm. I got the confirmation message that the Baud rate was changed. Still, no change.

I had the same issue. The problem was solved in an other forum:
https://forum.arduino.cc/index.php?topic=434623.0
I copy the solution here:
It appears that in fact your board is not running at 8MHz, but instead 16MHz.
Please select the correct setting for your board:
Tools > Processor > ATmega328(5V, 16MHz)
Or if it has the ATmega168:
Tools > Processor > ATmega168(5V, 16MHz)

that helped me a lot.

Flip the RX and TX wires of the HC06. This is because this statement : SoftwareSerial BT(10, 11); actually means SoftwareSerial BT(RXpin, TXpin);. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.

I think I typed wrong in the main question because this is how I have them connected. Sorry for misleading you.

BLK GND
GND CTS

That looks backwards to me. Connect GND to GND and CTS to BLK.
The bluetooth module operates at a predefined baud rate. You need to ensure that your Arduino communicates at that baud rate - you don't get to pick any old baud rate.
The baud rate can be changed with the AT+UART=x command (where x is a single digit representing the baud rate: 1=1200, 2=2400, 3=4800, 4=9600 (default), 5=19200, 6=38400, 7=57600, 8=115200, 9=230400, A=460800, B=921600, C=1382400).  If the HC-06 isn't on the default baud rate of 9600 (which is highly possible) then you will have to guess what the right baud rate is. Work through the possible ones listed there in yopur BT.begin(...) function to see if one of them starts working.

He's actually right. It isn't backwards.

Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window? Is there a problem with the Arduino IDE?

Even if the baud of serial monitor and the code is same, there is a possibility that you have not configured your HC-06 to works on the same baud.
There are many ways to check and configure it by using AT-Command. You will easily found them since many tutorial has been written, here is some of the example :
link 1
link 2

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How fast can I read Arduino port D?
I'm trying to see how fast I can read an Arduino IO port.  It's being toggled with an random speed /white square wave and I want to see which is faster, the Arduino or the signal.  The pin on port D is driven by an open collector comparator (LM311).
So I have this code

buffer[0] = PORTD;
buffer[1] = PORTD;
buffer[2] = PORTD;
buffer[3] = PORTD;
buff...
...fer[28] = PORTD;
buffer[29] = PORTD;

that I can read the port in burst mode.  This code is as fast as I can write I think.  I've unrolled a possible loop here.  buffer[] is a local variable as that seems faster.  I'm not an assembly expert so I can't really browse the assembly instructions.
I've added a 500 Ohm pullup resistor to the input pin that I'm interested in.  A lower value seems to give more randomly distributed values that a 10k resistor.
I tried timing buffer[0] ... buffer[29] readings and that returns 4 microseconds with interrupts off.  I hope that micros() doesn't need interrupts to function!  That would equate to 7.5 million readings /sec.  That's about 2 clock cycles per instruction on my 16 MHz board.  Can this be right?
How fast can this code run?

How did you time your unrolled code?

Turned interrupts off, recorded micros() before reading port 30 times, then print micros() - micros before.  Does that work?

I don't trust software, I always use a scope and a GPIO to get actual timing.

Your timing seems reasonable.
At a rough guess, without actually compiling it, your code will turn into something along the lines of:
IN R24,PORTD  ;First read   - temp = PORTD     - 1 cycle
ST X+, R24    ;First store  - buffer[0] = temp - 2 cycle
IN R24,PORTD  ;Second read  - temp = PORTD     - 1 cycle
ST X+, R24    ;Second store - buffer[1] = temp - 2 cycle
...

This is indeed the fastest way of reading the port if you want to keep the data. Basically it will do an IO read from PORTD using the IN instruction which takes 1 clock cycle. Then it will perform a store to SRAM using the STS instruction which takes another 2 clock cycles. The store instruction can also post increment the pointer it is using (stored in the R28/R29 X-register pair in my example) for free which saves you time.
So basically that should do 3 clock cycles for every read - one to do the read, and one to do the store, or >5 million reads per second from a 16MHz clock.

There will additionally be a couple of cycles at the beginning to set X-register to point to the buffer. If the buffer is a constant pointer - i.e. the buffer has a fixed address, it will only take two instruction cycles at the beginning to load the address. If it is a non-constant address, it will take up to four as it has to load the address from the SRAM.

I'm surprised that a succession of buffer[const] = ... assembles to ST X+, I would have expected I'd need to use buffer[var++] = ... . I just ask as I'm going to want to do similar 'fast' things myself shortly

@Neil_UK GCC is quite clever when it wants to be. It will work out that each of the writes corresponds to a series of incrementing addresses and convert it into ST X+ instructions. If you leave a gap, say miss buffer[10], it will probably keep the same optimisation but add an additional ADIW X,1 in the gap rather than recalculating the address.

Yeh, I too was wondering about the array indexing.  I thought that it might take more processing.  One odd thing is that the readings change with the value of the pull up resistor.  With a higher value you get more "0" in the results for the same signal.  Probably one of those inductance things which  probably becomes apparent when reading at 8 MHz.  This is probably getting a bit fast for the general plug it in and hope Arduino style of design.  500 Ohms gives an evenish number of 1s and 0s.

st X+, r24 takes two cycles, so that's 3 cycles for every read.

@EdgarBonet so it is. Only 1 cycle on ATTiny devices though :). I was using this but they have since updated it with a few corrections.

According to the instruction set manual, it's 2 cycles, except on XMEGA and on “reduced core” ATtinies. My understanding is that “reduced core” refers to the AVR core that lacks registers r0 through r15, i.e. the last line in this table. Most ATtinies, including the ones Arduino programmers are most likely to come across (e.g. ATtiny 85), are not “reduced core”.

I just tried compiling your code with avr-gcc 4.9.2:
buffer[0]  = PORTD;
buffer[1]  = PORTD;
...
buffer[29] = PORTD;

Here is what I got:
in  r24,    0x0b  ; temp = PORTD     – 1 cycle
sts 0x0110, r24   ; buffer[0] = temp – 2 cycles
in  r24,    0x0b  ; temp = PORTD     – 1 cycle
sts 0x0111, r24   ; buffer[1] = temp – 2 cycles
...

That's 3 cycles per read, i.e. a 5.33 Mhz reading frequency. For
some reason the compiler didn't want to use the st X+, r24
instruction suggested in Tom Carpenter's answer. Let's try to hint the
compiler a little bit, and rewrite the C code as follows:
uint8_t * p = buffer;
*p++ = PORTD;
*p++ = PORTD;
...

This generated the exact same assembly! The compiler somehow figured out
the address of each memory write, and it replaced each occurrence of the
pointer p by an explicit address. To prevent this kind of
“optimization”, let's make the pointer a variable whose value is unknown
at compile time:
void fill_buffer(uint8_t *p)
{
    *p++ = PORTD;
    *p++ = PORTD;
    ...
    *p++ = PORTD;
}

Here is the generated assembly:
movw r30,  r24   ; Z = p (Z is the register pair r31:r30)
in   r24,  0x0b  ; temp = PORTD   – 1 cycle
st   Z,    r24   ; *Z = temp      – 2 cycles
in   r24,  0x0b  ; temp = PORTD   – 1 cycle
std  Z+1,  r24   ; *(Z+1) = temp  – 2 cycles
...
in   r24,  0x0b  ; temp = PORTD   – 1 cycle
std  Z+29, r24   ; *(Z+29) = temp – 2 cycles
ret              ; return

Still 3 cycles per read. Here the compiler is using the std
(store with displacement) instruction rather than st X+ (store with
post-increment).
In the end, what instruction the compiler chooses doesn't really matter.
All memory access instructions takes two cycles. Then, no matter what
you do, repeatedly transferring data from a port to RAM will take
3 cycles per transfer, irrespective of the instruction you choose
for the memory write.
Now, this doesn't mean you can't read faster. The AVR CPU core has
32 general purpose registers. Since you are only performing
30 port reads per burst, this means you can use the register file
as an ultra-fast temporary buffer. This seems easier to do in assembly,
and it will cost you a significant overhead in saving registers to the
stack and restoring them afterwards. But the read burst itself will be
faster:
; declare as:
;   extern "C" void fill_buffer(uint8_t *p);
.global fill_buffer
fill_buffer:

    ; Prologue: save registers and move the pointer.
    push r2         ; save all the registers belonging to the caller:
    push r3         ;  - 18 register to save (r2 – r17, r28, r29)
    ...
    push r28        ;  - 2 cycles per register
    movw r30, r24   ; Z = p (Z = r31:r30 is a pointer register)

    ; Now we can read the port really fast.
    in   r0,  0x0b  ; temp_0  = PORTD – 1 cycle
    in   r1,  0x0b  ; temp_1  = PORTD – 1 cycle
    ...
    in   r29, 0x0b  ; temp_29 = PORTD – 1 cycle

    ; Now save to RAM.
    st   Z+,  r0    ; *Z++ = temp_0   – 2 cycles
    st   Z+,  r1    ; *Z++ = temp_1   – 2 cycles
    ...
    st   Z+,  r29   ; *Z++ = temp_29  – 2 cycles

    ; Epilogue: restore the registers.
    pop  r28        ; restore all the previously saved registers:
    ...
    pop  r3         ;  - 18 registes to restore
    pop  r2         ;  - 2 cycles per register
    clr  r1         ; leave r1 cleared, as required by the ABI
    ret             ; return

Now we are reading the port at 16 MHz: one read per cycle!
It turns out that that we can convince the compiler to do exactly this.
I had to see to believe, but it works. Something essentially equivalent
to the above assembly can be generated from C++ like this:
// Quickly read the port into temporaries.
uint8_t temp_0  = PORTD;
uint8_t temp_1  = PORTD;
...
uint8_t temp_29 = PORTD;

// Now save to RAM.
buffer[0]  = temp_0;
buffer[1]  = temp_1;
...
buffer[29] = temp_29;

Out of curiosity what compiler optimisation flags were you using? Also when I tested it was with I believe avrgcc 4.6, so optimisation behaviour may have changed.

@TomCarpenter: I used -Os. And indeed, this may change between compiler versions.


text:
Arduino Unreliable Serial communication
After reading the following 2 articles:
https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
I have get rid of the complete String class from my main program and went back to using character arrays.
This seems to work reliably until some extent but once I start stress testing it, quickly turns out that it is not reliable at all!
Here is the complete code, you can load it into the mega and it will produce the same results (I have removed all other unnecessary parts from the code):
#define DEBUG

char Command_PC[64], Command_Xbee[64], Command[64];
int count=0;
bool Complete_PC=false;
bool Complete_Xbee=false;

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

} // END void setup

void comm() {

/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    count = 0;
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          break;
         }
      Command_PC[count] = character;
      count++;
    }
  }

/* COMM FROM Xbee */
if (Serial1.available()){
  #ifdef DEBUG
    Serial.println("Xbee: New command, collecting...");
  #endif
    count = 0;
    memset(Command_Xbee, 0, sizeof(Command_Xbee));
    while (Serial1.available()){
      char character = Serial1.read();
      if (character=='\n')
         {
          Complete_Xbee =true;
          break;
         }
      Command_Xbee[count] = character;
      count++;
    }
  }

   delay(500);

 if (Complete_Xbee || Complete_PC) {

  if(Complete_Xbee)
    strcpy(Command, Command_Xbee);
  else
    strcpy(Command, Command_PC);

  #ifdef DEBUG
    Serial.print("Command received: >");
    Serial.print(Command);
    Serial.println("<");
  #endif
           Complete_Xbee=false;
           Complete_PC=false;
 }

}

void loop()
{
    comm();

} // END void loop

The code is simple, all it is intended to do that whether there is a command coming from the PC (USB) or Xbee (attached to hardware uart) process it and do further things. As long as you typing in commands manually it goes reliably for a while but even then after 10-15 commands it might screws up. The automated testing with:
for ((;;)); do echo HELLOWORLD > /dev/ttyACM0; done
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORL<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLDELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...

Brings out the bug right away. Is there any problem with this code? Any ideas how to make this 100% reliable even if it takes slowing the main program down?
I have noticed that by adding: delay(500); it makes it more stable. If this is not there it will even fail on the first manually entered command like:
PC: New command, collecting...
PC: New command, collecting...
PC: New command, collecting...
Command received: >lloworld<

By adding a delay to my test script:
for ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done
It runs stable for a while but after 15 mins testing it start misbehaving again:
Command received: >HELLOWORLD<
PC: New command, collecting...
Command received: >HELLOWORLD<
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><

To me, your problem is because the program is reading the characters faster than they are sent by the computer. Then, some situations occur where all the characters of the buffer have been read (Serial.available() = 0) but the '\n' character has not been sent by the computer yet. The program will then exit the loop without setting the Complete_PC variable to true.
In that case, the program will write several times "PC: New command, collecting..." without writing any result (Complete_PC not set to true). It can also drop the first letters, as they were read during the previous loop and the Command_PC array and count were reset in between.
The delay(500) command improve the stability because it increase the chances that the whole line is received when the program is not reading it at the same time.
Try something like this:
while ((!Complete_PC)&&(count<60))
{
    int character = Serial.read();
    if (character=='\n')
    {
        Complete_PC =true;
    }
    else if (character!=-1)
    {
        Command_PC[count] = (char) character;
        count++;
    }
}

As @Edesign has mentioned your reception methodology is slightly flawed.  A better arrangement would be:
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

The count and complete flags are now static - that is, they retain their values between iterations of the loop. You only look at one character per iteration of the loop (you could enhance it by changing the first if to a while if you like, but this way plays better with handling multiple data sources), and add that to the string. Only when the \n is received do you flag it as complete. There is no clearing of the whole array, it's not needed - just ensure that you always add a \0 to the end of the string each time you add a character.
The current character position (Count_PC) is reset when you receive the \n so that it is ready to receive the next command - be sure that you process the command that same loop (which you do anyway).

I have tested this code and it comes up with about the same results. Running or ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done will produce ommand received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
empty commands after about 10 mins. If I then stop the stress test for a second then restart it then it is working again for a while.

Also with your code if my delay(500); is not present then it returns empty right away for the word hello instead of receiving at least a couple of characters like ello.

You will have to show how you have fed this code into your existing code - how you handle the command and reset things will also have a bearing on things. As well as when you are doing your debug printing...

http://pastebin.ca/3737758 the difference is I still kept my while loop, breaking not breaking at \n made no difference during the tests however I believe that if I don't have the break statement there it is more stable, because if the end of the line is reached and there would be some junk characters after it in the buffer those would be erased by the Serial.read() and would not end up in my final Command_PC of course.

@qlesk When testing this code, did you completely removed the whole if statement after /* COMM FROM PC */? Because those lines are supposed to deal with 1 letter at each loop, so it will never work if you keep resetting the array with the memset command for example.

@Edesign: http://pastebin.ca/3737759 It is the complete code, I take out the xbee part because it's just a copy cat and not relevant for my testing here. No I left the if there and it does work as it did so far. After a while it becomes unreliable, I will test it with another arduino pro micro at the afternoon.

@qlesk Your link shows the answer to my question is NO. You have to remove all the lines after "/* COMM FROM PC */", from line 21 to 41, and copy paste the code Majenko write in its answer. Changing the micro won't fix anything as the problems comes from the code. Alternatively, you can also try the code I posted in my answer and give a feedback...

@Edesign, @Majenko: thank you for your help, it turns out that the hardware DOES matter as well. It was partially a hardware issue. Regarding my initial code, you can get that code remove the delay(500); from it and load it into an Arduino Leonardo and it will pass my first initial stress test without any delays and it works stable even after an hour testing.
I believe that both the Mega and the Leonardo have USB2 connections:
Bus 001 Device 003: ID 2341:0042 Arduino SA Mega 2560 R3 (CDC ACM)
Bus 003 Device 013: ID 2341:8036 Arduino SA
Although this is was a Keyestudio MEGA, a cheap chinese counterfeit which would explain why did it have this issue. My initial code was not wrong but as you have pointed out it could have been improved, what I did.
Code1:
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

Code2:
/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          Count_PC = 0;
          //break;
         } else {
             if (Count_PC < 62) { // Don't overflow the array...!
                 Command_PC[Count_PC++] = character;
                 Command_PC[Count_PC] = 0;
             }
         }
  }
}

The difference between his code and my last code is that I do the while looping inside the function while his relies on the main loop cycles to complete the string.
Both are working but if the main program have a lot to do, his version will noticeably make the responses more sluggish. Which can be easily tested with:
 for ((;;)); do date > /dev/ttyACM0; done


text:
Capacitors in DC circuits
I have a question about capacitors in DC (digital) circuits. The picture below is an edited schematic of the Arduino Uno R3.
The DTR line is connected to the reset input of the Atmega328 by a 0.1uF capacitor.

The capacitor is needed to initiate a load to the atmega flash memory through the USB -> UART. Why is this the case, everything I have been taught says "Capacitors block DC and let AC through"
All I see is something that can let AC noise through to the Arduino reset? I know its needed, I tested it. But why its needed, how it fulfils that function I have no idea.
Please help

Possible duplicate of What is the cap for in Arduino reset circuit?

Yes, capacitors block DC. But when there's a change from 0->5V or vice-versa, that isn't DC any more. The capacitor is charged/de-charged/reverse-charged, so there is a small current flow for a short time.

@WesleyLee It is close to a duplicate. But that answer isn't so good and it doesn't cover Andy's problem with it, either. This circuit does deal with Andy's problem there. So an answer here would actually be useful, I think.

@jonk -- fair points, I'll retract the flag but leave the URL just in case.

The Atmel datasheet, page 305, Section 29.5 "System and Reset Characteristics" provides some useful information for the reset pulse. It says that the worst-case minimum pulse width is \$2.5\:\mu\textrm{s}\$. It then goes on to say that the ramp rate has to be contained between two boundaries; no faster than \$10\:\frac{\textrm{kV}}{\textrm{s}}\$, but also no slower than \$10\:\frac{\textrm{V}}{\textrm{s}}\$. So there are some restrictions that should be managed by any reset system.
There are some nice reset circuit ICs available which provide a manual reset input as well as a control line. I'd probably use one of those about a circuit I cared about. Okay. Actually, I'd make my own out of a PIC10LF320 in a SOT-23-6, which also includes a brown-out circuit of its own, which I'd probably also re-purpose, as well.
But let's look at this circuit. DTR is normally held HIGH (I believe) and is pulled LOW in order to initiate a reset. Assuming that the two MCUs are running on different power rails (or the same, doesn't matter), \$C_5\$ is charged up to the difference between the ATmega328's rail (via \$RN_1\$ and the DTR output line's HIGH value.) If there is no difference, the voltage will be nearly zero. But if the rails are different, then there will be a small voltage across \$C_5\$ that represents this difference.
When DTR is pulled LOW, that end of \$C_5\$ is also pulled down to that voltage (close to ground.) For the first moments, this also means that the other side of \$C_5\$ is similarly pulled downwards, too. If there was some voltage rail difference, then that's the voltage that appears at the reset pin of the ATmega328. Depending on the voltage differences between the MCUs and the reset pin requirements of the ATmega328, this could be a problem. The datasheet says that it may be required to be as low as \$600\:\textrm{mV}\$, though the typical only requires to be pulled down to \$1.3\:\textrm{V}\$. But if no difference in the rails, then hopefully near-ground appears at the reset pin of the ATmega328. I'm going to assume there is no difference, here, so that we at least have a good chance it works okay.
Now, as soon as \$C_5\$ is yanked down by DTR, \$C_5\$ begins charging up through \$RN_1\$, starting at a rate of about \$500\:\mu\textrm{A}\$. The time constant is \$1\:\textrm{ms}\$. So the voltage will rise rapidly. Assume that we only just barely achieved the required \$600\:\textrm{mV}\$ at the start (the capacitor held a slight charge.) Then we'd cross over the minimum rising threshold of \$1.1\:\textrm{V}\$ within about \$100\:\mu\textrm{s}\$. This is well more than long enough for the earlier mentioned minimum reset pulse width of \$2.5\:\mu\textrm{s}\$. So the spec is met here.
Now, let's go the other direction. Let's say that now DTR is held LOW for a long enough time that it charges up to about \$5\:\textrm{V}\$ through \$RN_1\$. Now, DTR is driven HIGH. What happens? Well, the other side of \$C_5\$ will now be at about \$10\:\textrm{V}\$ (the \$5\:\textrm{V}\$ charge on \$C_5\$ added to the DTR HIGH voltage value.) This is rapidly discharged, safely, via \$D_2\$. That's why \$D_2\$ was added. Otherwise, this voltage would be presented to the RESET pin of the ATmega328 and would have to be discharged via any internal protection diodes present there (which may themselves have additional specifications that must be met.)
What's interesting here is that the RESET pin in particular is called out in the datasheet on page 299. It says that it can support up to \$13\:\textrm{V}\$ worst case. So, technically, that might mean that \$D_2\$ isn't necessary to avoid driving protection diodes in the CPU. But it is still a good idea for an entirely different reason. This is to discharge \$C_5\$ rapidly (it would be very slow, via \$RN_1\$), so that it can be used for another reset very soon after being used.

Note on the reset pin:
As Majenko added in a comment, there is a high voltage programming mode for Atmel devices like this. I frankly don't fully apprehend it, as I haven't read a datasheet on the topic. But I did find out from an Atmel video that the PC6/RESET line, which normally acts like a /RESET line, can be changed into operating like a general purpose I/O port by changing the RSTDISBL fuse, which makes the general I/O function available. The bad thing about that is that the ISP programming mode NEEDS the /RESET line to do its job. So you can't program the device anymore, if you set up that fuse. This then forces you to use the parallel programming mode that is entered using the high voltage programming mode. I would guess that entering this mode uses the /RESET pin again, but this time places a high voltage on it that is detected in order to put the device into its parallel programming mode instead of the ISP programming mode.
I can't readily find a specific programming document on the details of using this mode to program their devices. Microchip publishes them. But it appears, cursory examination only, that Atmel does not. They document how to use the mode with their tools, such as the STK500 (which I have.) But not how to design your own tool. I'm guessing, for now, that this is a matter of non-disclosure for Atmel. And given that they have it available for so many different devices, I can see why they might want to avoid having to support it.
The details on this pin are starting to get complicated-sounding. But pins cost money and silicon is cheap. So Atmel, like other companies, try to come up with methods to use their scarce pins to provide as much versatility as they can to sell devices.
That's it.

The problem with allowing a +10V spike on the RESET pin is that a high voltage (say 10V) on RESET is used to initiate HVP mode (High Voltage Programming). The diode is not there so much to protect the pin as to prevent HVP mode ever being accidentally entered.

@Majenko Thanks. I was just quickly scanning the sheet and could have read further on. Yes, that's about the right voltage for what I recall with PIC programming on the old PIC16C parts "back in the late 1980's," so I might have guessed.

@Majenko Can you provide a page reference that discusses this programming mode for the PIN? Is this the RSTDISBL Fuse thing? I just can't find the exact programming specs in the datasheet. So I'm guessing it is elsewhere. Would appreciate a reference. I'll include it in my answer, if available.

Not off hand, though I can probably find one. I knew it as a hunch like you from PIC programming, and did a google image search for "ATMega328P High Voltage programming" which gave me images of the wiring and pinouts used for HVP, including, on some, the voltage of the RESET pin.

@Majenko Thanks. Got it. I think I now understand it. I just listened to an Atmel video. It helps.

The closest I can find is this: http://www.atmel.com/webdoc/stk500/stk500.highVoltageProgramming.html - It says For High-Voltage programming a 12V programming voltage is applied to the RESET pin of the Atmel AVR device.

@Majenko I've added some commentary. Thanks for the catch!!

The capacitor C5 and resistor RN1 are used to TEMPORARILY apply RESET to the microcontroller chip during power-up.  It assumes that C5 is discharged and will conduct the "AC" (change from 0V up to 5V) until it becomes fully charged and releases the reset line so that the microcontroller can start up properly.
You can use this online calculator to see the time-constant for any given resistor and capacitor:  http://www.referencedesigner.com/rfcal/cal_05.php
When the circuit is first powered up, C5 holds the microcontroller -RESET line LOW (the active state) until C5 charges up through RN1.  At that point RN1 holds the -RESET line HIGH which releases the microcontroller to start up in an orderly manner.
It is not clear exactly what is happening between the U3 DTR pin and the junction of C5/RN2.  There is a label that says "LED3 Yellow", but there is no symbol for a LED or any other component there.  But there is typically a way for an external device to apply a reset also, so that you can re-program the microcontroller, and that is likely what is happening there.

Could you discuss the diode D2 in the circuit and how it helps regarding the use of C5? I was hoping a full answer would include that detail here.

I believe D2 is provided to protect the reset input of the microcontroller from any possible reverse-polarity voltage.

If possible that would be good, I have always left the Diode out, and wondered its use.

Hmm. Assume DTR is held LOW for a while. What does RN1 do to C5 then? What then happens if DTR is yanked high?

So C5 drops low momentarily when RTS is pulled low. Following the time constant it is recharged by Vcc through RN1, giving the momentary reset needed to programme the Atmega flash. Sound right?

Probably, but that stray(?) label confuses things.

I'm pretty sure I know why D2 is present, though. Andy mentions the problem in the link that Wesley provided right away. It serves that purpose.

@DannyJ It's more complicated. The ATmega requires a guaranteed $2.5:\mu\textrm{s}$ pulse width and it also specifies a minimum and maximum voltage ramp time, as well (from $10:\tfrac{\textrm{mV}}{\textrm{ms}}$ to $10:\tfrac{\textrm{V}}{\textrm{ms}}$.) So there is much more to discuss.

10 v/ms I do not think would be good. I should take time read the DS more, but they keep me too busy and I get side tracked far to easily


text:
PWM multiplexing on Arduino nano

simulate this circuit – Schematic created using CircuitLab
Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do PWM multiplexing on Arduino Nano?
So far, here is what I have done:
const int R=9, G=10, B=11, M1=5, M2=6, M3=7;

//I use pin 5,6,7 as selector since they are on same PORT (PORTD)

void setup()
{
    pinMode (R,OUTPUT);
    pinMode (G,OUTPUT);
    pinMode (B,OUTPUT);

    pinMode (M1,OUTPUT);
    pinMode (M2,OUTPUT);
    pinMode (M3,OUTPUT);
}

void led(int r, int g, int b)
{
    analogWrite(R,255-r);
    analogWrite(G,255-g);
    analogWrite(B,255-b);
}

void loop()
{
    for(int i=0; i<256; i++)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

    for(int i=256; i>0; i--)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

}

But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?
EDIT
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one for-loop.
I am using __asm__("nop\n\t") as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)
Thanks in advance

I've copied and slightly modified your diagram, as below.  Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

simulate this circuit – Schematic created using CircuitLab
I'm supposing that unlike the original diagram, this one represents what you actually wired up.
A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur.  To see this, do some timing analysis on the code.
The code repeatedly executes sections of code like the following:
    led(0,i,0);
    __asm__("nop\n\t");     //one clock cycle delay
    PORTD = B01000000;      //select LED-2

The call to led() results in three calls to analogWrite().  As seen by perusing at garretlab the source code for analogWrite(), digitalWrite(), and pinMode(), each of those analogWrite() calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute.  Thus each of the two for loops takes less than 10 milliseconds to complete, causing the loop() routine to run more than 50 times per second.  Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.
To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the for loops.  For example, suppose you want to go up in one second and down in two.  As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add delayMicroseconds(3906-36) at the end of the first for loop, and delayMicroseconds(2*3906-36) at the end of the other, to achieve the specified rates.  (The -36 term accounts for time used by other code in each loop.  It's probably an overestimate and perhaps should be left out.)
However, the previous paragraph doesn't take multiplexing effects into account.  You may, of course, want a different PWM level for each of the nine different LED chips.  It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.
For more information about software PWM, see some articles that google turns up, including:
• Arduino PWM pin vs digital pin PWM simulation on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
• AnyPWM Revisited, a blog article by Nick Borko about PWMing 12 LEDs using software PWM
• PWMAllPins, an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM
Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations.  But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.

Thanks jwpat, I did not notice the mistake on diagram before. I edited my original question. "emulate PWM in software", sounds interesting, can you explain more?

@dpw, I added some links that help with the software PWM concept.


text:
State machinese for serial input
I am trying to control a servo using keyboard.
void loop() {
if (Serial.available() > 0) {
  x = Serial.parseInt();
  while(pos < 180){
  pos = x + pos;
  Serial.println(pos);
  myservo.write(pos);
  delay(100);
 }
  }
else if(Serial.available() > 0){
if(pos>=180){
  pos = 0;
  delay(500);
  myservo.write(0);

  }
  }
 }

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?

I don't understand why you use 2 Serial.available condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:
int pos = 0,x=0;
void loop()
{
  while (Serial.available() > 0) x = Serial.parseInt();

  pos+=x;
  if (pos>180) pos = 0;
  myservo.write(pos);
  Serial.println (pos);
  delay(100);
}

I should've been more clear. I want to rotate the servo from 0-180, and once the servo goes past 180 I want to reset it back to 0

Can you explain what is the serial input used for?

Getting input from the keyboard. I put in a value between 1-90 and It should rotate the servo that much. Once the servo rotates more than 180 degrees then it should reset to 0; I want to set it up so that immediately upon receiving input it rotates that much. Right now it waits until it resets to adjust the amount I rotate the servo

I think I got your objective. Answer updated

Thank you. I was complicating it with all the if statements and conditions. Your answer makes much more sense Thank


text:
Pause between switching motor direction
I'm new both to this forum and to Arduino. My robot is comprised of Arduino Uno with Arduino Motor Shield, 12V DC gear motor, and two limit switches. The robot supposed to move endlessly on rails between the two walls back-and-forth. I have it all wired up and am able to switch the directions of the motor's rotation by pushing the limit switches. However, I also want to have a pause between switching of directions:
... Robot moving forward ...
If front limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CCW
... Robot moving backwards ...
If rear limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CW
... Robot moving forward ...
Simple delay(2000) doesn't work as the limit switch remains pushed against the wall. I've been trying out millis() approach but the fact that limit switch remains pushed (HIGH) I can never produce a difference in time needed to trigger an action. I learned about State Machine but not sure if and how this could help my case?
Can anyone please help me in implementing a two second pause between the switching of the motor's direction?
Below is the code that momentarily switches the motor's direction when robot reaches the wall and limit switch is pushed.
int switchFront_State = 0;
int switchRear_State = 0;

const int ledYellow = 6;
const int ledGreen = 5;

const int switchFront = 4;
const int switchRear = 2;

const int motorDirection = 12;
const int motorBreak = 9;
const int motorPWM = 3;

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

  pinMode(switchFront, INPUT_PULLUP); // Front switch
  pinMode(switchRear, INPUT_PULLUP); // Rear switch

  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

  // Setup Channel A
  pinMode(motorDirection, OUTPUT); // Motor direction pin
  pinMode(motorBreak, OUTPUT); // Motor break pin
  pinMode(motorPWM, OUTPUT); // Motor PWM pin
}

void runMotorBackward(){ // Motor moving backward
  digitalWrite(motorDirection, LOW);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void motorStop(){ // Stop motor
  digitalWrite(motorBreak, HIGH);
  digitalWrite(motorPWM, 0);
}

void runMotorForward(){ // Motor moving forward
  digitalWrite(motorDirection, HIGH);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void loop(){
  switchFront_State = digitalRead (switchFront);
  switchRear_State = digitalRead (switchRear);

  if (switchFront_State == HIGH){ // If front switch is pressed
    digitalWrite(ledYellow, HIGH); // Yellow LED
    motorStop();
    runMotorBackward();
    } else {
    digitalWrite(ledYellow, LOW);
  }

  if (switchRear_State == HIGH){ // If rear switch is pressed
    digitalWrite(ledGreen, HIGH); // Green LED
    motorStop();
    runMotorForward();
  } else {
    digitalWrite(ledGreen, LOW);
  }
}

Have you considered using a full state machine rather than just sensing the states of the switches?

I don't get why delay(2000) does work?

Gerben, delay(2000) works but it requires limit switch to be in LOW position in order for motor to run again. Originally, I tried placing delay(2000) between motorStop() and runMotorForward() / runMotorBackward() which worked but not in the useful way for me. In other words, the delay would be fired if the limit switch is pushed (HIGH) but the motor wouldn't start running again till the limit switch is released again (LOW).

Ignacio Vazquez-Abrams, I'm not sure what do you mean by "full state machine?" As I suggested, I'm new to Arduino and programming in general.

I think the problem is because there is no delay time after your motor switch its direction, so the robot is stay on position where the switch is pressed. I don't know if this gonna work, but perhaps you can add delay after the direction changed.
But based on your code, I can't find a condition to run if no switch is pressed. For alternative, you can try this
int direction_state = 1; //state where robot moves forward

void loop(){

  /*notes that here I assume while robot moving forward,
   *the rear switch is impossible to pressed, so does while
   *robot moving backward, the front switch is impossible to
   *pressed.
   */

  while ((digitalRead (switchRear)==LOW) && (digitalRead (switchFront)==LOW))
  //no switch pressed, loop will break if any switch pressed
    {
      if (direction_state == 1) runMotorForward(); else
                                runMotorBackward();
    }

  //indicator which switch is pressed and start of 2s motor stops
  if (direction_state==1) digitalWrite(ledYellow,HIGH);
  else digitalWrite(ledGreen,HIGH);

  motorStop(); //stop the motor
  delay(2000);

  //indicator 2s motor stops finished
  if (direction_state==1) digitalWrite(ledYellow,LOW); //indicator front switch is pressed
  else digitalWrite(ledGreen,LOW);

  direction_state = -direction_state //toggle the state
  if (direction_state == 1) runMotorForward(); else
                            runMotorBackward();

  delay(2000);

}

Feel free to ask if it's not works

Well, your suggestion above is exactly what doesn't work, adding i.e. delay(2000); after runMotorForward() / runMotorBackward() is not firing at all. Originally, I tried placing delay(2000) between motorStop() and runMotorForward() / runMotorBackward() which worked but not in the useful way for me. In other words, the delay would be fired if the limit switch is pushed (HIGH) but the motor wouldn't start running again till the limit switch is released again (LOW). As I described above, this is not an option as robot will get stuck first time it reaches a wall. The 2nd code doesn't have pause?

dpw, if you look at my code you'll realize that pressing on either limit switch (by hand) will set the robot in motion. I power the robot, it's not moving, then i press say the front limit switch and robot immediately starts to move backwards, hits the rear wall, changes the direction, runs towards the front wall, hits the front wall, changes the direction... endlessly, or as long as it is powered. All I want is that the robot pauses for two seconds when it hits the wall instead of just "bouncing" off of it.

Hi Dragan, I've edited the answers. Perhaps you can try it

Hi dpw, thank you sooooo very much for the corrected code. I uploaded it and it works EXACTLY the way I want!!! BTW, would it be possible to make switchRear to only switch motor to run forward and similarly that switchFront only switches motor to run backward. As of now, the directions could be confused if a "wrong" switch is pressed by accident.

Sure it can, you can modify the "while" condition. Happy I can help, and good luck to your project

Hello friends, something went wrong with my robot after I changed the motor. All of a sudden, the above code dhimaspw provided stopped working correctly!? On power up, the robot starts to run fwd for 2sec, stops for 2sec, starts to run rew for 2sec, etc??? It used to run till it receives a signal from one of the two limit switches. The circuit is untouched, except the new motor, which I find so confusing.

It would be better if you post another question, and put details about your motor there.

You need to make your switch logic edge sensitive rather than state sensitive. (That's the digital electronics term for it.) That means that you need to react to the change from switch off to switch on, not to the switch being on. (Since you're using INPUT_PULLUP mode, a switch on = LOW.
So:
In your loop, don't use
switchFront_State = digitalRead (switchFront);

instead, use code like below to detect a switch press:
int newSwitchState = digitalRead (switchFront);
if (newSwitchState == LOW && newSwitchState  != switchFront_State) {
    switchFront_State = newSwitchState;
    //Code to handle the limit switch being pressed
} else if (newSwitchState == HIGH && newSwitchState  != switchFront_State) {
    switchFront_State = newSwitchState;
    //Code to handle switch changing to the off state
}

You'll probably also need to use millis() to add some debouncing to your switch. (Ignore switch changes unless 10-20 milliseconds has passed, to avoid the switch jittering on and off when it is initially pressed or released.)