text:
Processing Serial data
I have a PM10 sensor that I'd like to get the values from.
Here's the official documentation from the sensor:

I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?
I'm looking at this example:
void setup() {
  Serial.begin(9600);
  Serial.println("<Arduino is ready>");
}

void loop() {
  recvOneChar();
  showNewData();
}

void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChar);
    newData = false;
  }
}

Ideally, i'd like to get the PM2 and PM10 values and print them out.

The proper method of receiving this kind of data is to use a sliding window. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape).  You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case).  As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.
The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array.  Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.
For instance:
uint8_t window[10];

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

void loop() {
    if (Serial.available()) {
        // Slide the window
        for (uint8_t i = 0; i < 9; i++) {
            window[i] = window[i + 1];
        }
        // Add the new character
        window[9] = Serial.read();

        // Output the current window data for debugging
        dumpWin();

        // Check the framing characters
        if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
            // Calculate the checksum
            uint8_t cs = 0;
            for (uint8_t i = 2; i < 8; i++) {
                cs += window[i];
            }
            // If the checksum matches...
            if (cs == window[8]) {
                // ...we have a valid packet!
            }
        }
    }
}

void dumpWin() {
    for (int i = 0; i < 10; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
    }
    Serial.println();
}

Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats.  For instance the PM2.5 would be:
uint16_t pm25i = (window[3] << 8) | window[2];
float pm25 = (float)pm25i / 10.0;

The PM10 would be the same but with window[5] and window[4] of course.

Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of SoftwareSerial instead of the hardware UART pins for communicating with the sensor.

Amazing stuff! Great work!

However, i'm having an issue, it never reached the IF condition, so i did some debugging:
Serial.print(window[0]);
Serial.print("=");
Serial.print(window[9]);
Serial.println();
And it's returning some weird results:
0=170
0=192
0=85
0=1
0=115
0=1
Shouldnt the first number be a byte? Shouldnt the second one be static as well? Why is the second number changing for each row?

You might be better off dumping the whole window each time. I'll add a little function to do that.

@R0b0tn1k By the way, 170 is 0xAA - the first number in the = will change to 170 when it finally reaches the bottom of the window (10 characters have been received).


text:
Windows driver installer not detecting arduino
I'm trying to program my Arduino Uno with my Windows PC. I followed all the instructions on the site. I mistakenly downloaded the .zip file and didn't unzip it, before plugging in my Arduino Uno. So naturally, no message came up. I then followed the correct procedure, but Windows driver installer does not detect the Arduino Uno. What can I do to fix this?

Is this a genuine Arduino or a clone? Also, why not just try deleting the zip and downloading and running the installer instead?

@JakeC genuine Arduino. I'm a newbie so you're going to have to take it slow with me.

Being that you are a newbie, I highly recommend just downloading the installer and running that. While the zip does contain the drivers, it is pretty hard to install them unless you are already familiar with manually installing drivers on Windows.

@JakeC can you direct me to where I can find the installer? I'm using a Windows machine.

https://www.arduino.cc/en/Main/Software where it says "Windows Installer"

@JakeC I got it working. Thanks, your advice saved a noob llike me a lot of wasted hours.

Please feel free to answer your own question and mark it as accepted (you might have to wait a bit for this depending on reputation) especially if there was something particular about your setup that you think might help future users.

@JakeC - alternatively convert your comment into an answer as it appears to have worked. :)

Per my comment above, the drivers are not installed when using the Arduino editor from an extracted zip file. If you are feeling adventurous, they are located in the /drivers folder and you can install them manually, there are plenty of instructions elsewhere on the internet on how to do that.
My recommendation would be to just download and run the installer version of Arduino, as that will take care of registering the drivers for you. The installer can be found on the download page indicated with the text "Windows Installer".

source: Stack Exchange

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

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

sort: votes


text:
What is the best serial protocol for bidirectional communication with NodeMCU?
Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.
Details:
I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.
I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending <=122 character strings to Arduino and possibly getting a short response.
I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).
My research shows that:

ESP8266 has obvious timing issues, having been designed for a different purpose.
Controlling the ESP8266 from Arduino via hardware serial works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.
The same via SoftwareSerial is unreliable
Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)

I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.
The Arduino already works as an I2C master.
I'm assuming I2C is the way to go, but wanted to ask for opinions first.
[EDIT]
Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 can't do very precise timing, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?

I need it the other way around, too - can you clarify what that means? I'd rather keep the hardware serial ports for programming - maybe, but unplugging two wires every time you need to program isn't that bad, if it makes the whole setup work reliably.

I would suggest my ICSC library - I use it for communication between a NodeMCU and a PIC32 board.  https://github.com/MajenkoLibraries/ICSC

@nick-gammon Controlling the Arduino by sending serial commands from ESP8266. Would be fine if the latter didn't talk so much - errors and boot message... And programming: 2 jumpers are tolerable but won't help when I'm monitoring/debugging the whole setup.

@majenko Useful, so thanks, but I'm not seeing much relevance to the question itself. First arg in constructor is a serial interface, which means the choice I'm asking about had already been made.

I have a page about debugging with I2C and SPI which shows how you can debug if the serial ports are in use for other purposes. I also have pages about I2C and SPI if that helps. I'm not seeing much relevance to the question itself - I don't see a question, frankly.

@nick-gammon Neat, thanks. he question stands, though - speaking ow which, are you playing Jeopardy, or is this really "unclear what is being asked" territory? Sorry. If my next edit does not explain to your satisfaction, please try to put me on the right track.

Most of the posts I have seen about it use serial, so I personally cannot answer your updated question. With luck someone else can.

Majenko's library appears relevant because support for non-UART software serial was recently added ( https://github.com/MajenkoLibraries/ICSC/pull/2/files ), and it was designed for high reliability.

Could you please edit your question to clarify: Do you want to reserve the UART on the Arduino for something else, so you want to communicate using some other pins of the Arduino? Do you want to reserve the UART on the ESP8266 for something else, so you want to communicate using some other pins of the ESP8266? Do you want to reserve both the Arduino UART and the ESP8266 UART, and communicate using other pins?

@david-cary My main reasons not to use hardware UART: 1. ease of debugging, requiring no other hardware of software. 2. NodeMCU sends unsolicited data and I don't know how to ignore or turn it off. 3. I may at some point wish to connect more than 1 duino to the esp.

So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.
In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.
One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.
Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial.  For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin).  When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high.  When the APM detects & processes incoming data as I2C slave, it sets OK2SEND low.  NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low.  APM detects HAVESENT low which completes the handshake.  When APM is ready for another byte, it sets OK2SEND high again.  etc.  Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.
If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above.  The APM could be like a dedicated I2C peripheral, albeit a slow one.

APM uses Wire.onReceive() and onRequest() - works well. Thank you, for reminding me that other kinds of communication can take place aside from i2c - it was a D'OH! moment for me.

Just to clarify, though: I wrote the Arduino was already the i2c MASTER. I only switched it to slave later because afaik NodeMCU can't work as a slave. But I'd really like to keep the Arduino as master so I'd have direct access to the RTC module.

While possibly not "the best", I have found I2C to be sufficient for my needs.
Simple to use, if a bit different conceptually (master-slave).
My tests have shown it to be reliable thus far, zero errors over 20 minutes (sending & receiving 20 bytes each time), as long as there were sufficient pauses between calls.
I am going to make the Arduino switch its i2c master/slave role based on the state of other pins. Master most of the time (to use a DS1307 RTC, etc), switching to slave whenever NodeMCU (which can only work as master) has something to say. Thanks to Zeph for the idea.

Side note: You now that on i2c you can have multiple masters talking to each other?

@offler Yes, I do recall that. Haven't gotten the hang of it, though, especially with NodeMCU. I don't trust examples that make it look easy, got burned too many times.

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


text:
Morse code translator Loop the same sentence
I'm a newbie so forgive my ignorance.
I'am using the Morse code translator to light up the LED which is fine but after it has processed the sentence it turns off. How can I get it to loop the sentence continuously.
Thanks

Add the code and we will be able to tell you something

-1 until some code arrives

I guess this is the sketch you are using. It reads characters from Serial and translates them to Morse code.
What you need to do to make it loop a sentence is, 1) read a sentence into a buffer, 2) loop though the buffer and translate to Morse code.


text:
Share battery pack with Arduino and DC motors
I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?

If you want to operate the uC reliably, then take a switching step down regulator (I usually use the LM2596 modules from ebay, 1€/each, but a lot of them are fine), then push the 5V voltage in the board directly (through the USB connector if you want some protection - e.g. fuse - or directly in the 5V pin if you don't want it)

I have LM317 and LM7805 can I use any of this? @frarugi87

The LM7805 has a 2V dropout, so as soon as the voltage drops under 7V you won't have 5V again. The LM317 has a 3V dropout, so it will not work. Moreover they are linear regulators (they will waste much power, and you don't want this to happen with a battery powered system). Just use a switching regulator (the modules you find on ebay are perfect for your needs)

You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts.
As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower.  A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used.
Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack.  Not a lot to lose on trying.
The UNO already has decoupling capacitors in it's 5 volt regulator circuit.
Just for fun,  you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator.
If you decide to measure the 5 volts with an analog input,  read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.

When the motors are running the battery voltage can drop quite a bit too. If the motors allow it, I'd use 8 batteries (9.6 volt) instead.

I like your analog input read up idea. To do so, should I connect arduino 5V pin to any one analog pin directly? Could you tell me more? I also like frarugi87 comments on main quesion. Could you comment on this that which one is the best approach? @marla

@palash he is saying that if you want to measure the battery voltage, you have to use a stable analog reference instead of Vcc, because if the 5V voltage drops to 4.5V your analog reading will raise. So if you want to measure the battery voltage, you can use the internal analog reference (1.1V), then use a voltage divider to lower the 7.2V to around 1V (for instance 82k and 13k). I suggest you to use a PMOS to disconnect this from the battery (otherwise it will consume power)


text:
ArduinoMEGA: 64 digital inputs cause random digitalRead values
I have 64 hall effect sensors (magnetic field sensors) (DRV5023AJQLPG) connected to an Arduino MEGA 2560. For that, I use 48 digital pins and 16 analog pins as digital input pins. The program in the Arduino continuously reads out those 64 digital input pins (in a for-loop) and sends out a serial byte, to a laptop via a usb cable, whenever one of those input pins changes between LOW and HIGH. I also use the ATmega2560’s internal pullup resistors to prevent irregular readouts of the input pins when the sensor is not giving a 0v output (i.e. when it isn’t measuring a strong enough magnetic field).
Everything is working fine when I only physically connect up to 16 of the sensors. The laptop then only receives bytes that correctly tell when a sensor measures a state-change.
However, when I start connecting more of those 64 sensors, then the laptop starts receiving irregular streams of bytes, erroneously suggesting that all the connected sensors measure changing magnetic fields (HIGH and LOW readouts).
I can think of two reasons why these irregular readouts occur:
1. Either, the ATmeag2560’s internal pullup resistors arent working as I think they should.
2. Or, the arduino board and >16 hall effect sensors combined are pulling to much current.

Pullup resistors not working?
When testing with only 16 sensors connected, it is a stable, properly working setup. When I explicitly don’t use the pullup resistors in the program then the setup does start behaving irregular, also with just 16 sensors. So the internal pullup resistors seem to be properly activated by the program.
Arduino + 64 sensors draw to much current?
Besides powering the Arduino board and sensors via the usb cable (providing 500mA), I’ve also tried external power sources that provide 1 or 2A. I’ve also powered the Arduino board via an external 5v, +1A voltage regulator, bypassing the Arduino’s onboard voltage regulator. This all doesn’t seem to make a difference in the system’s irregular behaviour. When measuring those setup’s current usage (with amperage meter) it didn’t go above 250mA.

Calculating the combined current usage (using datasheet info), I came to this:
- sensor operating current:             2,7 mA
- sensor output current when in ‘active’ state:     0,25 mA
- TOTAL current of 64 sensors   (3mA*64=)       192 mA
- Arduino MEGA current (approx)             150 mA
- TOTAL current of 64 sensors + Arduino MEGA:       **342 mA**

So, both the calculated and measured current usage seem within the range of what can be handled by mentioned power sources.
I’m kinda stuck now. Can anyone suggest anything that might cause this problem? Or point to incorrect thinking of me? Thanks for any responses.

'Schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line):

Top-side: the hall effect sensors and Vcc an GND rails:

Bottom-side: ArduinoMEGA + the 64 red sensor output lines to the input pins:

Below is the Arduino code:
/*
Arduino to Pd protocol

 Placing or removing a chess piece sends only one byte.
 There’s no other serial data being communicated.

 event:                     byte value:
 placing a chess piece on a square:     0-63
 removing a chess piece from a square:          64-127

 ArduinoMEGA pin to byte value mapping:
  byte      pin
  0     6
  1     7
  2     8
  3     9
  …
  46        52
  47        53

  48        A0 (analog 0)
  49        A1
  50        A2
  …
  62        A14
  63        A15

*/

byte prevSquares[64];  // array that holds previous readouts
byte i;                // variable used in for-loops
byte sensorValue;      // variable temp storing of digitalread

void setup() {
  Serial.begin(9600);
  for (i = 0; i < 64 ; i++) {
    pinMode(i+6, INPUT_PULLUP);  // activate pullup resistor
  }
  for (i = 0; i < 64 ; i++) {
    prevSquares[i] = digitalRead(i+6);
  }
}

void loop() {
  for (i = 0; i < 64 ; i++) {
    sensorValue = digitalRead(i+6);
    if (sensorValue != prevSquares[i]) {
      // chess piece was placed or removed from square
      if (sensorValue == 0) {
        // chess piece was placed
        // send serial byte (0-63):
        Serial.write(i);
      }
      else {
        // chess piece was removed
        // send serial byte (64-127):
        Serial.write(i + 64);
      }
      //update prevSquares array:
      prevSquares[i] = sensorValue;
    }
  }
}

Personally I think that 64 sensors is just a waste of space... You can wire them in 8 rows of 8 sensors, enable a single row and then read it, then pass to the next one. Anyway what is the error stream? all high, all low, change continuously? And does it do this on all the pins or just on some of them?

The stream consists of highs and lows, continuous change. It's occurring  at any moment on, say, half of all pins, or more, but which pins is changing over time. The stream does look like as if the pullup resistors are not in use.
(BTW: the sensors are powered (connections: ground, Vcc, output) and have an internal state. Using a matrix of 8x8 would turn them on/off all the time and they'd loose their internal state.)

Then I'd use some multiplexers... Or 16bit port expanders.. Because personally I don't like filling a board's pins with sensors, otherwise you won't be able to add other stuff.. Anyway.. You did all the tries with the same firmware (so compiling for 64 sensors even when using 16 of them)? Did you connect the new sensors with the board shut down or not? From the datasheet the atmega should be able to handle currents up to 200mA, and your circuit draws approx 50mA for the uC and 16mA for the pullups, so it should be fine

Yes, I've done all the testing with the software reading all 64 input pins, also when fewer sensors were connected. I (in)activated sensors by (dis)connecting the ground to those sensors, while the Arduino board remained powered. To be clear: The sensors are not powered through the atmega pins, but get their power from the arduinoMEGA board's ground and 5v pins (so, from the on board voltage regulator), and I've also tested it with an external +1A voltage regulator).

Did you try to leave all 64 sensors powered and (in)activate all of them by (dis)connecting the signal wire instead of the ground wire?

I just did that. It gives similar result, except it already becomes unstable when >8 sensors are connected.

Have you tried actually measuring the current use, instead of only calculating? Try adding some capacitors to the voltage supply near the sensors, as noise might be an issue here. PS you can multiplex the output pins only, so can keep the sensors powered on. Enable external pull-ups on a single row, and then read all the columns. Similar to how a keypad is multiplexed.

Like most 8 bit AVR processors, the ATmega2560 has a current limit of 200mA, so as long as the sensors are attached directly to the microcontroller, it does not help you to provide more power to the board.

How are all these sensors physically arranged? How are they connected? Is there a breadboard involved? (Just thinking about noise and cross-talk) Also, looking at the datasheet for the sensor, and it specifies a 10K pullup, however, AVR internal pullups are generally in the range of 30~60K, which might be too little and causing slow rise times.

It is actually a little more nuanced than a 10k resistor, there is an allowable range based on the supply voltage, see equation 3 of page 16 http://www.farnell.com/datasheets/1888830.pdf and then based upon the value you pick for the resistor, you calulate a value for the capacitor. Either way it would help if you could share your schematic and the capacitor values just to verify that his is set up properly.

It might be best to just stop using internal pullups anyway as the resistor is being used as part of a low pass filter. By you using internal pullups you are betting the entire performance of the filter on the accuracy of that resistance value, which isn't particularly accurate or stable.

I was recently testing something else (an old phone) and found the internal pull-ups were insufficient for reliable operation. Wiring in 64 of them could be a pain (although you could get a few resistor arrays). How about using some analog multiplexers?

Have you tried decoupling your power supply with a 0.1uF ceramic and a 100+uF electrolytic?

@EdoPaulus it is really strange.. Another test you can do is to actually measure what is on the pin: this way you can understand if it is the sensors fault or the uC fault. Moreover at least as a test you can try to separate the uC power supply from the sensors. Or place the sensors in groups of 8, for instance, and separate the power (for instance place a diode (anode +5V or better a higher one, cathode Vcc of the sensors group) and a capacitor (between Vcc of the sensors group and ground) in the range 10-100uF.

Thanks for all the suggestions. I've added some photos and a schematic of the setup. My next plan is to add external pull-up resistors to all the inputs and not use the internal pull-ups. For the value of the resistors I'll use the equation mentioned by @jake-c ( equation 3 of page 16 link )

@Gerben I'm curious, though: How does one multiplex the output pins while keeping the sensors powered? I've read a bit more into multiplexing, but keypad multiplexing seems to only involve momentary buttons and diodes, no continuous power on ICs for every sensor. Is there maybe a link that gives more info on this? ty.

@EdoPaulus Have a look at this schematic I cobbled together. You enable the pull-up for only a single row at a time. You add diodes to prevent connecting to rows together. Because of the diodes you need a pull-down resistor on the columns to get a strong LOW signal. Make sure R7-9 are higher value resistors than the pull-ups.

Perhaps you have to put a 10k resistor between the signal and the ground of the hall effect sensor to avoid electrical disturbance.
Regards,
Guillaume

After seeing your schematic, I think the general problem here is that you need to more closely read and follow the datasheet for this part. A lot of times, when you are hobbling a project together at a small scale there are a lot of things you can ignore and get away with, but as you scale up, all the rounded corners start to add up. In this case, you can get away with 16, but once you start adding too more, it becomes too much. Let's go over a few:
Pull up resistors
Like I mentioned in the comments, relying on the internal pull ups is probably not a good idea. In my personal experience, they are only really good for adding a quick button input for debugging purposes. I'm not sure specifically what would cause issues only after 16 sensors. It could be that collectively internal pullups are subject to a different and lower current limit, but I'm not familiar enough with the internal architecture of the ATMega2560 to do more than just speculate.
Whatever the case, the best practice here would be to use separate external pull up resistors, within the specifications of the datasheet. (See equation 1 on page 13 of the datasheet.)
Decoupling Capacitor
Per the datasheet, page 17:

A 0.01-µF (minimum) ceramic capacitor rated for VCC must be placed as close to the DRV5023 device as possible.

This capacitor is referred to as C1 in the datasheet figures and is required. This type of capacitor is called a decoupling capacitor, and one of the things it does is provide a local energy storage, so that when the sensor starts pulling a little extra current, it doesn't have to wait for the regulator to respond, it has some local energy already.
Your schematic indicates a single 1uF capacitor on the output of the voltage regulator, however, there are no capacitors for the sensors. The one capacitor is only for output filtering for the regulator, and will not satisfy any decoupling needs of the sensor.
Filtering Capacitor
Referred to as C2 in the datasheet, this an optional capacitor to filter out high frequency noise. This isn't needed in most cases, in fact, per the datasheet, page 13:

Most applications do no require this C2 filtering capacitor.

However, your project might not fall into "most applications" and there are a few things specifically that worry me.

You have long wires that are basically acting as antennas that will capture any nearby noise.
You have long power lines running parallel to your signal lines which can cause stray inductance which leads to other interesting things. (With the thickness of the plywood separating them, this might not be an issue, but it is something to be aware of).

I would definitely try the first two ideas above to begin with, and only pursue this as a last resort. The  only way to know for sure if this is something you need is to stick an oscilloscope on the line and see how noisy it is, but that is not something you probably have handy.
Other Concerns
I'm just a little bit worried about voltage drop. Depending on the gauge of wire used, with all the sensors connected, at the end of a strand you might have a non-negligible voltage drop.
With that many wires running together into the Mega, there might be cross talk problems.
Another common problem with scaling up is that there is a higher probability of having faulty components. This is especially with this part which per the datasheet indicates that is particularly sensitive to ESD. It could be that there is a dead sensor that has failed in such a way that it is causing problems for the other sensors. Maybe go through and test all 64 sensors, 8~16 at a time to make sure that separately they all work, and that the issue only occurs when all of them are connected.
Other Ideas
Many other comments on the question have suggested a multiplexer and/or multiplexing and I will just briefly echo that here. Multiplexers are typically used in situations where you don't have enough pins and you want to split a single pin to multiple other pins. While that isn't an issue here with the Mega (it appears you have enough pins to do what you are wanting to do), there are other benefits that can be derived from multiplexing this.
For example, one thing you could do is split up the board into 8 - 2 x 4 chunks and then have a multiplexer (such as a 4051 or a 74151) local to each chunk. Then you would have just 8 short wires going into the multiplexer, as opposed to having long antenna-like wires heading to the Mega. This could improve overall signal integrity.

Thanks for all these elaborate replies! I've just tried adding external pull-up resistors (22k) but that didn't make the system stable. I'm now gonna try adding those decoupling capacitors. I'm thinking of using 0,01µF (with ±20% tolerance), or would it be better to go for 0,1µF?
If that still doesn't work, I'm gonna use some type of multiplexing. I have a couple of IO expanders at hand with I2C communication. Or would 4015s be better? (Then I can probably also replace the MEGA with a common Arduino UNO)

And yes, I tested all sensors separately and they work fine. Also, I indeed have no oscilloscope at hand.

Adding decoupling caps has made it stable! For now, I've just added one 0,1µF ceramic cap per row of 8 sensors, to test it. That seems to work. Later on, I will probably buy and add a 0,01µF cap for every sensor. Also, I'll still double check with internal and external pull-ups. Thank you Jake, and also thank you @gerben.


text:
How can I dim a 10w LED?
I'm trying to dim a 10w LED via Arduino PWM.
This is the LED that I have: http://www.banggood.com/10W-Warm-Pure-White-High-Brightest-Save-Power-LED-Light-Lamp-p-88169.html
Without knowing much about this stuff, I bought this (namely because it had LED, DIM, and PWM in its name): http://www.ebay.com.au/itm/121437119430?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
I can't get the eBay dimmer to work for love or money.  When I connect it to ground directly on the battery terminal, it goes off, which means the dimmer circuit is working.  I don't even know where to start with MOSFET dimming solution, but I think that the IRFZ44N MOSFETs are the wrong ones because they won't turn on with 5v power (they need 10v or something, but those are the ones I have on hand).
I can't seem to find any good guides on how to do this after stacks of googling, and to be honest, I don't even know if those LED's can be dimmed in the first place.
What do I need to make this happen?

Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read its datasheet and so you can get a guess on how it should work:

attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
attach the LED to the terminals LED+ and LED- (remember the polarity!)
attach a transistor to pull down the pin DIM
send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)
EDIT:
How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done

That sounds great :) A couple of questions though, what transistor should I attach to pull down the pin DIM, and how would I know what frequency the PWM is pulsing at?

Any n transistor is fine. Attach an NPN with a base resistor, or attach an nMOS and you don't need any resistor (i prefer the second solution). Any transistor is fine: I usually choose nMOS in a sot23 smd case, but you can choose anyone - the required power is really low - and possibly logic level - i.e. Gate Threshold Voltage lower than 2V. If you don't know how to attach it, just ask. As for the frequency, according to this arduino page frequency is s approximately 490 Hz or, on pins 5 and 6, approximately 980 Hz. You can measure it though

I don't know how to attach it :(  Can I take you up on that option of asking you how to attach it? :D

@LewisCianci I added the (very complicated) wiring scheme. You just need... A MOS. no external components, no difficult wiring, just an nMOS.

So, just so I have this clear, you're saying I can use the existing LED Driver I have, as long as I have an nMOS sitting in between the Arduino and the light?  The only MOSFETs I have on hand are these: http://www.banggood.com/10Pcs-IRFZ44N-Transistor-N-Channel-Rectifier-Power-Mosfet-p-953277.html.  Will they work?  I heard that these MOSFETs aren't "logic level" so Arduino can't even turn them on.  You're amazing by the way. Tell people in your vicinity that, and tell them that I am witness to this fact.

I don't think that MOSFET I linked to is even close to what you're saying.  I think this is what you mean? http://www.ebay.com.au/itm/General-Purpose-Transistor-BC807-BC807-40-SOT-23-PNP-PARK-5C-0-5A-45V-/181873441750?hash=item2a58807bd6:g:CSgAAOSwsB9V-mlS

Those are power mosfets, so you should probably save them for power applications ;) moreover as you said the threshold voltage is 2-4 V, so it's not recommended. For this tasks I usually use an AO3402 (I bought a batch of them some time ago, so I have it lying around). 100 pcs are aroung 4 AUD from China on ebay. If you want something from Australia, I found that element14 Australia sells some BST82 at 0.49$ for 5 mosfets (shipping fees are high, but sometimes local sellers allow you to buy from distributors like element14, rs, digikey... without having you pay the shipping fees). .. continue

So for instance this is from element 14, this is from RS, or you can check from any distributor. Just look for N-channel MOSFETS (usually under Semiconductors -> Discrete) with a threshold voltage under 2V and you are fine. Double check that the gate-source voltage can be at least 5V and you found your transistor. Now, small caveat. This is for the definitive circuit, because I THINK that your circuit should already work. If you want to double check if it .. continue

works properly BEFORE buying the mos, you can try to use the ones you have on hand because, looking at the typical curves on the datasheet (see figure 1) at 4.5V Vgs and a current below 1A you should have less than 0.1V, which SHOULD make the dim work. So just for a quick check you can use the IRFZ44N, but I suggest to change them as soon as possible. And.. The ebay transistors you posted are PNP, not nMOS, so they won't work. As for the compliment, thank you :) You made me blush ;) Glad if I can help you

Thanks again for all your help.  So, I found this FET at my local electronics shop (JayCar) and this is the datasheet: https://www.fairchildsemi.com/datasheets/2N/2N7000.pdf.  It talks about a threshold voltage max of 3v, but typical at 2.1v. Would that work? And if it would work, would it be ideal or not?

Well, this should work. Lower Vgs(th) are better, but according to the "On-Region Characteristics" graph with a 5V Vgs you get a 0.5V Vds for a current of 0.5A. Since the current is much lower, the voltage is lower too, So, yes, it should work.. It's not the best one, but since it is the only one you have it should work. Just try it and let me know ;)

I would suggest the CAT4101 PWM controllable constant current sink LED driver.  You might want 2 in parallel for the higher current.
They can deal with up to 1A each (theoretically) though they may get a bit hot at that current level - so it would be better to parallel them so they deal with roughly 500mA each.

Is there a board with this chip on it with io pins? Or would I have to just buy the chip and wire it manually?

Have you asked Google? There's some pictures of boards on there, so chances are there are boards available (I used to sell one but haven't made any for a while).

What is the advantage of using the CAT4101 over the MBI6651 the user already has?

I know for a fact the CAT4101 works well (and easily) with the Arduino. I have never heard of an MBI6651.


text:
Pelco D Library for Arduino
Does anyone know of any Pelco D libraries available for Arduino?
I already have a PTZ joystick controlling 3 PTZ cameras, but I would like to add an Arduino 'intelligent' controller capable of sending automated sequences of Pelco D commands according to various PIR triggers etc.

did you succeed in using the suggested library? Ho do I determine the address of the camera to be written in the sketch?

It looks like someone wrote a Pelco library. Check out:
https://github.com/Pixelbo/Pelco_And_Arduino

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


text:
RS485 bus voltage?
Does anyone know the voltage situation regarding multi-drop nodes on an RS485 bus please?
Nick Gammons RS485 article shows 2 different hardware configurations, one using 5v devices, and another using 3.3v devices, and I am fairly sure my Pelco PTZ CCTV system uses 12v.
But I have never seen anything mentioned anywhere about needing to voltage-match nodes on an RS485 bus.
So I am unsure whether the MAX driver chips isolate the RS485 bus voltage from the mcu logic levels.
Or do any lower voltage devices (3.3v or 5v) need logic-level matching to their MAX driver chips, which all need powering from the higher bus level (perhaps 12v)?
Basically, I wish to add an 'intelligent' arduino controller to an existing ptz cctv system.

RS-485 is a differential bus. As long as the difference in voltage between the two lines reaches certain thresholds the signal can be interpreted unambiguously regardless of the system supply voltages. Isolation (from ground loops) is not provided by default by the driver, but can be implemented easily enough.

According to my datasheet for the LTC1480:

–7V to 12V Common Mode Range Permits ±7V Ground Difference Between Devices on the Data Line

Absolute maximum ratings

Supply Voltage (V CC ) : 7V
Driver Input Voltage  : – 0.3V to V CC + 0.3V
Driver Output Voltage : ±14V
Receiver Input Voltage : ±14V
Receiver Output Voltage : – 0.3V to V CC + 0.3V

I am fairly sure my Pelco PTZ CCTV system uses 12v.

Judging by the above you would need to drop Vcc on the part involving your 12V gadget and use level shifters for the logic levels (if you used this particular chip).

I suspect that the line-driver Vcc may be using a commercial standard of 5v which we are not aware off.
The RS485 Vcc VMax is only 7v anyway, so presumably the thousands of different 12v RS485 CCTV devices on the market must use line-drivers chips with a Vcc of 5v because they were historically assumed to be interfacing to TTL logic levels, and therefore still will be for compatibility.
So for integration, I think any 3.3v logic nodes will require level-matching up to a line-driver chip which has its Vcc connected to 5v for RS485 bus compatibility.
Line-driver Vcc would not normally be a problem for any home-brew systems, but could offer a potentially serious gotcha if mixing 3.3v home-brew with existing commercial 5v equipment.
I had been expecting it to be an already known problem, but apparently not, so it would seem to be something worth being aware of.


text:
arduino flexbot drone connected in a wrong way
I have an arduino flexbot, I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.
I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.
But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?

The motors turning on is expected because or the reverse diode in the mosfets driving the motor.
Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.
To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.
To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).

I measured the voltage of pin 1 in U3 without connect it to the USB port and the lecture was 3.0 V, and connected to the USB it was 4.5 V, Does that mean that I can connect the battery directly?

It should have been around 5 volt, not 3.0.  Though at 3v I'd have expected the MCU to work. But maybe they set a higher brownout-detection value. The battery is connected to pin 5 on the pcb. So connecting pins 1 and 5 is the most convenient way of connecting the battery voltage to the 5v rail.

I tried three things, the first one was connecting the battery directly to the pin 1, that  made the motors turn on for a second and then the click came back and motors turned off. The second one was remove the connection between battery and connect the pins 1 and 5, only can hear the click. And finally connect pin 1 and 5 to vcc, only three motors worked less than a second. Please feel free to post all the answers that you want, I'll give a like on each one. Thanks

Sorry to hear, that didn't work. Any chance of finding a replacement part?

Well, actually in my country that's very hard to do, probably I need to do it throw internet and buy it in another place

http://www.ebay.com/itm/LTC3200ES6-5-LTSH-IC-REG-SWTCHD-CAP-5V-0-1A-SOT23-10Pcs-/291634898601?hash=item43e6cb66a9:g:g4wAAOSwcBhWZ30e maybe? Let me know if you need some tips on how to remove the old part and solder the new.


text:
Use command line to upload program through hex file to Teensy-LC
I want to make a standalone programmer for Teensy-LC in windows 8.1.
So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.
But the solution available right now is to send the Teensy Loader and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.
Also it would be better if this code can be burned in an installer format instead of the Teensy Loader.
Is there any way to make this work?
EDIT
My Teensy.exe does not have the option for program or reboot
The icons are not accessible

Does that mean my interrupts are disabled or there might be something else I am doing wrong?
My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe
If I turn off the Auto Mode, all icons go grey.

Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on his website. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The source code for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).
All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this forum post.
Loading Firmware Without Pressing the Button
When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

Connect the Teensy to the computer via USB.
Run teensy.exe (found in C:\Program Files (x86)\Arduino\hardware\tools)
Click the button on the left to select the hex file to load.
Go ahead and leave Auto enabled (this actually doesn't matter).
Run teensy_reboot.exe (also found in C:\Program Files (x86)\Arduino\hardware\tools, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)

I have editted my question explaining the problem I am facing. It would be great if you could help me out with what I am doing wrong in my present method.

@newbie2015 They are disabled because you have auto mode turned on. Click the green auto button and they will enable.

I turned off the auto mode. Now all the icons go grey

@newbie2015 I have added instructions, I was trying to describe it from memory (as I didn't have a Teensy handy) and I got it wrong. I got a hold of one and the correct process is described above.

Works perfect with this
But is it possible to make a bootloader without opening the Teensy.exe? Like it is possible that I send an installer from my end like a software update and the client does not have to go through loading the hex file himself. Have the hex file embed in the installer that I sent. Is that possible?

"pressing the reset button is not necessary for programming": This sentence is wrong if you have previously loaded a sketch to the Teensy which is compiled with USB Type: "No USB". The automatic reboot will only work if USB is running in the Teensy.

Sadly the accepted answer is incomplete and requires manual steps.
The reason why your "Auto" button is greyed out is that you did not execute the second executable that is required for that: "Teensy_Reboot.exe".
You find it on your disk if you have installed TeensyDuino.
First kill Teensy.exe if it is running (Important)
Then you write path and file of your Hex file into the registry:
HKEY_CURRENT_USER\Software\PJRC\teensy\dir
HKEY_CURRENT_USER\Software\PJRC\teensy\file

Then you start Teensy.exe
Then you start Teensy_Reboot.exe as a hidden process.
That is the solution of your problem!
It is a shame that Paul does not document his stuff.
NOTE: If you have previously loaded a sketch into the Teensy that was compiled with "USB Type: No USB" the reboot will not work and the button on the board must be pressed manually, but Teensy_Reboot.exe is still usefull because it enables the green "Auto" button in Teensy.exe.
NOTE: Teensy_Reboot.exe has a severe bug: If the Teensy.exe is not successfull because another program still had the Teensy CDC COM port open while you started Teensy.exe, the Teensy_Reboot.exe may run eternally consuming 100% CPU under some circumstances. I reported that bug in the forum of Paul but he never answered to my posting.

PLAN B:
The disadvantage of using teensy_reboot.exe is that you don't know if the programming was successful or not because sadly teensy_reboot does not return any usefull exit code.
So the better option (which requires more code) is to instruct Teensy.exe directly from your program. Therefore you need a TCP connection to localhost.
You find more details in this thread:
https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443
where Paul (once again) did not answer my question.

PLAN C:
You can even replace Teensy.exe with your own code.
Have a look at this project: https://github.com/Koromix/ty
Sadly this code depends on the huge QT library. Apart from that it may not work with future versions of Teensies.


text:
Check the value of character variable
I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:
const char* front = "front";
const char* back = "back";

eyeballs(front);
eyeballs(back);

void eyeballs(const char* frontOrBack){

if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);}//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);}//end else*/
}

Isn't this more suited to stackoverflow, since there's nothing Arduino-specific about C string comparison?

Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.
Instead, you can use the C style strcmp function, which is also part of the C++ library:
    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    }

Don't forget to #include <string.h>

Thank you. Is that the only issue with my code? For some reason the ARduino IDE isn't catching the error.

@Armandas thx, updated.

@MichaelRader Syntactically, there is nothing wrong with your code, so the compiler doesn't display an error.  What you are doing is testing whether the address of the character array frontOrBack passed into the function eyeballs  is the same as the address of the constant character arrays "front" or "back", which will always be false.

Can you tell me why you have the ! before strcmp?

@MichaelRader If you click on the link that I gave for the strcmp function, you will see (under Return Value) that it can return one of three values: >0 (e.g. 1) if the the first character of string1 is greater than the first character of string2; <0 (e.g. -1) if the the first character of string1 is less than the first character of string2; and 0 if the two strings are equal (which is what you are testing for).  Putting a ! in front of a variable or function in C or C++ is the same as testing for 0.  So I could have written this as "if (strcmp(frontOrBack,"front")==0)"

Another option would be an enum.
enum
{
   FRONT,
   BACK
}
.
.
.
   if (frontOrBack == FRONT)
   {
      // Stuff
   }
   else if (frontOrBack == BACK)
   {
      // Some other stuff
   }


text:
How to properly reverse DC motor direction with 2 limit switchws
Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.
const int sw2 = 2;          //Up Limit switch
const int sw3 = 3;          //Down Limit switch
const int ic1_2 = 8;        //TA8409S IN2
const int ic1_1 = 9;        //TA8409S IN1
const int enable = 10;      //TA8409S Enable (motor)
int sw2State = 0;
int sw3State = 0;

void setup() {
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, 1);
  Serial.begin(9600);
}

void loop() {
  tilt_up();
}

void tilt_up()
{
Serial.print("up Started\n");
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
  sw2State = digitalRead(sw2);
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
    Serial.print("sw2 pressde\n");
  }
}

void tilt_down()
{
  Serial.print("down Started\n");
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
  sw3State = digitalRead(sw3);
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
    Serial.print("sw3 Pressed\n");
  }
 }

If you want to reverse the movement you sould remember where you are going. This, along with the brackets correction suggested by @MikaelPatel and @NickGammon, leads to this code:
boolean moving_up = true;

void loop() {
    if (moving_up)
        tilt_up();
    else
        tilt_down();
}

void tilt_up()
{
    digitalWrite(ic1_1, LOW);
    digitalWrite(ic1_2, HIGH);
    if (digitalRead(sw2State) == LOW) {
        moving_up = false;
        Serial.println("sw2 Pressed");
        Serial.println("down Started");
    }
}

void tilt_down()
{
    digitalWrite(ic1_1, HIGH);
    digitalWrite(ic1_2, LOW);
    sw3State = digitalRead(sw3);
    if (digitalRead(sw3State) == LOW) {
        moving_up = true;
        Serial.println("sw3 Pressed");
        Serial.println("up Started");
    }
}

This also fixes recursion, which would make the processor run out memory eventually.

@Gerben as I also wrote on the other answer, even with the original code there SHOULD not be any recursion problem, since (hopefully) sw2 and sw3 will never be engaged together (and so calling tiltDown - which is only done when sw2 is engaged - should not call tiltUp. Anyway the original code does not have the behavior the poster wanted

void loop() {
  tilt_up();
}

void tilt_up()
{
...
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
...
  }
}

...

void tilt_down()
{
...
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
...
  }
 }

You are recursing here. loop calls tilt_up which eventually calls tilt_down which calls tilt_up and so on until you - rather quickly - run out of RAM.
Rewrite so that you are not doing that.

Also see what @MikaelPatel told you in your other question. You have the brackets in the wrong place.
  if (digitalRead(sw2State == LOW)) {

should be:
  if (digitalRead(sw2State) == LOW) {

No, he is not recursing too much because (hopefully) sw2 and sw3 will never be engaged together. The problem here is that the motor will move towards sw2, then hit it, reverse for one cycle and then go "up" again. See my answer to get what (I guess) is the behavior the OP wanted

@frarugi87 :  Your code certainly looks much better, as the main loop now controls which direction it is going.

I got it to work!!!
do not know if it is the right way ... but it works. thank you all for your input/advice. here is the new working code:
/*

 */

// set pin numbers:
const int sw2 = 2;           // Down limit
const int sw3 = 3;           // Up Limit
const int ledPin =  13;      // Pwr L.E.D
const int ic1_2 = 8;         // TA8409S IN2
const int ic1_1 = 9;         // TA8409S IN1
const int enable = 10;       // TA8409S Enable (motor)

int sw2State = 0;            // Down Limit State
int sw3State = 0;            // Up   Limit State

void setup() {
  // Setting L.E.D and Motor In, Enable pins as an output:
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  pinMode(ledPin, OUTPUT);
  // Setting limit switches pins as inputs
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  // Enables motor
  digitalWrite(enable, 1);
  //Starts program down
  down();
}

void loop() {
  // reads the state of the limit switches
  sw2State = digitalRead(sw2);
  sw3State = digitalRead(sw3);

  if (sw3State == LOW) {
    down();
  }
  if (sw2State == LOW) {
    up();
  }
}

void up() {
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
}

void down() {
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
}

void err() {
  digitalWrite(enable, LOW);
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, LOW);
}


text:
How to change Void with button press
I have 2 buttons and 2 voids (blink_slow) (blink_fast).
i need to be able to press button 1 and blink-slow void will run, then press button 2  and blink fast will run. none of my code works, any idea how i can do this?
const int btn1 1;
const int btn2 2;
const int led  13;

void setup(){
pinMode(btn1,INPUT_PULLUP);
pinMode(btn2,INPUT_PULLUP);
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
}
void loop(){
if(digitalRead(btn2 =LOW)){
blink_slow();
}
if(digitalRead(btn3 =LOW)){
blink_fast();
}

void blink_slow(){
digitalWrite(led,LOW);
delay(1000)
digitalWrite(led,HIGH);
delay(1000)
}

void blink_fast(){
digitalWrite(led,LOW);
delay(500)
digitalWrite(led,HIGH);
delay(500)
}

Start by correcting the obvious:
const int btn1 = 2;
const int btn2 = 3;
const int led = 13;

void setup()
{
  pinMode(btn1, INPUT_PULLUP);
  pinMode(btn2, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop()
{
  if (digitalRead(btn2) == LOW) {
    blink_slow();
  }
  else if (digitalRead(btn3) == LOW) {
    blink_fast();
  }

void blink_slow()
{
  digitalWrite(led, LOW);
  delay(1000)
  digitalWrite(led, HIGH);
  delay(1000)
}

void blink_fast()
{
  digitalWrite(led, LOW);
  delay(500)
  digitalWrite(led, HIGH);
  delay(500)
}

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.
Now your turn to improve this!

He's not using Serial, so it's possible to use the TX pin?
I'm not sure if it has internal pull-ups aswell (or other specifics), but in theory it's not wrong?
But yes, I would advise to use Serial for debugging, since that almost everything you've got.

Yes, using pin 1 (TX) is possible when not using Serial but may give issues later on when doing do. A good practice is to avoid pin 0 and pin 1 until the sketch is debugged. Not a mistake, more a potential risk. Good catch, Paul!


text:
ESP8266 is not responding
I have ESP8266, FTD232 UART, Linux mint 17.3 OS, Arduino IDE 1.6.7,
Following are the connections:
External Power source  ESP8266
  3.3 V                  VCC
  GND                    GND
  3.3 V                  CHPD
  3.3 V                  GPIO0

FTD232 UART  ESP8266
    RX         TX
    TX         RX

Plus FTD232 GND and Power Source GND are connected to make sure that there is a common reference.
I open the Arduino IDE and select Generic ESP 8266 board.
Open Serial Monitor:
AT command, no response..?
I have tried lots of different things found from web, even a new ESP8266, but no response.
Can anybody provide help...?

Is your serial monitor set to BOTH NL & CR?

Which model ESP8266?

Yeah Both NL & CR And Baud Rate 9600,
ESP8266-01 Model, the one with 8 pins and 2 GPIO.

Dont select 'Generic ESP8266'; leave the default IDE settings. Simply connect the ESP, open the serial monitor, and try sending commands at 9600 or 115200. Or you can use minicom to send the commands directly without the IDE

The ESP8266-01 will boot and show some boot up messages at baud rate 76800 before switching to the default configured baud rate of 9600 or 115200.
Try setting the baud rate to 76800 and reset the ESP8266 to see if you can see the boot up messages first to determine if your circuit is working. You might see something like this:

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

Just a note on the "initial" baud rate of these devices ... many ESP8266's use a 26MHz rather than 40MHz crystal - this apparently does not change the  clock rate of the MCU, but it does effect the boot loader baud rate ... what should be 115200 becomes 74880 (not a conventional rate, but is supported by arduino ide at least) the reason for this oddball rate ... 115200 * 26 / 40 = 74880 - I guess the boot loader is setting the uart for what it thinks is 115200 before the necessary "adjustments" for 26 vs 40MHz crystal is taken into consideration.

1.What firmware ? AT commands do not work in nodeMcu firmware.
Usually the AT firmware work to 115200 bps.
2.If your FTD232 works at 5V, you will need resistor between Arduino TX and ESP RX. ESP8266 only works at 3.3V.
3.Try esplorer - is a very nice tool to test ESP8266:
http://esp8266.ru/esplorer/


text:
Four Fast PWM outputs, in parallel
I need four Fast PWM signals for four different transistors.
I want to use timers 1+2 (pins 3, 11, 9, 10) so it wouldn't interfere with delay(...).
I tried setting the timers to Fast PWM mode, and applied different OCRnA/OCRnB values, but nothing really worked - at most, I managed to get two good PWM signals, one from each timer.
How should I deal with TCCRnA/TCCRnB, OCRnA/OCRnB to achieve 4 parallel PWM signals?
My latest attempt:
// Timer 1 Fast PWM setup: TOP=0x00FF, Update of OCRx at BOTTOM (0), TOV Flag Set on TOP
pinMode(9, OUTPUT); pinMode(10, OUTPUT);
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // Divisor 64
// Timer 2 Fast PWM setup: TOP=0xFF, Update of OCRx at BOTTOM (0), TOV Flag Set on MAX (0xFF)
pinMode(3, OUTPUT); pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22); // Divisor 64
// ...
int val = 200; // Desired PWM output
OCR1A = val;
OCR1B = val;
OCR2A = val;
OCR2B = val;

You should keep the timers running to max. Not make them reset when the timer value is reached. This way it will reach both values.

It would help if you posted the code. Note that there are two fast-pwm options. One that overflow at MAX and one that overflows at OCRnA.

Added example code. I tried many combinations, this is one of them.

That's a snippet - Please post a Minimal, Complete, and Verifiable example. Then we can try to help you.

That's all there is to it. The code was simply copied from my setup() function.
Regardless - I think the question is clear enough even without code examples - How should I deal with TCCRnA/TCCRnB, OCRnA/OCRnB to acheive 4 parallel PWM signals?

Double check the fast PWM selection. Does this actually use OCRnA/OCRnB?

What do you mean by "parallel"? Same frequency? Same duty cycle? Can you clarify why you don't just use one timer and route it to 4 transistors?

My latest attempt: - what does that attempt do? What do you want it to do, that it does not do?

You've put a bounty on the question, but don't seem interested in clarifying what the question is, exactly. No-one has attempted to answer, which maybe tells you that the question is vague. Even if you sketch on paper (and scan) or do a simple line-art drawing, that would help to clarify what "4 parallel PWM signals" means.

I want to drive four separate motors on a quadcopter, and thus the need for four separate and identical signals.

Basically, your question comes down to this:
"How to generate two PWM signals with only one timer."
(Once you've got that figured out, you could set up 6 PWM channels)
Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.
IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it)
IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

Setting the max
Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point).
We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.
The datasheet tells us this:

The TOP value can be assigned to be the fixed value 0xFF
  (MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

Setting a limit per pin
We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt
  request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0).
  All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

Extra info on compare
Below you can read some extra info on the signaling.
What actually will happen, depends on how the WGM

15.5 Output Compare Unit
  The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and
  OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the
  Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is
  enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is
  automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing
  a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
  according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max
  and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in
  some modes of operation (”Modes of Operation” on page 98).

Fast PWM
The actual settings are different per mode/modus, but for fast PWM we have:
Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0      0      Normal port operation, OC0A disconnected.
0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
              WGM02 = 1: Toggle OC0A on Compare Match.
1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

The table tells us we need to set COM0A1 and COM0A0 to 1.
COM0B1 COM0B0 Description
0      0      Normal port operation, OC0B disconnected.
0      1      Reserved
1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

This table tells us we need to set COM0B1 and COM0B0 to 1.
WGM mode
If it's all set up, we only need to put the PWM in the right mode.
Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
0    0     0     0     Normal        0xFF Immediate   MAX
1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
2    0     1     0     CTC           OCRA Immediate   MAX
3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F
Succes?
You should now be able to change the PWM's of these pins by setting the output compare registers of these.
Getting the double PWM of the other timer ready, shouldn't be much more different.
Be sure to set the right prescaler. Though it depends on a lot of external things.


text:
Logic level converter 12v to 5v
What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.
I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on ebay . Will it work like I want? Offer DIY solutions as well.

You're asking for an oxymoron there - "cheapest and best"? You can have the cheapest or you can have the best - which do you want? You can't have both. I think you mean "which is the best low-cost method"

And what in the car are you trying to connect to? To do what?

@Majenko, or something cost effective. Though, in this case it either works, or not. So any working low-cost method will do? But, this is more of a shopping question in this state. I believe anyone could/should make the call for himself when buying something. Your second point is spot on.

Use a car phone-charger. Especially if you plan to use it in a car, as the voltage in a car can fluctuate, and have huge spikes.

It would help us to know if your goal is to power the Arduino or to condition signals from the car so that they can be read by the Arduino. Since you're asking about a "logic level converter" I'm assuming it is the later. This could be a good question, please come back and clarify / add more information.

Well do you really want a logic level converter. Because a logic level converter can only handle not too much current.

Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

Power If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance here is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.
Get status If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you
Set status If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points

simulate this circuit – Schematic created using CircuitLab
Just one very big WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be only some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)

And... only after spending a lot of time I noticed that this question was from 2 years ago, and the reason why the question popped up is just because the OP did not accept an answer...

Use LM7805 linear voltage regulator to regulate to 5 v , it's all about 2-4$, you need LM chip and 2 capacitors, that's all :) and if you need 3.3 just search for linear voltage regulator

Don't forget a big-ass heat sink. Running from a car (up to 15V) you'll be dissipating a lot of heat.  The 7805 is not a good choice for car use.  Also he asked for "logic level converter" - though I don't think he knows what he wants ;)

I think too :) but let's explain to man :) and it doesn't need a big heatsink if he is powering only arduino from 12 volts, but i don't even know why he asks for that, cuz it's integrated into arduino board, and if he looked how to build standalone atmega328 he would know what he has to use

Direct connection is not the best idea. During certain moments there may be huge voltage spikes.

Well not really if he's connecting it to car's battery because a lot of addon devices operate on 7805 and i've never seen one that had problems with 7805 burning out or something :) it might be, but it's pretty rear :)

Your safest option is to use an opto-isolator. Connect the LED side in parallel with the load with a suitable resistor, then the transistor side becomes, effectively, a button connected to the Arduino.
As far as the car is concerned you have just connected an LED. As far as the Arduino is concerned you have a button connecting to ground.
It provides complete isolation of the car's electrics from your Arduino.

This is a good answer for a "logical shifter" as asked in the question.

This might be what you need — a multi-channel level shifter with input and output voltage ranging from 3.3V to 18V:
https://www.ezsbc.com/index.php/featured-products-list-home-page/ls2.html#.WqmSZ2aZNGU
It's no bi-directional: you'll need a couple of boards if you want inputs and outputs from an Arduino to 12V.

What are you trying to achieve?
It's simply unclear if you want to run the Arduino on 12v of the car battery. Or if you want to control the car-windows by hooking into them? Or if you want to read out your car using the arduino.
I'll go with the later since otherwise the question would be stated a little different.
Also, you're looking for something good/cheap.
You don't tell what type of car you want to connect to.
But I think this might help you out: https://www.sparkfun.com/products/13262
25€ isn't that pricey, compared to the car you're fiddling with... So you should go with a little quality (also, you don't need them in batch?).
While a bit subjective, sparkfun could be considered a better vendor than most e-bay suppliers. Both in documentation and support. And in this case, their price isn't that bad. (I'm not affiliated with sparkfun, I actually never bought stuff of them, since e-bay works well for me. There may be hundreds of other good/better suppliers, but this one popped up first on google)
Also, "hacking" your car can have serious safety risks.


text:
ESP8266 cannot read DHT22
I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.
Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
}

Nevertheless I always get the message "Failed to read from DHT sensor!".
Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.
Any ideas?

Have you got the right pin number?

Yes. Please check the link I posted in the answer below. I did not verify each pin but for example addressing pin 2 with the DHT library means you need to connect the DHT data to "D4" at your nodeMCU.

I found, that the pin mapping printed at the board of the nodeMCU does NOT match the pin mapping in the library/software.
Check out this issue/solution. It states the correct pin mapping (e.g. pin 2 is "D4" at the board) and provides also an according workaround. My DHT22s are working now... :-)

I had been racking my brain for over 16 hours trying to figure out why this library would not work. I tested the DHT on an Arduino and it worked fine but whenever I tried on the nodeMCU it failed to read or gave spurious data. That is untill I saw the above answer that is not mentioned anywhere. The pins for the nodeMCU are not the same as the Arduino. (I thought that by defining the pin it would be using the pin stated) This is false as the library is mapped the Arduino pins so this is something to look out for, for any nodeMCU/ESP8266 beginners.


text:
Using Temperature sensor arduino to trip off an ac device
Using Temperation through arduino to trip off an ac device?

My hovercraft is full of eels.

I assume that what you are trying to ask is something like: "How can I use a temperature sensor to control an AC (mains) powered device with an Arduino?" It really helps if you can state a clear question. Perhaps you could edit the post to add some detail and clearly state your question. Also as a new user it encourages people responding to you if you follow up on comments quickly.

@Majenko, I understand the frustration that comes with fuzzy questions, but in the long run I think we do better if we can offer constructive advice on how to ask good questions. Someday I'm going to get around to writing some Text Expander snippets so that I can make my suggestions when I'm in a good place and then reuse them :-)

Welcome to Arduino Stack Exchange. We hope you find this site useful. Please read How to ask a good question. Your question as it stands is very unclear.

Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.
Here is one link to an interesting project - if you are interested in brewing beer.
Cheers!

Nice project, Mikael. And @user16651 - these are the sort of details you should include in the question. For example, are you attempting to brew beer? Or not? Every bit of information helps get a better answer.


text:
Porting my project to multiple Nanos
I'm still fairly new to the Arduino world. I got myself a kit with a clone board  couple of months ago and have successfully prototyped the project and got it to the state I want it to be. I now want to create 5 - 10 working models of what I've done.
I'd seen on Amazon that I could get 5 Nano clones for about £10 and this seemed ideal to me. Until I saw that people were complaining that some Nano's aren't quite a direct replacement for the Uno that I have working. There's some kind of problem with loading the software from the IDE.
I really don't want to do anything more than just load my software onto the Nanos "As Is" using the IDE I already have.
Can anyone recommend what I need to look out for to ensure that the Nanos I buy will work this way please?

The Arduino Uno and Arduino Nano are fairly compatible.
Problems:

The board layout isn't the same, Nano's won't wield a classic "shield".
Nano's don't have a barrel jack.
Nano's (usually) have a micro USB connector. While the Uno has another one.
But, Nano's are smaller, withouth leaving out the USB connection.

But wait!
Microcontrollers of the same family are quite scaleable, Nano and Uno might even have the same micro on it! Be sure your Nano has the same Atmega328(P?) chip as your Uno.
Check if the pins you're using, are accessible on the Nano. Then you should be fine.
There is a little problem with cheap Arduino Nano's, I've bought 2, from 2 different vendors. They we're about 3$.

The first one featured a counterfeit FTDI chip. By installing the latest FTDI drivers, my FTDI actually got bricked. I had to undo this by using M_PROG or some EEPROM flashing tool to unbrick the chip, and install older drivers (which didn't corrupt it).
The second one featured an CH340G usb-serial chip. I had to download and install the drivers from a chinese website. But Windows wouldn't install unsinged drivers that easily. You have to go into advanced boot options mode and allow installing unsigned drivers.

Getting these Nano's working took me an reasonable amount of time. But they now are working quite well :)
It's something to take into account when buying cheap.
I wouldn't really bother for the alternative crystal, as long as they're 16Mhz. For time-critical behaviour, I wouldn't rely too much on your crystal.

... people were complaining that some Nano's aren't quite a direct replacement for the Uno

First, I hope you have understood that the Nano and Uno have totally different board formats. The Uno is the classical Arduino format. And the Nano is for breadboards.
Second, (and this will have to be a guess in lack of info or reference in your question) the Nano USB hardware on clones may differ and require another device driver. There might be other component selections to reduce the cost such as alternative a crystal for the oscillator, protection fuse, etc.
Cheers!

The project I'm doing is just controlling RGB LEDs. All I need is to connect to one digital pin on the board and supply it with power. I was hoping I could solder a wire to a pin, load the software then seal the entire thing in a box with power in and power/signal out.

An even cheaper solution is then to use Pro Mini clones. You would have to buy a FDTI or USB-RS232 module for sketch uploading.

Why use such a complex system when surely a little 8-pin ATTiny would be a better fit?

@Majenko the ATTiny looks interesting - but I doubt very much if it will be a simple replacement for my Uno. Can you point me to any further reading please?


text:
afmotor saying "servo does not name a type"
I have made a sumobot with an arduino, an afmotor shield and a 4-pin ping sensor when I upload my code it keeps giving me this error: "'Servo' does not name a type" here is my code.
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIGGER_PIN  A0  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     A2  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

 //speed variables for the left and right motor
int Lspeed = 180;
int Rspeed = 255;

//declaring the left and right motors and attaching them to
//their corresponding connector on the motor shield
Servo leftMotor;
Servo rightMotor;

void setup() {
  Serial.begin(115200);
  //sets initial speed
  leftMotor.setSpeed(Lspeed);
  rightMotor.setSpeed(Rspeed);
}

void loop() {
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  unsigned int CM = uS / US_ROUNDTRIP_CM;

  if (CM < 15 && CM > 0) {
    int iteration = 0;
    while( iteration == 0){
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      iteration = 1;
    }
    delay(600);
  }

  //starts motors going forward
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);

  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

Try #include <Servo.h>

As a kindness to people reading your question and trying to answer please include your code in the question rather than linking to it. Also, including the code ensures that it will stay available.

ok, but the insert code thing kept glitching out and just showing garbled text in varying bold and code

also im using 2 paralax servos (large)

Possible duplicate of Why does it say "Servo" does not name a type

You are creating Servo objects instead of AF_DCMotor objects. Change this:
Servo leftMotor;
Servo rightMotor;

to this:
AF_DCMotor leftMotor(1);   // Change these numbers to the correct motor numbers
AF_DCMotor rightMotor(2);  // you are using on the shield


text:
Use command line to upload hex code to teensy.ex
I need a command line implementation for uploading code to Teensy-LC through Windows 8.1 operating system
I know Paul has not released support for command line for Teensy-LC yet but i would like to know if any work has been done by anybody else in this regard.
I asked this and this. But all these solutions include

sending the hex file to the user.
Asking him to open Teensy.exe
Asking him to upload the hex file into Teensy.ex
Asking him to run teensy_reboot.exe

So is it possible to create an installer of a sort for this purpose which eliminates the user performing all these operations separately and a guided installer simply with Next->Next which does the entire job.
But I suppose that since Command Line installer is not available for windows I don't know if this is possible for impossible.
So if there is any way I can achieve an installer UI for Teensy-LC bootloader that would be perfect
Other viable option
If not that is it possible to make the entire process happen with the person not having direct access to the hex file.
Like sending a packaged installer or something
I am not sure how this would happen but if there is any possible way please help me out

You might be able to run the teensy.exe in the background, and press the right button using code

But this is a third party application I don't have access to. Secondly the question that you pointed me to does not have an answer yet. So even that person was not able to press button of a third party application in background. is there any other way?

Most applications use the windows api to create buttons. E.g. screenreaders are able to access this information, and read out button info, and also "click" on it.

This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in my earlier answer. My favorite one that I have used in the past is AutoIt. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.


text:
List of Arduino board preprocessor #defines
When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.
After a lot of hunting and some good fortune I found that the format of this definition is:
#define ARDUINO_<PROCESSOR-DESCRIPTOR>_<BOARDNAME>

Some are easy to guess (ARDUINO_AVR_UNO, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.
Question 1: Is there a list in existence of the possible definitions?
Question 2: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between BoardX-5V and BoardX-3.3V, and how is this distinction defined?

What do you need it for? It would probably be more useful to differentiate between processors (e.g. ATMega328), instead of boards.

I have a multi-node project that uses an Uno, a Leonardo and a  of Pro Minis. The code is nearly identical for the three versions but to ease debugging I want to be able to upload (or at least compile from) the same code for everything.

Switch on File>Preferences>Compile Verbose. Then build/verify and inspect the output. You will see the -D defines that are passed to the compiler. This makes it easy to determine the difference between your boards.

Grep did not work for me as shown. Found the path by looking at the verbose compiler output. I discovered the SparkFun boards.txt file on my computer was located here:
C:\Users\Jim\AppData\Local\Arduino15\staging\packages\sparkfunboards.1.1.10.tar\avr-1.1.10\boards.txt

The list of board symbols can be generated by this shell command:
$ grep board= boards.txt | cut -f2 -d= | sort -u
AVR_ADK
AVR_BT
AVR_DUEMILANOVE
AVR_ESPLORA
AVR_ETHERNET
AVR_FIO
AVR_GEMMA
AVR_LEONARDO
AVR_LILYPAD
AVR_LILYPAD_USB
AVR_MEGA
AVR_MEGA2560
AVR_MICRO
AVR_MINI
AVR_NANO
AVR_NG
AVR_PRO
AVR_ROBOT_CONTROL
AVR_ROBOT_MOTOR
AVR_UNO
AVR_YUN

The boards are defined by the "build.board" property in the boards.txt file.
mini.build.board=AVR_MINI

This property is used by the build recipe together with ARDUINO_-prefix.
-DARDUINO_{build.board}

Cheers!

+1, thank you for that list. It's a shame it doesn't spit out the dual-speed versions to remove any doubt, but this answers the question more than well enough.

The board property is the same for both versions of pro-mini while not for mega. Maybe boards.txt should be updated with distinctive names for the pro-mini variants, e.g. AVR_MINI_16MHZ, AVR_MINI_8MHZ.

For those looking - I was trying to find the define for a NodeMCU ESP8266 - so based on the info in this answer, it is ARDUINO_ESP8266_NODEMCU
Thanks !

Mikael has the right answer, but there are multiple boards.txt files depending on the installed boards with board manager,
modifying the command to:
grep board= `find . -name boards.txt` | cut -f2 -d= | sort -u

and running it from your base Arduino directory collects the whole set.

Adding detail to Bill's answer adding to Mikael's: The packages you download through the Board Manager reside in (as of 1.8.9 and many revs prior):

linux: /home/(your login)/.arduino15 You can also run Bill's one line script in your Arduino installation folder, to get the 'builtin' boards.

The first blank is the platform. This is "AVR" for AVRs, "SAM" for SAM-based Arduinos, etc. This is derived from the platform directory containing the core.
The second blank is the board. This comes from the entry in boards.txt in the core itself, and is the identifier before the first period.
There is no difference between compilation processes with regards to voltages; any speed difference is given in F_CPU and the board itself should not be checked for this.
So there is no definitive list, since the list is of arbitrary size due to its source.

This is true only when boards.txt doesn't define a build.board value and one is automatically generated by the Arduino IDE.


text:
Read information from Twitch's API and execute actions depending on the output
i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.
The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf
What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.

Break your problem into small steps and try to identify the success criteria for each step. So you might:

Try to set up the Ethernet shield and get it to respond to a ping on your local network.
Try to connect to a site outside of your network.
See if you can find some examples of using the Twitch API.
Try to replicate one of the simple examples.
See if you can get the Stream object that you want.
See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.


text:
Irrecvdemo program in or remote library gives fatal error #include<WProgram.h>
Whenever I compile irrecvdemo of or remote library it gives error saying that fatal error saying

no file or directory exists #include <WProgram.h>

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

Welcome! It sounds like you've got a syntax error in your sketch. If you include your code it will be much easier to help you.

#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}

You are using a very old library on a modern IDE.  The file that was called WProgram.h in IDE version 0023 and below is now called Arduino.h.  You will need to change any references to WProgram.h to Arduino.h instead.
Well written libraries do this with a #ifdef block:
#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

Can I know exactly where to edit and which lib file

I can't really tell you that, no, you will have to find it for yourself. You will need to find where you installed the library to and look in the files included with it. There may be only 2 - a .cpp and a .h file - or there may be more. There may be a "utility" folder with more in as well. The include will always be near the top of the files though, so it should be easy to spot. Depending on your operating system you may have the facility to search for files with certain words in them - for instance on Linux and OS X there is the grep command line utility. Not sure what is on Windows.

I found those files and copied that codes which you gave,I tried on CCP file h file...I tried all combinations and used older version of ide also but it did not compile...

@AdithyaPai What is the library you are trying to use?

IR remote library... Just using demo codes to get binary numbers from normal ir remote...by connecting ir receiver sensor tsop-...

@AdithyaPai WHAT IR remote library? Give me a link to it.

https://github.com/z3t0/Arduino-IRremote?e_pi=7%2CPAGE_ID10%2C5785360335

Well, that library already has all the right things in it and doesn't require any modification. Your code compiles against it perfectly. My guess is that you have a second, rather ancient, copy somewhere around that is conflicting. Search your hard drive for any old copy and eradicate it.