body:
**Nick Gammon's** code worked fine for me. Here is an **oscilloscope picture** of the waveform I've got from **his code**:

[![Output of Arduino UNO pin 9, approximately 1 V peak-to-peak Amplitude with spikes][1]][1]

His code above (*from Nick Gammon, on Jan 25 '16 at 20:33*) worked excellent for me. I used his code on Arduino UNO and got about **7.9 MHz** of output frequency on an approximately **1 V amplitude** (peak-to-peak, with spikes making it go to about **2 V peak-to-peak amplitude**).

The image above was obtained with my 40 MHz Oscilloscope from *ICEL Manaus* (manufacturer) at pin 9 (I used the Arduino UNO), with a LED and a resistor as a load at pin 9:

 - a green LED of about 1.79 V voltage drop
 - and a 4.7 Ohms resistor with 5% tolerance

The oscilloscope probe (*Channel 2, with fall slope trigger detect*) is on the 4.7 Ohms resistor. It follows the connection order out of the pin 9 from Arduino UNO:
*PIN 9* > *green LED* > *4.7 Ohms resistor* >  *GROUND*.

The green LED keeps blinking at a normal luminescence, as compared when used at other output frequencies.

I used a external 5 V DC power supply, along with the USB connection on my PC.

If you have any questions just put them here. Thanks and thanks [Nick Gammon][2]

  [1]: https://i.stack.imgur.com/8NWfq.png
  [2]: https://arduino.stackexchange.com/users/10794/nick-gammon


sender: user

message:
Recommendations for limit switches for Arduino

I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my [turntable][1] makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.

Any suggestions on which limit switch I should get?

Thanks so much in advance!

  [1]: http://cdn.shopify.com/s/files/1/0220/4654/products/slider1_large.jpeg?v=1420208854

sender: assistant

body:
A $2 microswitch with a roller would be OK for a million revs or so.

[![enter image description here][1]][1]

You would put a little ramp on the diameter and use it to trigger the switch.

Non-contact magnetic or optical could be better for more cycles or faster operation.

  [1]: https://i.stack.imgur.com/okIHN.jpg


body:
Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.

But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable,

You can calculate no of turn, arcs etc.

For eg:

 1. A 400ppr would give you a resolution of 0.9 degree per pulse, and
 2. 600ppr would give you 0.6degree per pulse of accuracy.

Although you can go for even higher ppr encoders but you can get these at very low cost.

Pic from: https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1

Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution.
[![A 400ppr rotary encoder][1]][1]

  [1]: https://i.stack.imgur.com/7BnyH.jpg


message:
Problem with a digital potentiometer application

I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.

The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.

I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.

In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one https://arduino.stackexchange.com/questions/4952/digital-potentiometer-not-fading-led without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).

So... what am I doing wrong and how to fix it?

Thank you!

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/klwYJ.png

Many tutorials were used when making the code.
<pre>
#include <SPI.h>

int vcc = 2; // attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; // attach pin 4 to Echo
int gnd = 5; // attach pin 5 to GND

int shortest = 250;
int longest = 12000;

int CS = 10; // for digi pot

void setup() {

  SPI.begin ();
  pinMode (vcc,OUTPUT);
  pinMode (gnd,OUTPUT);
  pinMode (CS, OUTPUT); // for digi pot
  // initialize serial communication:
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(vcc, HIGH);
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echo,INPUT);
  duration = pulseIn(echo, HIGH);

  if (duration > 200 && duration < 220)
  // Limiting out an unwanted, randomly appearing distance measurement
  // made useless by later code though
    {
     Serial.print("Error ");
     Serial.print(duration);
     Serial.print("\n");

     return;
    }

   // Compressing the result of the distance measurement into the scale of 0 - 128
  if (duration < shortest) duration = shortest;
  if (duration > longest) duration = longest;
  duration = (1.0f-((float)(duration - shortest) / (float)(longest - shortest))) * 128;

  digitalWrite(CS, LOW);
  SPI.transfer(0); // 0x01 and 0x04 seem to "work" too. With 0x11 and 0x08 no voltage goes through
  SPI.transfer(duration); // sending a number from 0 to 128 to the digital potentiometer
  digitalWrite(CS, HIGH);

  Serial.print(duration); // printing the result of the measurement and calculations
  Serial.print("\n");

  delay(100);
}
</pre>

body:
Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power *rheostat*.

Instead you should be controlling the motor using PWM and a transistor ([here is a good tutorial](http://www.circuitstoday.com/pwm-generation-and-control-using-arduino)).

But to help you understand the digital potentiometer and so you can work with it better:

Step one is always to read [the datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/11195c.pdf).  That details the SPI communication protocol for you so you can know what numbers mean what.

In this case the protocol is made up of two bytes - a command byte and a data byte.

The command byte is made up like this:

[![enter image description here][1]][1]

As you can see it's in two parts - a command and a potentiometer selector.  So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0.  That would be `0b00010001` or 0x11 in hex.  So your transaction would look like:

    digitalWrite(CS, LOW);
    SPI.transfer(0x11);
    SPI.transfer(duration);
    digitalWrite(CS, HIGH);

Another important part of the datasheet is the electrical characteristics.  That is a table that tells you the minimum, typical and/or maximum values for different parameters.  One important one here is the *wiper current* which it states as being allowed between -1mA and +1mA.  That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it.  That is why it's not good for powering things like motors, no matter how small.

  [1]: https://i.stack.imgur.com/2gUGj.png


message:
Arduino Nano, ICSP header and 595 Shift register

I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.

    74HC595   |    A. Nano
    DS     <-----> MOSI (ICSP)
    SH_CP  <-----> SCK (ICSP)
    ST_CP  <-----> D6
    MR     <-----> 5V (ICSP)
    OE     <-----> GND (ICSP)
    VDD    <-----> 5V (ICSP)
    GND    <-----> GND (ICSP)

My code:

    //pin connected to STCP
    const int latchPin = 6;
    //pin connected to SHCP
    const int clockPin = 17;
    //pin connected to DS (MOSI)
    const int dataPin = 11;

    byte val=0;

    void setup() {
      // put your setup code here, to run once:
      //SPI pins are output
      pinMode(latchPin,OUTPUT);
      pinMode(clockPin,OUTPUT);
      pinMode(dataPin,OUTPUT);

      pinMode(3,OUTPUT);
      updateRegister(0);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(3,HIGH);
      for (int i=0; i<8; i++) {
        updateRegister();
        delay(500);
      }

    }

    void updateRegister() {
      //pull latch low to write new bits to the register
      digitalWrite(latchPin,LOW);
      //shift out the data
      shiftOut(dataPin,clockPin,LSBFIRST,val);
      //pull latch pin high so that the leds light up
      digitalWrite(latchPin,HIGH);
    }

body: Do you need to add the _  to the shiftOut(dataPin,clockPin,LSBFIRST,val); ?


body:
<!-- language-all: lang-C++ -->

It is extremely confusing to have a variable `val` and then use `_val` in your function but then:

      shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.

Also this is just going to give you a boolean:

     updateRegister(!i);

Why take "not i" there?

---

I suggest you use SPI and not muck around with shiftOut. I have a [page about the 595 chip](http://www.gammon.com.au/forum/?id=11518) including example code. eg.

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    byte c;
    void loop ()
    {
      c++;
      digitalWrite (LATCH, LOW);
      SPI.transfer (c);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop


body:
`const int clockPin = 17;`

I'm pretty sure that should be 13, not 17.


message:
Analog Pins are sensing Values

I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

body:
This is normal, as the unconnected pin may float from GND to VCC. You may  enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.

For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.


body:
The ADC is multiplexed across the pins, and will carry a small charge from pin to pin.  If you want them to be zero, tie them to ground.

This answer, https://arduino.stackexchange.com/a/575/6628 , suggests pulling them to ground for higher accuracy.


message:
Converting data between baud rates

This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:

Here goes..

Let's say a device sends three characters [ABC] via serial at 9600 8N1.

And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.

The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.

Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?

body:
I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.

However, there is one magic character in UART communication: `U`

What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:

    ____start_____     _____     _____     _____     _____
        |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
        -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.

This effect is cleverly used for a system called [Automatic baud rate detection](https://en.wikipedia.org/wiki/Automatic_baud_rate_detection) whereby a receiver waits for a `U` character to determine the baud rate to use.  Most modern microcontrollers have this facility available.

If you can't get the frequency of a block of `U` characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.

If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.

Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.


body:
My logic analyser has a "guess baud rate" feature, which usually is fairly accurate. If you analyse an incoming bit stream you can probably have a reasonably good guess. For example the shortest transition means the baud rate cannot be **slower** than that. For example, at 9600 baud sooner or later you will get a transition in 104 µs (ie. `1/9600`). Thus if you see that, the baud rate could not be 4800 baud.

Also, in general, there will be a gap between "packets", so in your case after the "ABC" there would be a longer gap (of all 1s). You would assume then that the active time represents an integral number of bytes (eg. 3 bytes, 8 bytes, but not 1.5 bytes).

Another thing is that baud rates are usually multiples of a power of 2 times 300 (ie. 300, 600, 1200, 2400, 4800). So this gives you a small range of possible baud rates to test. You could test (say for 9600) and see if you get reasonable results. A "reasonable result" would be a stop bit appearing 10 bits after a start bit.

See my post: https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino


body:
Try measuring pulse width and match shortest pulse against pre-defined widths corresponding to available baudrates. This way you can detect baudrate by analysing random binary stream.

Signal glitches, such as very short spikes, will be filtered out, as they will never match the list of baudrates.

Repeat the measurement few times to raise accuracy and choose the most probable value from all guessed values.


body:
In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.

For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.


message:
Arduino uno not writing to file

I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.

    void handle_ajax() {
     int startUrlIndex = HTTP_req.indexOf("button");
     int endUrlIndex = HTTP_req.indexOf(" HTTP");
     String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
     int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
     int endButtonIndex = url.indexOf("&");
     String button = url.substring(startButtonIndex, endButtonIndex);
     int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
     String state = url.substring(startStateIndex);
     int device = button.toInt();
     int newState = state.toInt();
     dim_light(device, newState * 12);
     write_config("", "text");
    }

    bool write_config(String line, String text) {
     configFile = SD.open("config.ini", FILE_WRITE);

     if (configFile) {
      configFile.write("Dipshit");
     }

     configFile.close();
     Serial.println("Works.");
     return true;
    }

body: You have run out of RAM. Consider moving string literals into flash with thr `F()` macro.


message:
ESP8266, Arduino IDE vs Lua?

I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.

Do you need a custom firmware to use the Arduino IDE instead of Lua?

The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

body:
Using the Arduino IDE *is* custom firmware. That's what you're writing. You don't *need* any new firmware because the new firmware is what you are writing.

I can't think of any downsides to using C++ to program the ESP8266 instead of Lua - in fact it can only be a benefit since you are not using an interpreted language which is going to be slower than natively compiled code.


body:
Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.

In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably _not_ worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?


body:
I STRONGLY RECOMMEND TO STAY WITH THE ARDUINO IDE!

Despite programming in C++ not being as friendly and versatile as Lua (working with Esplorer is really a dream come true!), Lua is VERY UNSTABLE AND UNPREDICTABLE!!!

You can run a simple program of ten lines and it works ok for a day... two... and suddenly, on the 3rd day the chip hangs unexpectedly, and with no reason!
If you are lucky, the chip will reboot and program will start running again... that WAS NOT the case with me. I had to reload the program again! After 3 cycles like this, I decided to abandon Lua... FOREVER.


body:
Sorry for bumping, but this thread helped me to decide for Arduino IDE.

I started with Arduino IDE but couldn't get it to work with ESP-07.
Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.

Now with Arduino IDE things start to work the way they should! :)


message:
Unable to connect Ethernet shield W5100 to localhost

I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.

In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".

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

    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
    IPAddress ip(192,168,0,4);
    byte server[]={192,168,0,1};

    int value=9;
    EthernetClient client;

    void setup() {
      // Serial.begin starts the serial connection between computer and Arduino
      Serial.begin(9600);
      // start the Ethernet connection
      Ethernet.begin(mac,ip);
    }

    void loop() {
      // Connect to the server (your computer or web page)
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");
        client.print("GET /Ethernet/getData.php?"); // This
        client.print("value="); // This
        client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.println(" HTTP/1.1"); // Part of the GET request
        client.println("Host: 192.168.0.1");
        client.println("Connection: close");
        client.println(); // Empty line
        client.println(); // Empty line
        client.stop();    // Closing connection to server
      }

      else {
        // If Arduino can't connect to the server (your computer or web page)
        Serial.println("--> connection failed\n");
      }
      delay(10000);
    }

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

[![Serial monitor output][1]][1]

My Ethernet connection detail screenshot is as follows:

[![Ethernet connection details][2]][2]

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?

Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

  [1]: https://i.stack.imgur.com/qXM0T.png
  [2]: https://i.stack.imgur.com/DXR0n.png

body:
After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.

Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.


body: Well, the problem has been solved. The Ethernet shield was not properly stacked onto the Arduino board which caused connection to fail.


message:
Both red and blue led of ESP8266 stays on

I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used `AT+IPR=9600` command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:

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

 wdt reset
 load 0x40100000, len 1396, room 16
 tail 4
 chksum 0x89
 load 0x3ffe8000, len 776, room 4
 tail 4
 chksum 0xe8
 load 0x3ffe8308, len 540, room 4
 tail 8
 chksum 0xc0
 csum 0xc0

 2nd boot version : 1.4(b1)
 SPI Speed      : 40MHz
 SPI Mode       : DIO
 SPI Flash Size & Map: 8Mbit(512KB+512KB)
 jump to run user1 @ 1000

Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.

Any help would be appreciated.

body:
If you have too, you can find the firmware for the ESP8266 [here][1] and re-flash it.

There's some good info [here][2] about the instruction set.

With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.

What happens with only 3.3V and GND connected to the ESP8266?

Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?

  [1]: https://github.com/espressif/esp8266_at/tree/master/bin
  [2]: http://bbs.espressif.com/download/file.php?id=84


message:
Arduino can't multiply?

I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500*1000+2500*2000+2500*3000 etc), the Arduino comes out with very weird answers. For example

2500*1000=9632

If I just compute 2500*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

body:
2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:

    2500L * 1000L == 2500000L

Floats work also, but are more expensive:

    2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


message:
Branching Bus for Sensor

I am looking to setup a system where I have a master Arduino polling a number of sensors.

The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)

Questions

1. How long can the lines be?
2. Can the lines branch?

body:
How many sensors and what kind are they?
What Arduino do you have?

Basically you could use 1 Arduino Output per sensor if you have enough, or you are going to need to use a multiplex technique via additional electronic components.

The only other solution would be to use communication (I2C/Serial/etc) to receiving nodes at the sensor.


body:
I have a page about [connecting Arduinos using RS485](http://www.gammon.com.au/forum/?id=11428). You can connect multiple devices up like this:

[![RS485 setup][1]][1]

That has a reasonable range, 20 metres or more.

---

On that page I describe a *Rolling-master system* where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.

This screenshot shows the various devices "talking" during their timeslot:

[![Rolling master demo][2]][2]

In that particular case there were 3 devices active out of 4 configured.

---

> I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.

  [1]: https://i.stack.imgur.com/auNfc.png
  [2]: https://i.stack.imgur.com/XB5aq.png


message:
What is the relation between Arduino's clock and possible VGA resolution?

I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.

What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

body:
<!-- language-all: lang-C++ -->

I doubt if that would be fast enough. See [my thread about connecting to a VGA monitor](http://www.gammon.com.au/forum/?id=11608).

Borrowing from that page, so as to not make a link-only answer ...

---

For 640x480 pixels of active video you have something like this:

[![Video timing diagram][1]][1]

---

## Vertical Sync

Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

*    The screen refresh rate (eg. 60 Hz)
*    The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

[![Refresh rate][2]][2]

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.

The other figure of interest is the screen resolution.

In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.

Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

---

## Generating vertical sync pulses

This code in my VGA output sketch generates the vertical sync pulses:

      // Timer 1 - vertical sync pulses
      pinMode (vSyncPin, OUTPUT);
      Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
      OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
      OCR1B = 0;    // 64 / 64 uS = 1 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.

Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).

Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:

    ISR (TIMER1_OVF_vect)
      {
      vLine = 0;
      messageLine = 0;
      backPorchLinesToGo = verticalBackPorchLines;
      } // end of TIMER1_OVF_vect

---

## Horizontal sync

Horizontal sync pulses tell the monitor when to start drawing each line.

To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).

In other words:

     (1/60) / 525 * 1e6 = 31.74 µs

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).

Thus that is:

    ((1/60) / 525 * 1e9) / 800 = 39.68  ns
    1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.

The horizontal sync pulse width is 96 pixels, so we want a pulse of:

    96 * 39.68 ns = 3.8 µs

---

## Generating horizontal sync pulses

Now we are ready to set up the timer for the horizontal sync pulses:

      // Timer 2 - horizontal sync pulses
      pinMode (hSyncPin, OUTPUT);
      Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
      OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
      OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.

Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).

Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.

    ISR (TIMER2_OVF_vect)
      {
      } // end of TIMER2_OVF_vect

---

## Pixel data

Now things get tricky ...

Let's see how long we have to draw 640 pixels:

    ((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).

The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

---

## Summary

Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

---

>  I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

---

## Example of working at that resolution

A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

[![Example VGA output][3]][3]

---

> So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).

You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.

So yes, to work on more monitors you should have a direct relation between clock speed and resolution.

I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.

  [1]: https://i.stack.imgur.com/tGTx3.png
  [2]: https://i.stack.imgur.com/cxDIR.png
  [3]: https://i.stack.imgur.com/SC5PU.jpg


message:
Why is my Adafruit motor shield not spinning my motors?

I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.

I removed the vin pin, and I'm using [this](https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software) tutorial/code to make the DC motor spin.

I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.

Any ideas?

Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.

    // Adafruit Motor shield library
    // copyright Adafruit Industries LLC, 2009
    // this code is public domain, enjoy!

    #include <AFMotor.h>

    AF_DCMotor motor(4);

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Motor test!");

      // turn on motor
      motor.setSpeed(200);

      motor.run(RELEASE);
    }

    void loop() {
      uint8_t i;

      Serial.print("tick");

      motor.run(FORWARD);
      for (i=0; i<255; i++) {
        motor.setSpeed(i);
        delay(10);
     }

      for (i=255; i!=0; i--) {
        motor.setSpeed(i);
        delay(10);
     }

      Serial.print("tock");

      motor.run(BACKWARD);
      for (i=0; i<255; i++) {
        motor.setSpeed(i);
        delay(10);
     }

      for (i=255; i!=0; i--) {
        motor.setSpeed(i);
        delay(10);
     }

      Serial.print("tech");
      motor.run(RELEASE);
      delay(1000);
    }

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/NqNqb.jpg

body:
Per the comments above, and the [documentation from Adafruit][1], a 9V battery is insufficient for use with motors as they do not provide enough current.

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14


body:
A couple of things I see...

**1.)** Your motor leads may be shorting out of the housing of the motor. make sure they are not.

**2.)** You may have the motor on the wrong port for the given code:

On line 7 of the code it reads: `AF_DCMotor motor(4);`

So try switching physically your motor to port 4.

**3.)** Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.

    // --------------------------------------
    // i2c_scanner
    //
    // Version 1
    //    This program (or code that looks like it)
    //    can be found in many places.
    //    For example on the Arduino.cc forum.
    //    The original author is not know.
    // Version 2, Juni 2012, Using Arduino 1.0.1
    //     Adapted to be as simple as possible by Arduino.cc user Krodal
    // Version 3, Feb 26  2013
    //    V3 by louarnold
    // Version 4, March 3, 2013, Using Arduino 1.0.3
    //    by Arduino.cc user Krodal.
    //    Changes by louarnold removed.
    //    Scanning addresses changed from 0...127 to 1...119,
    //    according to the i2c scanner by Nick Gammon
    //    http://www.gammon.com.au/forum/?id=10896
    // Version 5, March 28, 2013
    //    As version 4, but address scans now to 127.
    //    A sensor seems to use address 120.
    // Version 6, November 27, 2015.
    //    Added waiting for the Leonardo serial communication.
    //
    //
    // This sketch tests the standard 7-bit addresses
    // Devices with higher bit address might not be seen properly.
    //

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

      Serial.begin(9600);
      while (!Serial);             // Leonardo: wait for serial monitor
      Serial.println("\nI2C Scanner");
    }

    void loop()
    {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        Wire.beginTransmission(address);
        error = Wire.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknow error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(5000);           // wait 5 seconds for next scan
    }


body:
I see that this is still not working even with a proper battery. My next best guess is you need to update your library:

>     // Adafruit Motor shield library
>     // copyright Adafruit Industries LLC, 2009
>     // this code is public domain, enjoy!
>
    #include <AFMotor.h>

Judging by `2009` and `AFMotor.h` you have a copy of an old version of the library. I recommend getting the [latest version][2] and following the [official tutorial][3].

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14
  [2]: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
  [3]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-dc-motors


message:
mthread and multiple header files

I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.

I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.

here is what I got:

main: call header:

    #include "tcan.h"

tcan.h:

    #ifndef tcan_h
    #define tcan_h

    #include "Arduino.h"

    class tcan : public Thread {
      public: tcan();
      protected: bool loop();
      private:
    };
    #endif

tcan.cpp

    #include "Arduino.h"
    #include "tcan.h"
    #include <mcp_can.h>

    bool tcan::loop() {
      // lala
      return true;
    }

but I get an error when compiling:

> tcan.h:6:28: error: expected class-name before '{' token  class tcan :
> public Thread {

Thanks in advance

body:
The compiler error is due to that the compiler does not know what Thread is.
> tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. **A good practice is to include all header files that are needed to read the header file.** As *Thread* is defined in *mthread.h* the *tcan.h* file should be:

    #ifndef tcan_h
    #define tcan_h

    #include <mthread.h>

    class tcan : public Thread {
    public: tcan();
    protected: bool loop();
    private:
    };
    #endif

Cheers!


message:
arduino pro mini downloading?

I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver.  I'm assuming they can all be connected.  My question is, how do I download programs to the arduino board?  And where might I find specific programs to download?

body:
The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!

With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).

Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.

As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!

As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


message:
Can Android phone can be used instead of( or with) Arduino as controller?

I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

 1. phone as controller (without arduino) - this option would be the
    best
 2. if phone cannot give commands maybe with arduino, while
    using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

body:
You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.

So for normal RC car you would need to have:

AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC


message:
How to switch on 32A/240VAC with Arduino?

I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.

I'm based in India and I am unable to find a relay switch rated higher than [this][1].

I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

  [1]: http://www.amazon.in/Channel-Module-Shield-Arduino-Electronic/dp/B00C59NOHK/ref=pd_sim_sbs_147_6?ie=UTF8&dpID=51amkYDfw4L&dpSrc=sims&preST=_AC_UL160_SR160,160_&refRID=1DYV10685X37A49WG5NV

body:
The simple answer is: you need to find a relay rated high enough for the voltage and current. There's no way you can make a small relay handle a large current, and relays cannot be joined together to share the load.

If a relay is not available in your country (and I seriously doubt that - you're probably just looking in the wrong places - instead of looking for things on Amazon or eBay try looking at proper industrial electronics suppliers) then you would have to come up with something more creative.

How about designing and building a small electro-mechanical system that physically changes the position of the existing switch for you? Solenoids to press the right bits of the switch, or motors to turn the right bit round, etc.


body:
> I don't want to try anything that results in a fire hazard.

That's a good idea.

Besides those toy relays there are real ones:
[440 V AC * 63 A][1] (Around there, you can find smaller ones too)

BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)

If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)

  [1]: http://uk.rs-online.com/web/p/non-latching-relays/8002896/


body: What about staying with small relay and just add a contactor? The relay will deal with the low current 230v to drive the contactor and the contactor would deal with the high current.


body:
Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).

The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.

With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.


message:
How to emulate an RFID tag with the RC522

Is it possible to emulate an RFID tag with the [RC522](http://playground.arduino.cc/Learning/MFRC522)? (Spec sheet: [nxp MFRC522.pdf](http://www.nxp.com/documents/data_sheet/MFRC522.pdf))
I want the RC522 to act like a NTAG213 nxp.com/documents/data_sheet/NTAG213_215_216.pdf and to be read/write by other readers/writers.
Are there libraries for that purpose?

body:
No. Looking at the datasheet, card emulation is not a feature provided by the RC522.

Another popular chip, the [PN532][1], does seem to indicate support for that feature, however, looking at the most popular [library for this chip][2] from Adafruit, it does not implement this feature. Another [library][3] from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.

  [1]: https://www.adafruit.com/datasheets/pn532ds.pdf
  [2]: https://github.com/adafruit/Adafruit-PN532
  [3]: https://github.com/Seeed-Studio/PN532


message:
Bad LCD? Bad microcontroller? Or what?

So I recently bought an Arduino along with an LCD module and two extra ATmega328P-PU ICs. Yesterday it was working just fine then I disconnected everything and reconnected it and this happened.

What could possibly go wrong?

Setup:

[![Photo of Arduino and 16 x 2 LCD display][2]][2]

with microcontroller that came with the board:

[1]: https://i.stack.imgur.com/x3e7P.jpg
[2]: https://i.stack.imgur.com/mhd5m.jpg

body:
> So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.

My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".

From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.

Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.

Cheers!


body:
These 16x2 LCDs are fairly sensitive about their power requirements.

As a first step, I would check the VCC and GND wires are well connected, and closely connected on the breadboard near the LCD.

If your LCD display shows rubbish characters, check the 4 data lines are connected in the correct order.

Also it looks like the contrast is at minimum (or LED backlight at maximum).  It could just be the photo, but best check both of these.


message:
How can Arduino know that the number in a variable is a pin number and not something else?

I have a question with the topic *variables*.

So, a variable is a place where you can store data.

And when you make a variable with datatype int (`int ledpin=13;`) then you store a value 10 in a variable named `ledpin`.

BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

body:
Yes, a variable is just somewhere to store some data.

It's what you *do* with the variable that is important.

For instance:

    int ledpin = 13;
    pinMode(ledpin, OUTPUT);
    digitalWrite(ledpin, HIGH);

That will set the variable `ledpin` to 13, then the next line will query the `ledpin` variable to find out what number it is, then pass that number to the `pinMode` function to set the mode of the pin to `OUTPUT`. The line after then does the same thing but passes the number 13 that it read from `ledpin` to the `digitalWrite` function to turn the LED on.

However, if you do this:

    int ledpin = 13;
    pinMode(ledpin, OUTPUT);
    ledpin = 10
    digitalWrite(ledpin, HIGH);

then it will act just the same at first, but the `digitalWrite` function will get the number 10 not the number 13 since the value in `ledpin` has been changed to 10 in the third line.

Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.


body:
You need to put the correct number into the pinMode() function.

You could put the number into a variable like:

    int ledPin = 13;
    pinMode(ledPin, OUTPUT);

or you can put a number straight into pinMode() like this:

    pinMode(13, OUTPUT);

Whatever number you put in will be the pin that you start using.

Here's an example to blink the onboard LED:

    int ledPin = 13;                 // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // Whatever number is in ledPin is made an output.
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(1000);                  // waits for a second
    }


body:
> BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

The Arduino does not "know" the intention of a variable. The variable "becomes" a pin number when passed as an argument to pinMode() or digitalRead().

The use of a variable to "name" a pin is part of a programming style. There are a lot of examples sketches that try to convey programming style. One of these is to reduce the amount of ripple effects of change; reduce the number of line to change for a logical change.

Continuing the LED pin number example above. The "baseline" code is:

    void setup()
    {
      pinMode(13, OUTPUT);
      ...
    }
    void loop()
    {
       digitalWrite(13, HIGH);
       ...
       digitalWrite(13, LOW);
       ...
     }

This works just fine BUT what is the ripple effect if we change the pin "13". The example uses symbols OUTPUT, HIGH and LOW which are also just numbers.

Typically in C the tradition is to use the preprocessor and define a macro.

     #define LED 13

The preprocessor will replace LED in the source code with 13 and the compiler sees the same code as above.

An alternative is using a variable.

     int LED = 13;

The drawback is that memory is allocated and it is possible to change the value at run-time which is often a very bad idea especially for a pin. The definition should actually be:

     const int LED = 13;

The drawback with the macro is that it is just a value. In C++ it is best to use a constant variable. This tells the compiler both what data type and value it is. A constant variable cannot be assigned (again).

The next level to strength code quality and reduce ripple effects is to use lexical scope. A lexical scope such as a function body, class or namespace defines "when" a symbol is available.

An example; first global scope where definitions are available across the source code (just as for a macro):

    const size_t BUF_MAX = 32;
    static char buf[BUF_MAX];

    const char* read()
    {
       ...
       for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
       ...
    }

Local lexical scope; definitions within a function:

    const char* read()
    {
       const size_t BUF_MAX = 32;
       static char buf[BUF_MAX];
       ...
       for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
    }

The symbols buffer *buf* and the buffer size *BUF_MAX* are only available in the function.

    class Reader {
    public:
      void read()
      {
        ...
        for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
      }
    protected:
      const size_t BUF_MAX = 32;
      char m_buf[BUF_MAX];
      ...
    };

Again the symbols are only available within the class and member function. Here is also another example of programming style. The prefix *m_* is used to show that it is member data.

Last, the same example using a namespace:

    namespace Reader {
      const size_t BUF_MAX = 32;
      char buf[BUF_MAX];
      ...
      void read()
      {
        ...
        for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
      }
    };
    ...
    for (int i = 0; i < Reader::BUF_MAX; i++) Reader::buf[i] = ...;

All symbols must have the prefix Reader when used outside the namespace.

These techniques have been developed to allow writing larger programs with reuse. It is important to use them when writing a library for Arduino and especially when sharing. Ripple effects and symbol redefinition/collisions are reduced.


message:
Powering Motor doesnt work from Digital Pin, but works on 5V power

I am building a little car project, and I have come across an issue that has made me go mental.
I have a single motor (3V-5V), that on direct 3.3V & 5V output works fine. However, when I connect this to a digital port, it for some reason doesn't power. Of course, I first thought it was not supplying correct power, so I got myself a voltage meter and tried that. 3.3V outputs, well 3.3V, all fine. The digital port outputs 4-5V (when it is coded to). So here is my question: Why aren't my motors powering/turning?

body:
Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.

A motor needs a large amount of current to start turning (called the *stall current*) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.

You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin.  Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.

Here is a good tutorial: http://www.circuitstoday.com/pwm-generation-and-control-using-arduino


message:
How to avoid delays in the loop() function?

vI have this functions in my loop() and it publishes temperature reading to Ubidots(an IoT cloud service) using the #include <Ubidots.h> library but it seems it returns a boolean and so the loop is delayed until a true or false value is return and this takes a while there by slowing  down my loop() function and other functions in it.
Is there a way I can call this function without it having to slow the loop?

    #include <math.h>
    #include <Wire.h>
    #include <Servo.h>
    #include <WiFi.h>
    #include <Ubidots.h>
    #include "rgb_lcd.h"
    #include "Timer.h"
    //#include <SoftwareSerial.h>

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

    char ssid[] = "ROSTALECOM_6916";                                                 //your network SSID (name)
    char pass[] = "6PTDFYJD";                                                         //your network password (use for WPA, or use as key for WEP)
    String api = "875c4a17d995ce4977bdfc1ace55233fd0591c7ce";                             //your API Key number
    String idvari = "567d623a762542205cbc517f";                                          //the number of the Ubidots variable
    String ctext = "{\"color\":\"blue\",\"status\":\"active\"}";
    Ubidots ubiclient(api);                                                             //with that you call the api with the prefix ubiclient

    byte p5[8] = {
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F
      };

    int a;
    int temperature;
    int B=3975;                  //B value of the thermistor
    float resistance;

    String readString;
    int val;
    int hum = 70.35;
    unsigned char base = 10;

    //Temperature Limits
    int maxTemp = 29;
    int minTemp = 28.5;

    //Declarations
    rgb_lcd lcd;
    Servo winServo;

    //Ubidots timer
    Timer t;

    void setup()
    {
        //Loading character
        lcd.createChar(0, p5);

    Serial1.begin(9600);
    Serial.begin(9600);
    winServo.attach(3);
    lcd.begin(16, 2);
    //mySerial.begin(9600);

    //Start Screen
    lcd.print("--SmartGarden--");
    for (int i = 0; i < 16; i++)
    {
            // scroll one position left:
            lcd.setCursor(i, 1);
            lcd.write((uint8_t)0);
            delay(400);
     }
    lcd.clear();
    lcd.print("Connecting...");
    //connect to  wifi network
    boolean response;
    int status = WL_IDLE_STATUS;
    response = ubiclient.WifiCon(ssid, pass, status, api);
    Serial.println(response);

    //
    t.every(1000, sendToUbi);

    }

    void readTemp()
    {
       a=analogRead(0);
       resistance=(float)(1023-a)*10000/a;
       temperature=1/(log(resistance/10000)/B+1/298.15)-273.15;

       //Send temperature via Bluetooth
       Serial.print(temperature);

       //print temperature to LCD
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Tmp:");
       lcd.print(temperature);
       //print humidity to LCD
       lcd.setCursor(8,0);
       lcd.print("Hm:");
       lcd.print("50");

       delay(1000);

    }
    void writeServo()
     {
      if (val != 0)
      {
      //val = map(val, 0, 1023, 0, 180);
      winServo.write(val);
      delay(100);
      }
     }

     void sendToUbi()
     {
     ubiclient.save_value(idvari, String(temperature));                                                  //this function is to post to ubidots and return True or False depending on the connection status
     Serial.println("The sensor value " + String(temperature) + " was sent to Ubidots");                //print the sensor value
     }

    void timerMax()
    {
      for (int i = 0; i < 60; i++)
      {

       }
       winServo.write(180);
     }

    void loop()
    {
      //read temperature
      readTemp();

      //Update ubidots timer
       t.update();

      while (Serial1.available()) {
        delay(3);
        char c = Serial1.read();
        readString += c;
      }
      if (readString.length() >0)
        {
          Serial.println(readString);
          delay(15);

           val = readString.toInt();
           if (val != 0)
           {
           //val = map(val, 0, 1023, 0, 180);
            winServo.write(val);
           delay(100);
           readString = "";
           }
           //writeServo();

        if (readString == "1")
           {
            digitalWrite(13, HIGH);
           }
         if (readString == "0")
           {
            digitalWrite(13, LOW);
           }
         readString = "";
      }

      if (temperature >= maxTemp)
      {
        timerMax();

      }

    }

body:
> How to avoid delays in the loop() function?

The question is why all the delays? Is there some logic missing? What are you trying to design?

Using delays is often a sign of an attempt to synchronize with external events. Wait for additional input, etc.

Let us walk through some of them:

    void readTemp()
    {
       ...
      delay(1000);
    }

What is this about? The function does read an analog input BUT then there is a lot of output to Serial and LCD and last this delay. Why?

    void writeServo()
    {
      ...
     delay(100);
    }

Again the same pattern. Now for your question "delays in the loop()".

    void loop()
    {
       readTemp(); // hidden 1000 ms delay

      while (Serial1.available()) {
        delay(3);
        ...
      }
      if (readString.length() >0)
      {
         ...
         delay(15);
         ...
         if (val != 0)
         {
           winServo.write(val);  // Possible hidden 100 ms delay
           delay(100);
           ...
         }
         ...
    }

Consider using some logic instead of the delays. There seem to be a common pattern you are using.


body:
As short reply and a general note, there is the [millis() function][1] that will be faster than a `delay()`. It returns the number of milliseconds since the Arduino board began running the current program. You use maths to check if you've waited long enough.

Like [this][2]:

      // check to see if it's time to do something; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // do something after the waiting interval here

       }

Edit: One should also be aware of [Interrupts][3], but be warned they must be used correctly.

  [1]: https://www.arduino.cc/en/Reference/Millis
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
  [3]: http://playground.arduino.cc/Code/Interrupts


message:
MFRC522 Only working sometimes

<!-- language: c -->

       /*
     * --------------------------------------------------------------------------------------------------------------------
     * Example sketch/program showing how to read data from a PICC to serial.
     * --------------------------------------------------------------------------------------------------------------------
     * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
     *
     * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
     * Reader on the Arduino SPI interface.
     *
     * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
     * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
     * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
     * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
     * when removing the PICC from reading distance too early.
     *
     * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
     * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
     * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
     * keep the PICCs at reading distance until complete.
     *
     * @license Released into the public domain.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10       // Configurable, see typical pin layout above

    MFRC522 MFRC522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
     Serial.begin(9600);  // Initialize serial communications with the PC
     while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin();   // Init SPI bus
     MFRC522.PCD_Init();  // Init MFRC522
     MFRC522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
      Serial.print("...");
    }

    void loop() {
     // Look for new cards
     if ( ! MFRC522.PICC_IsNewCardPresent()) {
        Serial.print("IsNewCardPresent");
      return;
     }

     // Select one of the cards
     if ( ! MFRC522.PICC_ReadCardSerial()) {
        Serial.print("ReadCardSerial");
      return;
     }

     // Dump debug info about the card; PICC_HaltA() is automatically called
     MFRC522.PICC_DumpToSerial(&(MFRC522.uid));
    }

I have recently purchased a RC522 RFID Module for my Arduino UNO. I connected everything, and started the IDE, downloaded the correct library, and ran the DumpInfo example program. The first time that I ran it, all went well, and when I swiped a card in fro, I recieved the correct data dump.

However, I started it up today, and reset everything, ran a new program to clear the Arduino, restarted my PC, and it still did not work. In the serial monitor it says that all is well, no error messages or anything. But, when I put a card in front of it, absolutely nothing happens.

Any help would be great!

body:
Check your power supply. I've seen so many weird results from inconsistent/under powered circuits. It's worth a look.

What does your circuit look like?
Are you powering the RFID reader from the Arduino or it's own source?
Are the grounds coupled?


body:
If I am right then you have soldered the pins of the module yourself and I recommend you to desolder the pins and soldered them again.

I also used RC522 RFID Module with an Arduino and I faced same type of problem with the module. This way worked for me.


body:
The first thing you could try is to increase the baud rate to 115200. I'm using a different library, and in the `auth_read_write.ino` sketch the `Serial.begin()` comments says "Read a fast as possible. There is a limit for how long we are allowed to read from the tags".

If changing the baud rate doesn't work, then have a look at this answer: [RFID-RC522 not working, red led is on][1]. It has a link to a different library which worked for me.

  [1]: https://arduino.stackexchange.com/questions/44099/rfid-rc522-not-working-red-led-is-on/44109#44109


message:
How are HIDs (keyboard,joypad) created and mapped?

I am creating an electronic device that has a 4 position rotator switch and a SPST Momentary ON push button. For the knob, I plan for position 0 to be low (OFF). Position 1-3 are high (ON). But I want these positions to equate to a different signal so they each have different values. When push button is pressed, it sends a high (ON) signal.

Can someone point me into slightly setting up the circuit to accomplish this?
And how can I create a remapper program (preferably in C++) that detects the HID device and allows the end-user to remap the pushbutton signal to any QWERTY key? I want replicate this process for each input of my device.

body:
When the Arduino sends data to the computer using the HID protocol it sends what is called a *HID Report*. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.

In the case of keyboard events it sends a *HID Keyboard Report*

[![enter image description here][1]][1]

It can send events for up to 6 keys at once along with up to 8 *meta* keys.  How those key events are interpreted are down to the *Keyboard Mapping* used on the computer.  This is the setting (usually in the *Language* or *Regional* settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.

While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.

So how would you go about doing what you want to do?  Well, my recommendation is not to do it on the computer, but to do it on the Arduino.  The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily.  So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event.  You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings.  How you do that communication (what protocol you come up with) is entirely up to you.

----

As for the hardware side of things - all you really need is just the switches / buttons and wire.  Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground.  For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.

  [1]: https://i.stack.imgur.com/WM4Lg.gif


message:
What is the Proper Voltage to supply an enough Current to the Arduino

I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?

I will be using a Lilypad Arduino.

Your replies would be a big help to me.

Cheers!

body:
The [Technical Specs][1] say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.

Remember though:  Power consumption = Current  x  Voltage

So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.

Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardLilyPad


message:
Why does an RGB LED between VCC and PWM work?

I'm an Arduino beginner and I recently bought a cheap starter kit on eBay. One of the lessons in the starter kit is an [RGB LED controlled by 3 PWM output pins][1]. However, the arrangement of the connections seems a bit funny to me:
[![Strange LED PWM setup][2]][2]

To my surprise, it worked. I could see the three LEDs inside the plastic change colors. Why does this work? Do the PWM pins accept current whilst low? Is this a common arrangement? See the above link for the code provided in the lesson.

  [1]: http://wiki.epalsite.com/index.php?title=Starter_Kit_for_Arduino#Lesson_6_RGB_LED_various_color_display
  [2]: https://i.stack.imgur.com/Qupku.jpg

body:
This is a common arrangement and is known as *Common Anode*, and the I/O pin is said to be *sinking* current.

To better understand what is happening here it's best to think of an I/O pin as a two-position switch:

[![enter image description here][1]][1]

When the I/O pin is HIGH point 1 is connected to point 2. When the I/O pin is LOW point 1 is connected to point 3.

So when HIGH the circuit is Vcc -> D1 -> R1 -> Vcc (or the other way around - I have done it that way because of the polarity of the LED), and no current can flow since it has nowhere that isn't at a lower potential than Vcc to flow to.

But when the I/O pin is LOW the circuit is now Vcc -> D1 -> R1 -> GND and so current can flow through it all to ground.  As a result the LED now lights up.

One thing you may have noticed now is that the operation is backwards.  Set the IO pin to LOW to turn the LED ON. That has the effect, as well, that PWM duty cycles are reversed.  `analogWrite(ledPin, 0)` will be full brightness and `analogWrite(ledPin, 255)` will be off.

  [1]: https://i.stack.imgur.com/WJFVn.png


body:
The RGB LED is common anode. This is why it is connected to VCC and the PWM pins pulls down to light resp LED.

A common cathode RGB LED would be connect to GND and the PWM pins would pull up to light

Cheers!


body:
> Do the PWM pins accept current whilst low?

The pins **sink** current when low. And yes, that is commonly done. The pins are **not** "do nothing" at LOW, and "put 5V there" at HIGH. They are specifically designed to try to source (drive high) current when HIGH and sink (drive low) current when LOW.

To have pins (more or less) do nothing, you have to set them to INPUT mode. Then they try to neither source nor sink.

*Caveat:* if you enable the internal pull-ups they will try to weakly source current.

---

> Is this a common arrangement?

It is quite common, depending on whether the device you are controlling is active high, or active low.


message:
Arduino mini being programmed with CH340G

So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.

So, this programmer has pinout of 5V|GND|TX|RX|3V3.

I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).

I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.

There's still no connection between them.

Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?

body:
First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See [this page][1] or [the arduino uno schematics][2] to see how to put the capacitor (it's simply in series with the signal.

However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.

As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.

  [1]: http://playground.arduino.cc/Learning/AutoResetRetrofit
  [2]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf


message:
What's the difference between setting a variable outside a function and setting a variable inside a function?

I'm programming C++ for arduino and today I have seen an example like this

    void loop() {
        byte variable = 0; // << This variable is the question.
        //more stuff here
    }

Is the same as this?:

    byte variable = 0;

    void loop() {
        //stuff here
    }

If the answer is "no", my question is "why?".

Thanks for your time!

body: No, it's not the same. Instructions within the loop() repeat every time the program gets to the end. If you set your variable at the start of the loop, it will automatically get reset to the default when you might not want it to be reset. The author of the example wants to reset to default every time the loop completes.


body:
The difference is not only about where you set the variable, but about where you defined it as well.

Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program.  If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.

If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.

If you define it inside the function, but _with_ a static specifier,

    static byte variable = 0;

then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and *will not* be executed within function.

Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.


message:
Atmega328 PWM frequency setting not working

I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:

    DDRD |= (1 << PORTD6); //Setting pin D6 as output
    OCR0A = 128; //50% duty cycle
    TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
    TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency?
Or where am I making the mistake? Thanks for any answers.

body:
Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden [initialization][1]?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L263


message:
Problem sending colors from an audio visualizer to Arduino

Sorry in advance for the length of my question; I want to provide proper context. I wrote an audio visualization program in Java that (in addition to making "pretty pictures" based off of the amplitudes of different frequencies being sent from the computer) sends a color to an Arduino Uno based off the sound it is "hearing."

I know the algorithm for generating this color is functional (in addition to sending that color to the Arduino, it also changes the color of an item on the DrawingCanvas). When the color is sent to the Arduino (as 3 bytes representing red, green, and blue), though, the physical LEDs don't respond correctly (they become a random color for a few seconds then switch to another random color for a bit – the behavior is hard to describe, but certainly not desired!).

I have been able to send colors to the Arduino using the same client program, but when the audio visualizer sends colors by the same method, this odd behavior occurs. My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Here are the relevant pieces of code from the client, the audio visualizer, and the Arduino:

**Client:**

    public class Client extends WindowController{
      //USB is a class I wrote that extends PApplet. Unless baud rates are the issue, I don't think we need to worry about this.
      static USB port = new USB("COM3", 9600);
      byte[] code = new byte[LENGTH];
      static byte killTerm = -100;
      private AudioVisualizer vis;

    public void begin() {
      resize(1500,900);
      for (int k=0;k<LENGTH;k++){
        code[k]=killTerm;
      }
      vis = new AudioVisualizer(10,30,1200,300,canvas);
    }

    public void onMouseClick(Location point) {
      runVis = !runVis;
      if(runVis) {
        vis.start();
        code[0]=-22;
        sendCodeUSB(code);
      } else
        vis.stop();
 }

    public static void sendCodeUSB(byte[] code) {
      for (int k=0; k<code.length; k++) {
        port.writeProfile(code[k]);
      }
    }

AudioVisualizer

    public class AudioVisualizer implements Runnable {
      Thread thread = null;
      DrawingCanvas canvas;
      byte[] code = new byte[3];
      private int xPos;
      private int yPos;
      private int width;
      private int height;
      private int scale;
      private Location topLeft;
      private Location bottomRight;
      private FilledRect background;
      private int brightness=0;
      private boolean needOff = false;

      public AudioVisualizer(int x, int y, int w, int h, DrawingCanvas myCanvas) {
        canvas=myCanvas;
  xPos=x;
  yPos=y;
  topLeft = new Location (xPos,yPos);
  bottomRight = new Location (xPos+width, yPos+height);
  width=w;
  height=h;
  background = new FilledRect(topLeft,width,height,canvas);
  background.setColor(Color.BLACK);
  initiateMonitor();
  scale = height/30;
      }

      public void start() {
        if (thread == null) {
          thread = new Thread(this);
       thread.start();
     }
      }

      public void stop() {
        thread=null;
      }

      public void run() {
        while (thread != null) {
          try {
            Thread.sleep(40);
          } catch (InterruptedException e) {
          }
          graphAmps();
        }
        thread = null;
      }

      public void graphAmps() {
        //there is a whole bunch of stuff here that is unrelated that I removed.
        //basically, just know that graphAmps() calls avgColors()
        avgColors();
      }

      public void avgColors(){
        //there is stuff here that generates avgRed,avgGreen,and avgBlue (known to be working)
        Color c = new Color (avgRed,avgGreen,avgBlue);
        background.setColor(c);
        //so we don't spam the Arduino more than we need to
        if(avgRed>10 || avgGreen>10 || avgBlue>10) {
          sendArduinoColor(c);
          needOff = true;
        } else if (!(avgRed>10 || avgGreen>10 || avgBlue>10) && needOff) {
          sendArduinoColor(c);
        }
      }

      public void sendArduinoColor(Color c) {
        //takes the color and sets code = an array of 3 bytes with values from 0-100 (100 is the highest brightness I ever want the LEDs to be)
        //I am sure this is done correctly so I've left it out.
        constrainArduinoColor(c);
        //calls the static method from the client and passes in the byte array with the rgb values
        Client.sendCodeUSB(code);
      }
    }

Arduino

    #include <EEPROM.h>

    int redPin = 11;
    int bluePin = 10;
    int greenPin = 9;
    //declared here for debugging ease of access
    int r;
    int g;
    int b;
    //are we going through the Spectrum Cycle loop for the first time?
    boolean sclFirstTime = true;
    //temporary initialization
    boolean waiting = true;
    int index = 0;
    const int LENGTH = 20;
    byte profile[LENGTH];
    byte avProfile[3];
    byte killTerm = -100;
    byte audioVisualizationCode = -22;

    void setup() {
      //start the serial communication
      Serial.begin(9600);
      //initialize the profile to all -1 values
      clearProfile();
    }

    void loop() {
      //if there is nothing over serial and nothing is in the EPROM, we are waiting
      if (!eepromProfileAvailable() && Serial.available()==0){
        waiting = true;
      } else if (eepromProfileAvailable() && Serial.available()==0) {
        //if there is something in EEPROM and nothing over Serial, we aren't waiting and load the EEPROM profile
        waiting = false;
        loadEEPROMProfile();
        //load the EPROM color profile into the array
      } else if (Serial.available()>0) {
        //if something enters over Serial, we aren't waiting, clear the profile, and load the new profile with the serial info
        waiting = false;
        clearProfile();
        while (Serial.available()<LENGTH) {}
        // Wait until there are LENGTH number of Bytes waiting
        for(int n=0; n<LENGTH; n++) {
          profile[n] = Serial.read(); // place them in the profile.
        }
        Serial.flush();
        //clear out the serial to prep for next time
      }
      //if we have a profile (either from EEPROM or Serial), save it, check for special codes (if found, apply the effect),
      //and if there are no special codes, the profile is a static color profile, and set LEDS to that.
      if(!waiting) {
        saveEEPROMProfile(); //omitted but working
        if (profile[0]==101) {
          while (Serial.available()==0)
            spectrumCycle(); //omitted but working
        } else if (profile[0]==-22) {
          audioVis();
        } else {
          anodeSafteyOut(redPin,profile[0]);
          anodeSafteyOut(greenPin,profile[1]);
          anodeSafteyOut(bluePin,profile[2]);
        }
      }
    }

    //a bunch of preset color effects omitted
    //we are using a common Anode LED, so low value is 255 instead of 0
    void anodeSafteyOut(int pin, int c) {
      if(c>=0) {
        c = 255 - c;
        //as a safety measure because there are no resistors (yes, I know im breaking an intergalactic law by not using any), make sure we aren't writing something too bright
        if (c>=155) {
          analogWrite(pin,c);
        }
      }
    }

    //wait for 3 bytes to come in, assign them to the avProfile, set the colors to that, do it again
    //THIS IS PROBABLY WHERE THE PROBLEM IS
    void audioVis() {
      while (Serial.available()<3);
      for (int k=0;k<3;k++)
        avProfile[k]=Serial.read();
      anodeSafteyOut(redPin,avProfile[0]);
      anodeSafteyOut(greenPin,avProfile[1]);
      anodeSafteyOut(bluePin,avProfile[2]);
      audioVis();
    }

So that's a lot, and I've left a lot out that I didn't think was necessary, though I'm happy to provide the full programs if needed. Thanks for your help!

Here is `constrainColorArduino`:

    public void constrainArduinoColor(Color c) {
      int r = c.getRed();
      int b = c.getBlue();
      int g = c.getGreen();
      int r1 = (int)(r*0.4);
      int b1 = (int)(b*0.4);
      int g1 = (int)(g*0.4);
      byte r2=0;
      byte b2=0;
      byte g2=0;
      for (int k=0; k<r1; k++)
        r2++;
      for (int k=0; k<b1; k++)
        b2++;
      for (int k=0; k<g1; k++)
        g2++;
      System.out.println(r+" "+g+" "+b);
      System.out.println(r1+" "+g1+" "+b1);
      if (r2>100) r2=100;
      if (b2>100) b2=100;
      if (g2>100) g2=100;
      if (r2<0) r2=0;
      if (b2<0) b2=0;
      if (g2<0) g2=0;
      System.out.println(r2+" "+g2+" "+b2);
      code[0]=r2;
      code[1]=g2;
      code[2]=b2;
    }

body:
Your idea that there's a synchronization issue seems plausible.  Whenever any byte gets skipped, color assignments shift from RGB to GBR or BRG, etc.

While sending a start code before the color profile is a possible approach to fixing the problem, it may be that occasionally one of the RGB values matches the start code, which could result in temporary desynchronization.

For an alternative method that doesn't require a start code, consider encoding the data into four bytes.  In the first byte, send the high two bits for RGB; in the second, the next two bits of each color; etc.  Set the low two bits of each byte to 11, 10, 01, 00 for first, second, third, fourth.

That is, each byte you send would be encoded BBGGRRdd where the capital letters are appropriate bits from RGB brightness levels and dd indicates which pairs of bits are being sent.

Here's some (untested) code that implements the decode:

<!-- language: lang-c -->

    byte code = Serial.read();
    byte shif = 2*(code & 3);
    byte mask = ~(3<<shif);
    code >>= 2;
    for (byte i=0; i<3; ++i) {
      profile[i] = (profile[i] & mask) | ((code & 3)<<shif);
      code >>= 2;
    }

The following shows a function `sendData3()` that encodes three bytes from an array of RGB data into four bytes to be sent to the Arduino.  It also shows a convenience function `sendDataRGB()`.  A call like `sendDataRGB(100, 0, 42);` puts three R, G, B values into a three-byte array and calls `sendData3()` to send it off.  [Substitute as appropriate in place of `Serial.write`]

<!-- language: lang-c -->

    void sendData3 (byte *dataIn) { // dataIn[] has R,G,B levels
      byte code;
      byte mask=3;   // mask for low 2 bits of a byte
      for (int b=4; b; ) {
        --b;
        byte shif = 2*b; // For moving bits to align with mask
        code = 0;
        for (int k=3; k; ) { // Loop to handle dIn[2], dIn[1], dIn[0]
          --k;
          code |= (dataIn[k]>>shif) & 3; // Pick off 2 color bits
          code <<= 2;       // Roll up
        }
        Serial.write (code | b); // Send encoded bits
      }
    }

    void sendDataRGB (byte R, byte G, byte B) {
      byte dataEg[] = { R, G, B };
      sendData3(dataEg);
    }


body:
>My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Close, but the source of the problem is probably this line

      Serial.flush(); //clear out the serial to prep for next time

Because your audio visualizer keeps sending data, it's quite likely that by the time you get around to claiming a record, at least some part of another one (or more) has also arrived.   When you discard that with flush(), you are probably most of the time *not* going to be discarding exactly a record's worth of bytes, but rather some arbitrary number more or less.  This introduces a synchronization problem.

You've already had some advice on solving synchronization problems.  There are a variety of workable methods, binary and otherwise.  One simple one that works in a lot of situations is to encode bytes textually in hex and terminate the record with a newline.  It does have just over a factor of two overhead, but it has the debug/test advantage of being human readable, and you can basically cover the overhead by switching from 9600 to 19200 baud.


message:
Where to start?

I am totally new to Arduino and I'm a real beginner with electronics and robotics. I would like to know where to start, knowing that my ultimate goal is to build an autonomous robot (I know that I will not be able to do this project before learning a lot of things). I am a developer so I have no problem with C and C++, actually I am using C++ at work.

Thanks

body:
Personally I think the best way to start is hands on with a small robot. I mean the kind that have a couple of wheels, are circular and only a few inches in diameter. You can add many kinds of sensors or actuators as you learn. You get to see it move and hold it and pick it up.

The idea is to start with basic LED control and then get motors turning, sensors on, and then improvements and upgrades.

If you're ok at coding then electronics may be the bottle neck. Get a good book is my advice. As far has hardware the EEVBLOG guy Dave gives a good run down on what he recommends [here][1].

Just start.

  [1]: https://www.youtube.com/watch?v=R_PbjbRaO2E


body:
I would start with a lot of small projects, each designed to give you confidence over one small aspect. For example:

* Detect variations in light with an LDR
* Operate a motor (there are various types of motors) - including controlling one with a MOSFET or BJT transistor
* Blink LEDs
* Connect something with a fancier interface (eg. I2C or SPI) and get the hang of "talking" to a more sophisticated interface chip (you'll probably need this for things like balancing)
* Try distance detection. Eg. with bouncing light or sound off an obstacle
* Communicate between two Arduinos - get used to communications protocols, reliability, packet loss, etc.
* Get used to detecting switch presses, either individual ones, or a keypad (or both)
* Look into reverse polarity protection
* Look into detecting low voltages on your batteries
* Try radio communications (probably need to send your robot instructions) - there are various different ways of doing that
* Possibly experiment with motor-driver boards (eg. H-bridges) which you may need for driving wheels
* Investigate reading continuous values (eg. potentiometers, rotary encoders)
* Investigate read-outs (eg. 7-segment LED displays, or LCD displays)
* Investigate generating sounds (beeps, tunes)

You could take a look at my [radio controlled car](http://www.gammon.com.au/forum/?id=11506) project. I look into some of those things there, and describe how I handled them.

[![Radio controlled car][1]][1]

I would do these things initially on the bench. Don't try to assemble something fancy until you have some experience with how the individual parts work.

  [1]: https://i.stack.imgur.com/EGaij.jpg