text:
VGAX library only allows 4 colors, library or hardware limitation?
I'm working with VGA DSUB-15 output, however VGAX only allows for 4 colors. I'm using an Arduino Nano that uses an 8-bit atmel chip, and I've seen many 8-bit computers of which have a bit more than 4 colors.

Is there any form or shape of VGA that uses composite output? The usual 15-pin VGA connector has separate analogue (baseband) signal lines for the red, green and blue components.

@HenningMakholm Ah, no. Will edit.

Google RGBI for more in-depth information about this phenomenon and how old computers with CGA graphics worked this way.

@winny RGBI has 16 colors.

@pipe Sure, but the principle of limited color space is transferable.

It's a memory limitation. The ATmega328 has 2 KB of RAM, and a 120x60 framebuffer at two bits per pixel (four colors) uses 1.8 KB. There's no room for more.

Thanks, is there any way i can get around this? Other than heavy optomization.

Use another microcontroller with more memory.

Are you using the Arduino to directly drive the VGA, or are you using a shield. If you're directly driving the display, I think the limitation is on the Arduino because with only 2kb or RAM, you can't really store all the pixel data. And the duino is also generating the high frequency vsync and hsync signals.

Try this: http://www.gammon.com.au/forum/?id=11608. Note: the code didn't work for me, but try it.

The link in the question leads to schematics that show the VGA output pins being driven directly by the digital output pins of the Adruino, with just some bridging resistors.

That's how you drive VGA directly without a shield.

So it may be possible to have more colours at a lower resolution.

That's what gammon said

The VGA interface uses full analog signals for Red, Green an Blue video. There is no limit to the color levels in the VGA standard.
However, it is not unusual to find that minimalist implementations of VGA in microcontroller products use Digital to Analog Converter (DAC) techniques with a limited number of bits of resolution.  For example, using two bits of resolution for Red and Blue, and three bits of resolution for Green so that the pixel information will fit into an 8-bit byte, etc.


text:
UVB sensing with Arduino
As part of the research I am involved with, the detection (not imaging) of UV (ultraviolet) sources, either emitters or reflectors is an important factor.
I am aware of the SparkFun UV Sensor Breakout - ML8511 component, which, according to the product specifications, has a decent broadband response across the UVA and UVB, with little amount of visible light.
Is there an Arduino component that only detects the UVB waveband (280nm to 320nm)?

The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.
Basically any device that has an I2C interface should work with an Arduino as long as you know how to interface with the device in the code.
If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"
The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.

source: Stack Exchange

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

sort: votes


text:
Ignore event until x minutes
I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.
Here is the code I come up with:
if (digitalRead(sensor_event)==HIGH)
  {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute > time_pushed+5)
                           time_set=0; // Unlock
                 }
               else
                 {
                        if (tm.Minute >= 55)
                          time_pushed=0;
                        else
                          time_pushed=tm.Minute; // Set global volatile min value

                        print("Sensor event");
                        time_set=1;
                 }
      }
  }

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.
The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).
Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.
Thanks

Use the millis() function instead if you can accomodate a rollover after 50 days.

Take a reading of millis() at the start time.
time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.

Assuming all three are unsigned values, if(current_time - start_time >= timeout), then rollover becomes irrelevant.

This is exactly what I looking for so the rollover never cause a problem, yes the device will run over 50 days. But in your example let's say the timeout is 1 minute 10000 mS. If current_time eg 9991512 and the start time 9990512 and lets say it overflows back from 9991512 -> 0000000 how is this helps me?

@catkillr: Arithmetic on unsigned long is performed modulo 2^32, so the difference current_time - start_time is always correct modulo 2^32 even if there is an overflow.

See http://www.gammon.com.au/millis for a detailed explanation of why this works.

Calculate target time, rollover if necessary and check if time is already passed that point. As long as you are checking the time multiple times per minute you shouldn't run into any issues.
if (digitalRead(sensor_event)==HIGH)
{

  if (RTC.read(tm)) {

          if(time_set)
            {
                   if (tm.Minute >= targettime)
                       time_set=0; // Unlock
             }
           else
             {
                    targettime=tm.Minute+5; // Set global volatile min value
                    targettime=targettime % 60;

                    print("Sensor event");
                    time_set=1;
             }
  }
}

The proper way to do that depends on whether the event is guaranteed to
happen at least once every 49.7 days. If this is the case then, as
Tom Carpenter suggested in a comment, you can just test for
now - last_event >= hold_time:
void loop()
{
    uint32_t now = millis();
    static uint32_t last_event = -hold_time;

    // Detect the event if it did not happen in the last five minutes.
    if (now - last_event >= hold_time
            && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        last_event = now;
    }
}

If you can have 49.7 days without a single event, then this approach
fails because last_event is ambiguous. The simplest solution is
probably to implement a state machine with only two states, as the event
detection is either “on hold” or it is not:
void loop()
{
    uint32_t now = millis();
    static bool on_hold;
    static uint32_t last_event;

    // Remove the hold after five minutes.
    if (on_hold && now - last_event >= hold_time) {
        on_hold = false;
    }

    // Detect the event.
    if (!on_hold && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        on_hold = true;
        last_event = now;
    }
}

Now I would want to insist on a specific point: in either approach
the millis() rollover is not an issue. The choice
between the first and the second approach depends solely on the maximum
time between the events, not on how long the program is meant to run.

Just to save a lot of headaches for everybody who wonders here and still have  a problem with this code:
uint32_t hold_time = 1*60*1000; // 1 minute will never work

uint32_t hold_time = 60000; // 1 minute will work

You must define the value as an EXACT number, not putting in multiplication and rely on the compiler to calculate it for you.
Probably because it's unsigned long and screws up something with the multiplication but with the first example you will be put on hold for days, maybe forever.

See Integer arithmetic and overflow. You can make it work by forcing the first item to be long: uint32_t hold_time = 1L*60*1000;

Don't bother with the RTC, just use millis().  Or just convert the time in hours/minutes/seconds to a single number in seconds (i.e. UNIX timestamp) and use that.  Then use these time comparison macros:
#define time_after(unknown, known) ((long)(known) - (long)(unknown) < 0)
#define time_before(unknown, known) ((long)(unknown) - (long)(known) < 0)
#define time_after_eq(unknown, known) ((long)(unknown) - (long)(known) >= 0)
#define time_before_eq(unknown, known) ((long)(known) - (long)(unknown) >= 0)

Then do something like this in your main loop, with a variable unsigned long sample_timer that's initialized to 0 at the start of your program:
if (time_after_eq(millis(), sample_timer))
{
    if (event)
    {
        sample_timer = millis() + 5*60*1000;
        // handle event...
    }
}

These time comparison macros will properly handle overflow if you use unsigned long for your timestamps.

−1 because this can lead to signed integer overflow, which is undefined behavior (i.e. a bug). But you can fix the macros by doing the subtraction before the cast.

Really? Then give the Linux kernel your down vote because that's where these macros came from: http://www.makelinux.net/books/lkd2/ch10lev1sec3

You found a bug in the Linux kernel. Congrats. But I would advise that, before reporting it, you make sure it hasn't already been fixed.

Update: I checked the current Linux kernel and, as I suspected, the bug has already been addressed. The fix, jiffies: Avoid undefined behavior from signed overflow, was committed by Paul E. McKenney three years ago. I urge you to read the commit message, as it explains in more detail what I wrote in my first comment. And notice that McKenney’s fix goes exactly along my suggestion: subtract before cast. Also, when you know you have posted a buggy answer, it is good practice to either fix it or delete it.

It's also good practice to comment before down voting.

I don't understand why you write that. Here is the only thing I found about commenting to explain a downvote, and it does in no way imply that the comment should be written before rather than right after the vote. I have tried to be constructive in all my comments, but this remark of yours sounds to me like pure angry rant.

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


text:
How do I find names of components I don't know?
I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

You could try adding a picture to your question, and ask us. (but please mark the ones you don't know).

I wouldn't want to post a new question for every single component I don't know

@Max So maybe put it in this question?

In your kit, you have a list of all provided components. Just google those you don't know and you should find images that match your kit. This should work.

The Arduino webpage has a section about their Starter Kits, including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for actuators (there are more categories to the left of the image).
There is a blog by Aaron Eiche, Arduino Starter Rundown, that if you scroll down, there is a chart that labels the main components.
There are several websites that have pages that identify components by image - an example is the uCHobby webpage Identifying Electronic Components, with pictorial menus of the main types of components.
In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.

A slightly more general answer to this question would be to browse the catalogue of a component supplier. Printed catalogues seem to be becoming rarer (Maplin used to sell a catalogue, but it seems to be discontinued this year), but RS and Farnell still seem to have printed ones.
I'm not suggesting you find specific components by searching the catalogue, but skimming through a catalogue will give you an idea about some of the components that do exist, and will help you to narrow things down a little.


text:
Why isn't this pushbutton program working?
Here is my circuit:

and here is my code:
int LED = 13;
int BTN = 7;

void setup() {
pinMode(LED,OUTPUT);
pinMode(BTN,INPUT);
}
void loop() {
if(digitalRead(BTN) == HIGH) {
digitalWrite(LED,LOW);
}
else{
digitalWrite(LED,HIGH);
}
}

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?

Where did you base your button connection on? To me it seems that it's always connected to GND. Pressing the button will send the electricity to GND, through the resistor, it's unlikely that it goes into the pin, since it has higher resistance (as far as I know).

It may be worthwhile to search up some electronics tutorials and/or Arduino basic tutorials.
When following a (good) tutorial, they would explain how to set up the electronics (and why it works).
Just connecting stuff in a way you think will work, is going to cause headaches or worse ;)

Max - A really useful site for you might be https://123d.circuits.io/ which allows you to blow up components virtually.  It lets you simulate your circuits (and code) and means you don't fry real Unos, which you may well do.  I've never yet managed to fry every component in a circuit on 123d, but I keep trying :)

I have a book which has this circuit...

Your code and schematic both seem to be wrong.
Try out this schematic:

And then code:
const int kPinLed = 6; // LED - Pin 6
const int kPinBtn = 7; // Push Button - Pin 7

void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
  {
    digitalWrite(kPinLed, HIGH);   // LED ON
  }
  else digitalWrite(kPinLed, LOW); // LED OFF
}

Paul is correct. Your button is wired wrong. The GPIO pin should be connected to the same side as the resistor. Also the button needs rotating through 90 degrees.
Also check how your LED is wired up. At the moment it looks like it's set up so that the GPIO sinks the current (LOW turns the LED on) yet the LED looks like it's connected the wrong way around for that.
In fact, I can't actually find anything right about that circuit...

And button seems to be shorted in breadboard too

Well spotted.  Updated answer.

The Input port is going to always be at Gnd, because you have connected it to ground.  Sorry to put it in such basic terms but this is the way I understand it.  It needs to be more difficult for the output of the button to get to ground than to get to the BTN pin of your UNO.  So put a bigger resistor (1K-10K) in place of your yellow wire between the button and ground.
And your LED is the wrong way round in the diagram.
(And Majenko is a quicker typist than me! :) )

In addition to the answers from Matt and Majenko, you code uses the wrong pin for the LED.
You have int LED = 13; whereas your LED is connected to pin 6.
NB: Pin 13 is connected to an LED soldered on to the Arduino board - as seen in the image below.

authors: Максим Зверек


text:
Circuit with buzzer not working :(
so I have a circuit with a buzzer and a resistor:

This circuit should be working, but for some reason the buzzer doesn't sound. I pushed the buzzer into the breadboard as hard as I could, I put the + side to positive and the - side to negative but it still doesnt work :(. How can I fix this?
Quick curiosity question: When I was doing electricity in school, the teacher just called the buzzers 'buzzers' but when I started doing arduino I noticed that the arduino community seems to call them 'Piezo buzzers/piezo speakers'. Is there any significance in the word 'Piezo' and should I start referring to them as 'Piezo buzzers' myself?

A buzzer that is not a piezo based device is a coil relay in which the coil circuit is normally closed. When the buzzer is energized, the relay activates and then opens the circuit, deactivating itself. The cycle repeats, creating vibration in the moving part of the relay. Piezo devices use a crystal material which vibrates when electricity is applied. The crystal is often attached to a membrane to amplify the sound.

In the image you provide, you've properly connected the GND and 5V power from the Arduino to your "buzzer". When you apply power to the Arduino board if you have an active beeper it will begin beeping. If instead you have a passive beeper (aka speaker, headphone) you might hear a slight click or pop. As others have said, you need to connect the positive lead of your buzzer to an I/O pin on the Arduino if you wish to control the buzzer.

There is two kinds of buzzers - active and passive

Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this

It may be difficult to detect, but if the buzzer in question is a passive buzzer, you should be able to hear a click when it is activated and possibly one when it is deactivated.

Yes.. fred is right.. you can hear a dup dup sound...

are you saying that rather than connecting the wire on the positive side of the buzzer to the power, I should connect it to one of the pins instead and control it with code to make it work? Also, how can I tell if my buzzer is active or passive without making it work?

Thats a hard question. Generally active buzzer comes with a paper cap on top. But this wont b true always. Yes.you should connect + of buzzer to a pin of arduino and - of buzzer to ground

You've already tried using it as an active buzzer. It didn't buzz, so it is either passive or faulty. The next test would be to connected to an output pin and set it alternately high and low, delaying a few milliseconds after each change. If it buzzes, it's passive (all Piezo's I've used have been passive). If not there is a fault, which could mean a broken piezo or it could be one that needs a higher voltage than your board supplies.

Recently, I was trying to find the difference between an active and passive buzzer. I connected a passive buzzer to voltage. It started heating up and smelling. I do not recommend connecting it like that anymore. Below, I am posting a link to ebay where you can buy 5 active 5V buzzers at a very affordable price. http://www.ebay.com/itm/172078418182?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

Try the toneAC library if it is a two pin piezo speaker... It generates weak alternating current, using two arduino pins. Your piezo will last longer. Works like old tone library. Remember to put a 100 ohm resistor in series :)

Buzzer coils get locked if a higher voltage is applied to the terminals - it could be 5-9 V. Once it gets locked it won't work even if you put direct battery to it. The only solution is to first take out your buzzer and give it a reverse voltage that will get the coil out of the lock position, then put 180 Ω resistor and run. It will work and it will never lock again.

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


text:
Arduino Due SPI will not loop
Help please
I am trying to connect an Arduino Due via a SPI bus to a MAXIM31855 thermocouple sensing chip. I am using Arduino IDE version 1.6.11.
The problem I am having is that the code will only read the SPI bus once, it will not loop, regardless of how many times I call the function to read the SPI bus.
I have connected the clock and the MISO to the pin header just below the SAM processor chip its labeled SPI and I have connected the CS to pin 4.
Each time I press the reset button on the Due, the SPI will read once. I have confirmed this by using a Salae logic analyser. The Due doesn't lock up as other functions continue normally, it simply will not repeat the SPI read.
The 4 bytes that are returned from the Max are consistent with the specification for the chip as are the timing of the clk (4kHz) and the MISO logic levels (there is no MOSI in this MAX chip).
If anyone has a clue as to why this will not loop I would appreciate their input.
Cheers
#include <SPI.h>
//Give convenient names to the control pins

#define slaveAPin 10
// set up the speed, data order and data mode
SPISettings settingsA(4000000, MSBFIRST, SPI_MODE1);

void setup() {

  Serial.begin(9600);
  pinMode(slaveAPin,OUTPUT);
  SPI.begin(slaveAPin);

}

uint8_t  val1, val2, val3, val4;

void loop() {
// read four bytes from device A
 Serial.println(ReadTemp());
 delay(1000);

 }

uint8_t ReadTemp(void)
{
  SPI.beginTransaction(settingsA);
  digitalWrite (slaveAPin, LOW);
  // reading only, so data sent does not matter
  val1 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
  val2 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
  val3 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
  val4 = SPI.transfer(slaveAPin,0x00,SPI_LAST);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();

  return val2;

}

Where's your main function?
Does it have a forever loop?

Call the SPI Transaction in void loop and then print val2 and let us know the results. I don't know if Serial.println can take functions as an argument.

@ammar.cma it's not taking function as an argument. It's taking result from function call (type is uint8_t).

Check this bug report; https://github.com/arduino/Arduino/issues/1406. Might need to update the Arduino IDE with the latest Due version.

@KIIV yeah. Function call :/


text:
Power measurement on Pins
as a project I have to build a sensor hub based on Arduino. I need a couple of sensors like gyroscope, barometer, etc. This is no problem so far. The problem arises when it comes to power measurement. We have to measure the power consumption of the Arduino AND all the sensors. Sure, I could use a sensor like the Adafruit INA219 sensor. But this only gives the total consumed power of the Arduino and the sensors.
Is it possible to measure the energy, say, for every pin on the Arduino?

"We have to measure the power consumption of the Arduino AND all the sensors."  and "But this only gives the total consumed power of the Arduino and the sensors." So what's the problem?

For these sensor most/all pins are just for communication, so they hardly use any power. The only pin of interest is Vcc. You can deduce the power usage by temporarily removing the sensors, and seeing how much the current is reduced (though this can be inaccurate, as the arduino may behave differently when a sensor isn't present). Or connect the current sensor between Vcc on the Arduino, and Vcc on the sensor. You can also, just get the approximate values from the datasheets.

You can put a 1Ω resistor in series with each of the 5V supplies to all the sensors, then link the sensor side of each one to analog inputs on the Arduino. Measure the voltage drop, and there's your current.

@JRobert: Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with.

adur, are the measurements to be made by the program using analog input pins, or by a person with a DVM?

"Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with."
"it possible to measure the energy, say, for every pin on the Arduino?"
You ask if it possible to measure the energy- yes it is-or at least an approximation. The basic solution is as follows. Suppose you want to find the energy consumed by some component at one pin.  Energy is measure in joules. For an electrical circuit we the amount of energy (consumed in 1 second) is given by the formula
joules=current X voltage.
Lets consider the case with one sensor first , lets refer to this as sensor A.
The amount of energy that electrical component consumes in some time duration is by sensor A is:
joules (use by sensor A)=current X voltage X time duration sensor A is on
Now to make this formula applicable to your answer- we can replace voltage by the average voltage, and current by average current, since this is mathemtically equivalent, that the component is on for, and the time duration would be the time the component is on for. So the equivalent formula that can be used is
joules= average current X average voltage of sensor A during time duration X time duration sensor A is on
So for example if the sensor is only ever used for 50 minutes for all time throughout your project- and the sensor is turned on at the arduino pin for 1 second for every minute of that 50 minutes then the energy used by that sensor on that specific pin is equivalent to leaving the pin on for 50 seconds at the average voltage and average current of that sensor. Say the average voltage is 3v then the energy and average current is 20ma. Then the energy used by that sensor is thus
3v*0.02amps*55 seconds=3.3 joules.
Thus to get the total energy (if there were two sensors A and B) you would just need to sum
(joules (use by sensor A)= current of A X voltage of A Xtime duration sensor A is on)+(joules (use by sensor B)=current of B Xvoltage of B Xtime duration sensor B is on.)
Similar formula for more sensors.
To sum up- basically you would need your arduino program to keep track of how long each sensor pin is on (assuming high voltage turn on the sensor and makes it use power, low voltage turns off the sensor or make it use no power)  for each of the time duration in the formula for the duration of the project, you would need an estimate of the average voltage and current (e.g. from data sheet) or another way. Then you would need to use the formula in your code to compute the energy used by each sensor and the total energy.
If you have a way to measure the voltage and current fast enough then you could use them measurement instead of using average value as explained above-but I guess using averages is the easiest way to do it.
.

Okay, thank you. That is what I was afraid of. But I think I will stick to this solution. Tank you :)


text:
Will this SensorHub work?
As a project I have to build a SensorHub with multiple sensors. I am relatively new to the Arduino and circuit world, so I need a little help.
The Goal is to build hub with multiple sensors and to be able to measure power consumption of the entire thing and log the data from all sensors.
So I came up with the following part list:

Arduino Uno (Rev3)
Adafruit 10-DOF IMU L3GD20H + LSM303 + BMP180
Adafruit Ultimate GPS v3
Adafruit VCNL4010 Proximity and Light sensor
Adafruit INA219 High Side DC Current Sensor Breakout
Adafruit MicroSD card breakout board
of course breadboard, powersupply, calbes, etc.

Everything is connected like this:

My question is now if this thing will work as I expect. With the 10-DOF, GPS and VCNL4010 I'm pretty sure. They work all with I2C on different addresses and all of them need 5V.
The question is now if I can measure the needed power with this setup. Or does the INA219 need power to be able to get the power to the Arduino? Do you see any problems?

By “measure the needed power”, do you mean like with a DVM?  That is, by manually taking meter readings of currents and voltages?

The INA219 breakout will pass current, even if it doesn't receive any power itself.

So, do you think this will work?

The current sensing part; yes. I haven't really looked at the rest of the circuit.

Okay, thank you. Let's see what others say to the remaining parts :)

Well, in the schematic both the red and black wire are connected to the GND pin on the INA219.

I was a bit worried about the I2C pull-up resistors on the boards, as  the INA pulls up to 5 volt and the other two boards run on 3.3V. But the VCNL doesn't mind 5v on it's I2C pins, even though it runs on 3.3V. And the 10-DOF uses a buffer between the chips and the I2C pins on the breakout. So that's fine too.

Marked this answer as solution since the solution is in the comments. Thank you :)


text:
XBee Shield Arduino External Power Issue
The XBee part of the entire thing works flawlessly no matter how things are being run.
Equipment:

Laptop
Arduino Uno
Sainsmart XBee Shield
USB XBee Explorer
2 x XBee Series1 modules
Terminal software

What we are doing:
Send data through terminal software using "XBee 1" on a USB explorer, to remote "XBee 2" which is connected to Arduino Uno using the Sainsmart Shield. Arduino sends a reply which we see in the terminal software. (This is basically just using the two XBee modules to eliminate physical RX-TX connections in a simple point to point communication.)
This configuration works perfectly fine when the remote Arduino + XBee are powered by a USB port of a PC (doesn't have to be the same PC - tried with separate PCs, one powering the transmitter and other the receiver.)
The problem:
This configuration does not work if the remote Arduino + XBee are being powered by:

9V Battery (brand new)
12V, 2A adaptor
5V, 2A mobile charger directly supplying through USB

BUT it starts working after pressing RESET (sometimes, very rarely, we have to press RESET 2 or 3 times but it does start working) and keeps working while the supply is not disconnected/turned off.
Important Note 1: As mentioned earlier, the remote XBee always works perfectly fine in all of the above cases as shorting RX/TX shows that the data perfectly and flawlessly echoes back.
Important Note 2: I don't think that the Arduino isn't starting up, as to check that I am blinking pin13 LED which always starts working fine in any of the scenarios listed above.
Please help. Having to RESET every time after power up makes the whole thing pretty useless for any real world application.
When I say that does not work, I mean I don't get a reply from arduino when I send a query over terminal.
After pressing Reset, it begins working, i.e. I start getting a reply.
But I don't think that Arduino isn't startup because Pin 13 LED blinks as expected which is something I put just to check whether Arduino code starts running.
As far as circuit, it is nothing but XBee Explorer USB plugged into my laptop and arduino with ready made XBee shield plugged into another USB port (which is when it works). Powering Arduino from a USB port of a different PC also gives no issues.
Only when Arduino is powered by external power source like an adapter or phone charger or 9V battery (literally tried all 3) does it not work automatically and I have to Reset the Arduino after which it starts replying.

You think you have described your system, but you really didn't. Either draw a circuit diagram, or find a simple setup which still reproduces the issue (and draw a circuit diagram of that).

I would also add more details to what you mean by "not working" (Is the Arduino operating system booting? Can you talk to it on the network? etc.)


text:
How can I read Data from 150 Arduino Serially to a Single Arduino to display it via serial port.
I know that Arduino nano/Uno has one Serial port to read serial data. But if I use software serial can i read more than one serial data.
I have 150 Arduino's working on a project(Can be reduced to 50 if required) these arduino will generate serial data (150 serial data as of now). I wanna connect all these 150 serial data to a computer through a single COM port. How can i make it possible.

That's... not realistic. On a uno or with rs232 as the chosen protocol.

How much data is being sent, and how often? Also, what is the "computer" that these Arduino's must talk with? Another Arduino? Or a PC?

Check out the Chainduino.

This should have been closed as a duplicate of existing questions on EESE, not migrated.

If each source generates messages at a low enough rate, you can put them all in series.
Each Uno has a serial input, and a serial output, and they are all chained. Each Uno labels its message with who it's from, and passes on received messages unchanged.
Obviously this means that if you used (say) 9600 baud, or approaching 1000 bytes per second, each device would only be able to source 6 bytes per second of message.
If that's not fast enough for your application, then you would need a higher baud rate at the COM port.

You can attempt to connect your devices in a loop, if you are insisting on using a single serial port for each. How well all that works will depend on a lot of things.

simulate this circuit – Schematic created using CircuitLab
I have no idea what your computer is, but this is a common mention to string multiple units together where they only have a single serial port each. The software in each unit will need to pass along messages that belong to other units and you will have to device a method for achieving that process. But it can work. Message delays will exist, of course. And with from 50 to 150 units, you may find some serious frustration. But if the needs are modest, you may be able to get by with this mechanism.


text:
NodeMCU ESP8266 on Arduino IDE doesn't detect Wifi
I am using a NodeMCU 1.0 v3 and I am trying the example sketch (wifiscan) but it just doesn't pick up any AP in the house. My phone and laptops etc are able to pick up the APs though.
Other sketches upload and work fine but the wifi aspect of it doesn't work. I even got an LCD sketch to work properly but it isn't able to find any access points or even join any access points. I have been trying to get it to work for hours now.
I first tried using the latest Arduino IDE (1.6.12), then I uninstalled and tried using 1.6.1 but no luck. My upload settings are NodeMCU 1.0 (ESP-12E module), 80Mhz, 115200, 4M (3M SPIFFS).

Your router might be using 5GHz Wifi which the ESP8266 doesn't support but your other devices likely do. Try setting your wifi network to 2.4GHz.

Thanks, I read on a forum somewhere that it could be the issue but when I checked my wifi it is indeed set at 2.4GHz. I also tested the esp8266 in an area with loads of APs so I ruled that out as an issue.

My gut feeling is that your hardware is just flakey.
I have one NodeMCU 1.0 that occasionally works, and occasionally does not.
On that one, it requires power cycling (unplugging and replugging) it a couple of times for it to start working.
The Arduino ESP8266 core is pretty solid, and wifi support should just work in it.
Just to make sure, you could post your simplest sketch which doesn't work (one that lists AP's, so that it can't be a ssid/password kind of issue), so people can check if there's a problem in the code..
Also, to be really sure, you could check your power system. NodeMCU has a 5v to 3.3v converter in it, and a usb plug, so that part should be ok. How many amps is the USB power supply rated at? If it's very low (<250ma) it could be an issue. You can also try adding a capacitor (something decent sized, >220uf at a random guess? I tend to go for ~1000uf) between gnd and 3.3v, and one between gnd and 5v pins. Watch polarity of-course, and double check, you don't want to short the power lines :)
There's a very small chance stabilizing the power in that way might help..

Thanks for the answer cranphin. I suspect it may in fact be due to a faulty unit. I used the example sketch that lists AP's but that didn't return anything. I also tried powering it separately using a 3.3v 2A supply. I think i'll just use it as I would a Arduino Pro mini because all other sketches except anything to do with wifi works. I'll add some caps as you suggested and see if it helps. Thanks again.

My DHCP table was full. I rebooted router and added more values for dhcp range (192.168.1.100-192.168.1.150) and the device now connects.... took me a day to figure this out.


text:
Connect an Arduino directly to RGB LED strip
I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB Strips. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

one cable on 12V
one cable on G
one cable or R
one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

https://learn.adafruit.com/rgb-led-strips/usage

+1 for the Adafruit tutorial, it will cover much more than is possible to explain in a SO answer. I've found this other source http://www.engineerathome.com/elektronica/how+to+build+an+rgb+led+strip+controller/33 to be useful for making my RGB controller.

if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1

Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.
You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).
Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).
As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.

Daymn, IRLxxxx is always logic level? I keep buying the wrong stuff (since I'm more of a programmer than an ee). However, my rgb-driver is working, and it's using IRF3205’s

Yes, the L is for Logic level FET. The IRF's are often also usable, depending on specs. The IRF3205 has a threshold of 2.0-4.0V, so is just about OK for a 5V chip like the Arduino. Not for a 3.3V chip like on a Due or chipKIT board. It's not really fully on till around 7V_GS though, so you'll be suffering some losses from it.

https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1
You can use the logic level ports to drive Logic level power MoSFET switches or use a RS85 IC to communicate to a DMX-512 interface special effects driver to RGB.
Other options include
Use 5A PWM 3channel dimmer purchased on line with 12V- 14.5Vmax PSU >40W per 5m reel string .
e.g. Laptop universal 65W charger ($30) with 14V -16V setting. and long AWG18 wire with 1-2V drop
(comments)

You start by improving your question with details on what you want to do with the interface.
if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard

The RS485 thing is smart, since that's how "the professional LED strip installations" work. But those strips/controllers may be more expensive.

"if you want guidance shopping for a LED driver , just say so or ask for details" please note that that isn't really the aim of stackexchange (http://meta.stackexchange.com/questions/158809/why-are-shopping-list-questions-bad). Given the fact that you can control them with logic level MOSFET's or DMX ledstrip controller, he should be able to figuren out what fits his needs/budget.

yes i posted link for <$30 ** 3 Channels DMX-512 Decoder Converter for RGB LED Lamp Light - Multi-functional Full-color LED Decoder Controller **

That's okay indeed (:

ok I'll do that next time.

No. Two reasons:

The Arduino can only supply about 40 mA per pin max. Your LEDs will require about 1000 mA or so per channel (based on the 3 A PSU supplied with the unit).
The LEDs are individually addressed and codes have to be transmitted to them. This requires code to be written for the micro and an interface to the data line.

Figure 1. The IR controller.
The IR controller supplied with the kit interfaces the power and provides the data signal to the strip.
The simplest way to control from your micro is to fit it with an IR (infra-red) LED and transmit the codes to the IR controller. This method also makes it almost impossible for you to damage your micro or the LED strip as the only connection between them will be by infra-red light.
Someone has probably figured this out already and you may find the complete code for an Arduino in a web search.

Are you arguing that these are individually addressed and also have a distinct supply for each color?  Not saying that is impossible, just that it seems odd.  Typically I'd expect individually addressed LEDs to use a common supply, and those with distinct supplies to be only controllable per color, by current modulating the three power supplies.

I'm not arguing! ;^) Of course, you're right. I should probably have said "Your LEDs will require about 1000 mA or so per R, G and B colour." The advert is typically vague about the LED specs.

I don't really think this is the simplest way ;p

@Paul actually re-using the existing drive box is simpler than engineering your own.

@Chris ah! I didn't check the link, but yeah, if that drivebox is included, it may be worth it. But i was thinking of "reverse engineering" the IR protocol and making your Arduino send it out. Adding a few mosfets to the RGB lines, and controlling them with analogWrite should be easier (in terms of coding). It just seemed like a work-around rather than a fix. (Though, with the IR receiver supplied, it makes sense)

But yeah, if you can find example code that works with this, then it's only a matter of connecting the IR transmitter.

No. there is no way to connect those directly.
You can use Solid state relays (SSR) for this.
I did it before and was able to make different colors.
Connect an external 12v directly 12V pin in srips.
Use SSR to connect from GPIO to LED R G and B pins

They already include a driver, so that's not really true - you can inject remote signals into the driver, or directly drive its FETs.

You can use a couple of relays on the arduino outputs, and control it from there.

Using MOSFET's, you can actually dim the R/G/B channels. (Mechanical) relays will wear out and are often too slow.

Please improve your answer giving specifics of how to solve the question asked.

+1 There's no dimming requirement in the question, so this is a reasonable answer for on/off control.  There really aren't specifics to give, beyond the connection details of whatever relay board is chosen.


text:
Arduino Uno with Camera and LCD
I would like to ask you if I can display real time view from Camera in Arduino Uno with LCD.
I have that components:

Camera OV7670 VGA 0.3 MPX
LCD TFT 2.4 SPI ILI9341
Arduino Uno R3

On a website: arducam.com there are used another components. I bought that parts because in a documentation in auction was that is compatible with Arduino.
I see that in Arduino UNO is not so much pins.
Could somebody help me to resolve this challenge?
Regards

That article says you need an ArduCAM CC3200 Uno - not an Arduino Uno.

This is like hauling building materials in a SmartCar.  Maybe you can get a still picture from the camera to the LCD.  But I can not imagine it being very fast if at all possible.  And you certainly could not do anything fancy.  For example, if the camera image needed to be transposed there is not enough memory in a Uno to hold the image in order to operate on it.  It would be much easier to use a more powerful platform.

Please add links to the products, schematics, board pin layout, etc. You should at least do the ground work before asking a question.

No, this is not possible.
The camera outputs a JPEG image. To display that on the TFT screen it is necessary to decompress that JPEG image and send the raw 16-bit (RGB565) colour information to the screen.
The Arduino doesn't have enough memory to do the job.
I wrote an absolute minimal JPEG decompressor a while back. It uses the absolute minimum memory possible (it operates on one macroblock at a time), and still requires around 100KB. That's 50x more than the Arduino Uno has.
Also on a 200MHz, 32-bit chip with FPU it takes about a minute to decompress a 320x240 pixel image. I can't even begin to imagine how many days that would take on a little Arduino Uno even if it did have enough memory to do the job...
As has been suggested, you need a more powerful board. And if you're going that route you may as well drop the useless OV7670 and get a Raspberry Pi with a proper Pi Camera module (or at least a USB webcam).

Useless? Why the hate?

Because it's a pretty pointless device. Certainly in the context of Arduino. You can't do anything with it other than copy the data to somewhere else, such as an SD card, so you may as well just hack a real digital camera (or use one with an external shutter trigger) and get some reasonable quality pictures out of it.

You're mostly right...even an SD card is only useful if you want to take pics every once in a while and definitely not for moving pictures. Slight correction though: this camera doesn't output JPEG; I think its RGB565 and YUV422 and small resolutions (up to QCIF) are supported.


text:
Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)
I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the lcd.ScrollDisplayLeft() but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.
This is what I have so far:
#include <ESP8266WiFi.h>
#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const char* ssid = "ssid";
const char* password = "pass";
const char* host = "api.thingspeak.com";

int find_text(String needle, String haystack, int from) {
  int foundpos = -1;
  if (haystack.length() < needle.length())
    return foundpos;
  for (int i = from; (i < haystack.length() - needle.length()); i++) {
    if (haystack.substring(i, needle.length() + i) == needle) {
      foundpos = i;
      return foundpos;
    }
  }
  return foundpos;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  lcd.init();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight
  delay(200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  lcd.setCursor(0, 0);
  Serial.print("Connecting to ");
  lcd.print("Connecting");
  lcd.setCursor(1, 1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    lcd.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Connected!!");
  delay(1000);
}
int value = 0;

void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

  }

  // We now create a URI for the request
  String url = "/apps/thinghttp/send_request?api_key=345345345345345";
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Fetching Data..");
  delay(10000);

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');

    int start_loc = find_text("<b>", line, 0);
    int end_loc = find_text("</b>", line, 0);
    if (start_loc > 0 && end_loc > 0)
    {
      lcd.clear();
      Serial.println("data:  ");
      lcd.print("data: ");
      lcd.setCursor(1, 1);
      for (int i = start_loc + 3; i < end_loc; i++)
      {
        Serial.print(line[i]);
        lcd.print(line[i]);
     }

  Serial.println();
  Serial.println("closing connection");
  delay(2000);

}
  }
}

Inspecting the library code, it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.
So, you might check if your LCD is capable of performing the scrolling operation.
This web page contains a tutorial on how to use the scrolling feature.  In this code example from that page:
void loop() {
  // scroll 13 positions (string length) to the left
  // to move it offscreen left:
  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(150);
  }

...you can see that it is not automatic.  That you need to call the method each time you want to scroll (in this case) one position to the left.


text:
How to extend my Sketch for Multiple Inputs and Outputs
I am using  4 Push Buttons and 4 leds in my project. Here the sketch is only for one push button and one Led. I want extend my sketch upto 4 push buttons and 4 leds .Please tell what changes I make in my sketch. Please any body can make changes in my sketch.
here is sketch:
const int buttonPin =2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
}

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);
  lastButtonState = reading;
}

Possible duplicate of Arduino Debounce Sketch

I'll show you the long but simple way. Just follow this logic in your setup and loop and you'll be ok. If you still don't understand and want more, tell me and I'll add more code for you.
Do something like this:
const int buttonPin1 = 2;    // the pin the button is connected to
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;

const int ledPin = 6;        // the pin the led is connected to
const int ledPin = 7;
const int ledPin = 8;
const int ledPin = 9;

int ledState1 = HIGH;         // the current state of the output pin
int buttonState1;             // the current reading from the input pin
int lastButtonState1 = LOW;   // the previous reading from the input pin
long lastDebounceTime1 = 0;  // the last time the output pin was toggled
long debounceDelay1 = 50;

int ledState2 = HIGH;         // the current state of the output pin
int buttonState2;             // the current reading from the input pin
int lastButtonState2 = LOW;   // the previous reading from the input pin
long lastDebounceTime2 = 0;  // the last time the output pin was toggled
long debounceDelay2 = 50;

int ledState3 = HIGH;         // the current state of the output pin
int buttonState3;             // the current reading from the input pin
int lastButtonState3 = LOW;   // the previous reading from the input pin
long lastDebounceTime3 = 0;  // the last time the output pin was toggled
long debounceDelay3 = 50;

int ledState4 = HIGH;         // the current state of the output pin
int buttonState4;             // the current reading from the input pin
int lastButtonState4 = LOW;   // the previous reading from the input pin
long lastDebounceTime4 = 0;  // the last time the output pin was toggled
long debounceDelay4 = 50;


text:
Arduino Mega 2560 and Android USB OTG serial communication
currently I am building a little project based on the Arduino Mega 2560.
My goal is to send some data gathered by some sensors to an Android phone.
It has to be as basic as possible.
Buying new hardware is no option.
After some research, I found that it is possible to communicate via USB OTG just with Serial commands.
I downloaded the an app which can do this (Serial Monitor), connected the Arduino via the USB cable to the Android.
Unfortunately, it did not work.
I have an Arduino UNO, too.
Connecting the UNO the same way to the phone works like a charm and does exactly what I want.
I did some more research and found nothing about that.
It seems that everybody is using the Arduino Mega ADK to establish a communication between Arduino and Android.
But I would like to be able to achieve this the same way it works with the UNO.
Can somebody explain me why it does not work?
EDIT
Here is the code I have to test:
Arduino
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Test...");
  delay(2000);
}

For Android I use the code from this tutorial.
Any further suggestions?

It this a genuine Arduino Mega 2560 with an ATmega16u2 as the USB solution (small square chip without leads) or a "compatible" with something else?  What USB VID/PID is associated with it when connected to a computer?  Does it work if you provide 7-12v power through the DC jack?

It's the original Arduino Mega 2560. Where can I see the VID/PID? What is PID? I think VID is vendor ID. But what is PID? I did not tested it with the power jack, yet. Unfortunately, I can test this on Monday, not earlier.

Does the Mega 2560, with the test code you showed us, work when connected to a regular computer?

Yes, the code does work with the Mega and UNO with my Mac and with a Raspberry Pi.

So I figured it out.
It was the VendorID. I found it and noticed, that the VIDs of the UNO and Mega are different.
I adjusted the code and now everything works as I expect.
So, thank you Chris Startton for the correct hints.
Thank you all.


text:
Did I just brick my ATMEGA 2560?
I bought an ATMEGA2560 on eBay and programmed it with Arduino IDE 1.6.9 using the USB cable, and the LED blinked as expected - All well and good.
Now I wanted to program the mega from my UNO as follows:

Uploaded ArduinoISP to the UNO
Changed the Board to Mega2560 and changed the Programmer to Arduio as ISP
Connected the two ICPS sockets with a 6 wire cable, where pin 5 on the UNO ICPS is cut and instead connected to D10 on the UNO
Upload the Blink sketch: IDE says Uploading for a minute, then some errors:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

5) Upload Using Programmer: Activity on the UNO (RX/TX) and the LED on the mega lights constantly - And I can no longer program the mega using the IDE
Any pointers to what I did wrong and how to fix it?
Best regards

Once you use ISP to erase or program anything other than the bootloader, you lose the ability to use the bootloader until you use ISP (or a more drastic method) to replace the bootloader.  So while you have not "bricked" you device, you have put it in a state that will require getting your ISP setup working to recover from.  There are countless questions and answers on proper ISP all over the web, your issue is unlikely to be unique but rather something you can solve by finding and reading them.

I have no doubt the truth is out there - I just don't know the right questions :-)
I tried burning the bootloader with the same setup, and that got the mega back (the led started blinking, and I can program it using USB), but I still don't know how to program the mega using ICPS - Any pointers what to look for?

All pages I have looked at says to connect MOSI to MOSI and MISO to MISO - The caveat is NOT to connect RESET to RESET but D10 to RESET, correct?

Ah, the problem seems to be in the IDE - Something with the fuses when programming the mega (I won't even pretend to understand that yet).
I upgraded to 1.6.12 and everything works like a charm. Best regards
Stefan


text:
Testing for bad WS2812B?
I bought a 100 pack of WS2812S SMDs last year (product link) and wired most of them together for a string of Christmas lights for a tree. It was more work, but way cheaper (at the time) than buying a strip.
I had a few left over that I kept stored away until tonight when I decided to work up a little circuit to enhance my wife's Halloween costume. Problem is, I can't get them to light. Initially I had 3 soldered together, making sure that the voltage and data were going in the right direction, but when I plugged them into my Arduino Uno with a very basic NeoPixels based sketch, none would light. Figuring I had a bad one, I desoldered them all and tried, one by one, on a breadboard. Still no joy.
I tested and confirmed with a multimeter that I was getting the required voltage from one LED to another and reading voltage on the DIN/DOUT pins, but never any light. If I put the Christmas strand from last year on the same pins it works great.
Is there anyway to tell if these are just bad LEDs, or have I missed a step somewhere? I figured if the multimeter showed no voltage on one or more of the pads, that would be an obvious sign to trash it, but since all three show voltage, both when wired together and separately, I can't figure a reason they shouldn't light. Is there more I can do to test?

Have you tried using different libraries? My personal favorite is light_ws2812

No, but seeing as how the larger string of LEDs works, I very much doubt changing libraries will make a difference.

Decoupling capacitors in place?

Your product link does not work.  You might edit your question and fix this.  Assuming you ordered WS2812Ss on PCBs you might inspect the PCBs closely for signs of cold joints or corrosion.  I don't believe the "voltage direction" is important.  However, if you have ever connected  the WS2812Ss in revers polarity, there is no telling if they will ever work again.  These are not simply 3 LEDs but LEDs connected to a rather complex 3 channel PWM controller. Note, data direction is very important.  As well as specifying the number of WS2812Ss connected.

Also, timing the control signal to the WS2812Ss is super critical.  You might try swapping out Arduino controllers to make sure they are not the source of the problem.


text:
Coding problem (gesture sensor)
Hi I am using an Arduino Mega 2560 with two sparkfun zx gesture sensors, two servos, 4 rgb leds strips and 4 light switches.
With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.
My knowledge of coding is limited so I am unsure of how to work around this, I think I have to introduce some new code.
interrupts leds and servos
However, I am unsure of how to introduce it.
Any help would be appreciated.

Driving servos and LEDs from a hardware PWM may help. They will maintain a steady state even if there are interrupts. They may be a little less responsive to changes if there are interrupts.
Are you doing too much when the sensor interrupts? Typically a sensor makes multiple measurements and may be filters the results. When it is ready it interrupts. In the interrupt it should do as little as possible. Typically sending a message via global to a polling function that is not running in an interrupt. For example it may set a flag and the poling function reads the result. Reading the result in the interrupt would be bad.

With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

The best solution for this problem would be to use objects and the millis() function.
Here is a great tutorial about objects and why do we use them with the millis() function. I wont explain it because it it too long and this tutorial is simply better.
I would also suggest to see the blinkWithOutDelay example code from the Arduino IDE. It is probably the first step you have to take to learn how to use the millis() function.

canadiancyborg, that might not be relevant – the question appears to be about conflicting use of interrupts.


text:
Use TFT LCD with Uno and Wi-Fi shield
I need to work with Arduino Uno, LCD and Wi-Fi shield.
I was wondering whether I can use the LCD in the link, 2.2" TFT Display - Test the Display with the Uno and Wi-Fi shield - and how to search for them?

You may even ask adafruit support (they are pretty good at support). But, because of the possibility of having multiple shields use the same pins, I don't use shields.

Start by checking which pins are used by the shields and if there is any conflicts. Check the shield schematics and example libraries.
If there are any conflicts, check if the shields has any jumpers that may be used to change the pin configuration.
Cheers!

Yes the arduino Uno will work with that LCD display and can work with wifi shield at same time too.

Providing they're I2C shields, it is possible to use both at the same time, you may have to write your own modifications to allow this however as each shields library may assume it is the sole connected shield.


text:
Using Arduino to detect when a sensor is on and off and display time elapsed
I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.
Here is the code for the timer:
int main(void) {
  LARGE_INTEGER frequency; // ticks per second
  LARGE_INTEGER t1,t2; // ticks
  double elapsedTime;
  // get ticks per second
  QueryPerformanceFrequency(&frequency);
  // start timer
  QueryPerformanceCounter(&t1);
  //the code for sensorwill be written here
  QueryPerformanceCounter(&t2);
  elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
  printf("\nElapsed time : %lf ms.\n", elapsedTime );
  return 0;
}

QueryPerformanceCounter is a function from windows API. Arduino's millis() function will act in a similar way, but only in millisecond accuracy.

@chamod Arduino also has a micros() function which has accuracy down to 4 microseconds

You can easily do this in Arduino.
However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the millis() and micros() functions? The only problem with the micros() function is that it will overflow after 70 minutes.
The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.
Most of the code for this can be extracted from the various Arduino examples that are on the website.
For the pressure sensor threshold you can use the Arduino AnalogInput example and add an if statement after the analog read and combine that with the millis() function from the Arduino BlinkWithoutDelay example:
int sensorPin = A0; // Choose whichever analog pin you like
int sensorValue = 0;
int flagA = 0;
// flag is used just to indicate if timer has started or stopped

unsigned long startTime;
unsigned long stopTime;
unsigned long elapsedTime;

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

void loop() {
  sensorValue = analogRead(sensorPin);
  // read the value from the sensor
  if(flagA == 0  && sensorValue > xxx) then {
    // if above threshold run timer
    startTime = millis();
    flagA = 1;
  }
  if(flagA == 1 && sensorValue < xxx) then {
    // if falls below threshold stop timer
    stopTime = millis();
    elapsedTime = stopTime - startTime;
    Serial.print("Elapsed time = ");
    // Put your print function in here
    Serial.print(elapsedTime);
    Serial.println(" ms");
    flagA = 0;
  }

Fairly easy, as basically you just need to time stamp the events from the sensor.
You can create a time base for the stamping. Triggering for the stamping can be done via polling, external or pin hanger I terrupts, or capture. To list a few.


text:
SparkFun Monster Moto Shield current sensing issue
I am using a SparkFun Monster Moto Shield (PDF) for driving two DC motors. The shield is working fine and I am able to drive the motor in both directions. However, the current sensing is continuously showing "zero" in the serial monitor.
I am confused why the shield is not measuring any current. I want to measure normal current of 750 mA and stall current of 6 A but I'm getting zero value continuously. If anyone can help me I shall be very thankful.

What is supposed to measure the current?

You're goign to need to post your code.

Can you show us how your code is looking like? Please remember that you can not measure current directly, the method that is used to do that is to measure voltage drop on measuring resistor.
Check this image


text:
Controlling 20 servo motors independently with a single Arduino
I am wondering if I can control 20 different servo motors with only a single Arduino Uno board. My motors must be able to rotate in both directions and I also should be able to define the speed for each of them independently. Also I am able to use integrated circuits or a device that connects to my Arduino board.
Is this a possible scenario?

Surely you can implement it using shift registers to effectively increase your pin count?

@Makoto Will I be able to control any of my pins independently  using shift registers ? Lets say I want 2,7 and 16th pin to be high and others low. Will I be able to do this ? It always confuses me to be able to do these kind of things with only controlling couple pins.

Yes, shift registers usually have a memory stage and an output stage. You can shift the levels you want in to the memory and then latch all of them to the output at the same time. You can also do this fast enough to pwm each pin independently

You may modify Servo.h with #define SERVOS_PER_TIMER 20 and attach a servo to every single pin of your Uno – which may give slightly jerky movements due to the high CPU load. Or you may use another chip just to drive the servos. Or you could use another Arduino/ATmega/ATtiny and volunteer to test my Tiny Servo Controller program.

You could use GPIO expanders like the MCP23008. Very easy to use over an I2C bus and you can have 4 of them per bus, or you could use the 16 bit version.


text:
Can anybody advise what type of connector this is?
I recently purchased an LiPower shield from SparkFun.
I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?
I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?
Please see pictures below, thanks!

The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.

That is generically a "JST" connector.  Named from the company that originally designed and made them.  But I believe there are many "second-source" (and likely counterfeit) sources of similar or identical connectors.
They are avaiable in a variety of mechanical configurations (horizontal, vertical, PC board mount, wire-end, etc. etc.)  And there are several variations with different pin sizes and pin-pitch (distance between the pins). They all look very similar, especially in photographs, but as you demonstrate, the different pitch families are NOT inter-connectable.
If you had bought the battery from SparkFun, it is quite likely that it would have the mating connector.  But since there is no standardization here, you will end up dealing with these kinds of mismatches.

header on the board IS jst XHA connector,but wirinhg harness is XH,


text:
Is there a non-float alternative to pow()?
I've scoured the LANGUAGE REFERENCE in the Arduino web-site, and I can't find a non-Float equivalent to pow()  I've got to be missing something big, but for the life of me, I'm stumped!  I found pow() in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters,  [base] and [exponent] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024
Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!

For the general case of integer pow(), see http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int.  For powers of 2, just use shifts.

For the general case, @dat_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.
Multiplying a number by a power of two can be accomplished by the left shift operation (<<), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward.  In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see this answer on Stack Overflow.
It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which have a max value of 2^15-1 on Arduino Uno.
Given those caveats, here's a function to calculate powers of two within these constraints.  This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.
int pow2(int p){
    return 1 << p;
}

Error: It can go up to 2^32 - 1 if you use an unsigned long.

@DatHa thanks, I seemed to have lost the word "signed" during editing.  Fixed.

It can go past 2^32 - 1 if you use an implementation of arbitrary precision integer arithmetic

I'd like, specifically to know why the results of an integer conversion on the results of pow() DOES NOT work for powers of 2. For me, pow(2,3) returns 8.00, but while int(8.00) returns 8, int(pow(2,3)) returns 7!

It works with int, double, long and float. unsigned long and unsigned int should also work. You are not required to use ONLY floats.
Hope it helped!

The reason the answer above answer works is because the set of real numbers (which contain floats) contains the set of integers

@DatHanBag: And more importantly, every 32-bit integer is exactly representable by a double.  Actually, since IEEE floating point is based on a binary mantissa/exponent representation, every power of 2 should be exactly representable even beyond 2^53 (the point where double can't represent every arbitrary integer, an 1 unit in the last place of the mantissa is greater than 1.0).

@PeterCordes Yes I did know that. Maybe I should have said "bounded sets" when referring to float and integer sets for arduino in my comment about the answer of

This is a somewhat valid answer to the general question of using pow() for integers, but AFAICT arduino doesn't even have hardware floating point, so it's a terrible answer.  An integer pow() implementation like this one that runs in log2(n) time multiplying and adding to accumulate a result would almost certainly probably perform better, and failing to mention that bit shifts work for powers of 2 just makes this a terrible answer to this question.

@PeterCordes  "so it's a terrible answer". -agreed that it is kind of a low quality simplistic answer. pow() is certainly computable in log2(n)- the simple method learned in school (multiply number by itself to the power is not so efficient). You can do it better with a Fourier transform for really big integers -for example.  But maybe the OP will accept and like it.


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

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

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

How did you time your unrolled code?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
Power an arduino on a 12V circuit
I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.
Thank you in advance for the help.

Product page says?

I saw that the arduino can support up to 12V - isn't this your answer?

Not from Vin pin probably. But from the power-in jack.

this question about stripleds has been asked too many times, try reading some answers to learn more about how they work , and power sensitivity from 12 to 14.2V.. see related on right side

Possible duplicate of Controlling 7W 12-14V power LED with Arduino

I just want to know how to wire my arduino to a 12V power supply, the question is not about the led part. I couldn't find a clear answer about that

So now can you update us about which part is still not clear?

As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.

The answer is yes, you can. Since there are no information about which Arduino you are using, Lets assume that you use Arduino uno. Based on the official webpage documentation, the recomended voltage input is ranging from 7 - 12 V. Therefore it is possible.


text:
Arduino calculator: I'm struggling to write a sketch which parses inputted characters
I am attempting to make a calculator with arduino using a 16x2 Text-LCD and a 4x4 keypad. I've already programmed the part where the arduino board gets input from the keypad and displays characters on the LCD respectively, but I'm struggling to program the part where the '=' button is pressed and the arduino parses the sum and gives the answer. I'm not using the RW lin to read the LCD, instead I am adding characters pressed to a char[] variable. Can you guys please give me some code to parse the inputted characters? Thanks!
EDIT:
Code:
#include <LiquidCrystal.h>
#include <Key.h>
#include <Keypad.h>

char keys[4][4]={
  '/','x','-','+',
  '=','9','6','3',
  '0','8','5','2',
  'C','7','4','1'
};

byte rowPins[4]={7,6,5,4};
byte colPins[4]={3,2,1,0};

Keypad input=Keypad(makeKeymap(keys),rowPins,colPins,4,4);

LiquidCrystal lcd(8,9,10,11,12,13);
int inputSize=1;
char inputSum[16];

int cursorNum=0;

void setup() {
 lcd.begin(16,2);
}
void loop() {
  char key = input.getKey();
  if(key) {
    if(key == 'C') {
      lcd.clear();
    }else if(key == '=') {
      parseInput();
    }

    else{
    lcd.print(key);
    inputSum[cursorNum]=key;
    cursorNum++;
    }
  }
}

int result;
void parseInput() {
  //Parse code goes here

  lcd.setCursor(0,1);
  lcd.print(result);

}

Perhaps putting your current code ?

Relevant: Smart design of a math parser?

Characters in a char[] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. Consider subtracting the ascii value of one less than 0 from each char to get the number. Edit: @Matt informed me that 0 is the lowest ASCII number. As he suggested, you can subtract the character '0' from the digit to get the value. You want to specially handle any addition, division, or other operator symbols.
Then you can treat each number like a digit in a number. If you can break up the array of numbers by the operators, you can successively attach the operands to the operators. Keep in mind that each number to the left is a power of ten (assuming this is how it's implemented. This is called Endianess.)
If you post code I may be able to help further.

"one less than 1" ?? In other words zero?  The idea is correct the keypad libraries usually return a char so int number = KeyPad.getChar() - '0'; would work

I was thinking that ''1' was the lowest ascii number. I just checked a ascii table and it looks like '0' is. I'll update my answer.

You could parse it with something like this:
int parserr;

int parse(char* input)
{
  parserr = 0;
  if (input == 0) return (0);
  char* ip = input;
  char c = *ip++;
  if (c == 0) return (0);
  int res = 0;
  char op = 1;
  while (1) {
    int num = 0;
    int neg = 0;
    if (c == '-') {
      neg = 1;
      c = *ip++;
    }
    int isnum = isdigit(c);
    while (isdigit(c)) {
      num = (num * 10) + (c - '0');
      c = *ip++;
    }
    if (neg) num = -num;
    if (!isnum) op = 0;
    switch (op) {
    case 1: res = num; break;
    case '+': res = res + num; break;
    case '-': res = res - num; break;
    case '*': res = res * num; break;
    case '/': res = res / num; break;
    default:
      parserr = (ip - input - 1);
      return (res);
    };
    if (c == 0) return (res);
    op = c;
    c = *ip++;
  }
}

The variable parserr holds the error position (+1), zero is no parse error.
The function parse() will return the value of the simple expression with no operator priority.
This can be refactored to allow normal operator priority:
#include <ctype.h>

class Calculator {
public:
  int eval(char* input, int& result)
  {
    if (input == 0 || *input == 0) return (0);
    m_ip = input;
    if (expr(result)) return (0);
    return (m_ip - input + 1);
  }

private:
  char* m_ip;

  char getc()
  {
    return (*m_ip++);
  }

  int ungetc(int res)
  {
    m_ip--;
    return (res);
  }

  int number(int& value)
  {
    int neg = 0;
    char c = getc();
    if (c == '-') {
      neg = 1;
      c = getc();
    }
    value = 0;
    if (!isdigit(c)) return (ungetc(0));
    do {
      value = (value * 10) + (c - '0');
      c = getc();
    } while (isdigit(c));
    if (neg) value = -value;
    return (ungetc(1));
  }

  int fact(int& result)
  {
    return (number(result));
  }

  int term(int& result)
  {
    if (!fact(result)) return (0);
    int value = result;
    char op;
    while ((op = getc()) != 0) {
      if (op != '*' && op != '/') return (ungetc(1));
      if (!number(value)) return (0);
      switch (op) {
      case '*': result = result * value; break;
      case '/': result = result / value; break;
      }
    }
    return (ungetc(1));
  }

  int expr(int& result)
  {
    if (!term(result)) return (0);
    int value = result;
    char op;
    while ((op = getc()) != 0) {
      if (op != '+' && op != '-') return (ungetc(0));
      if (!term(value)) return (0);
      switch (op) {
      case '+': result = result + value; break;
      case '-': result = result - value; break;
      }
    }
    return (1);
  }
};

Cheers!

What if I input "2+53”? I believe it should do "53+2 = 17", and not (2+5)*3 = 21.

That is what "no operator priority" means :). Parsed and executed in order. It is easy to modify for priority operators.


text:
control vibrator motor speed with ultrasonic sensors
First, thank you for taking the time to read my post.
I am attempting to use 3 ultrasonic sensors to control 3 DC vibrator motor using the PWM output of an Arduino. Fairly simple, I know, but I'm just a beginner. :)
Here's my code,
int trigpin_1 = 2;
int echopin_1 = 3;
int trigpin_2 = 4;
int echopin_2 = 5;
int trigpin_3 = 6;
int echopin_3 = 7;
int motor_1 = 8;
int motor_2 = 9;
int motor_3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(trigpin_1, OUTPUT);
  pinMode(echopin_1, INPUT);
  pinMode(trigpin_2, OUTPUT);
  pinMode(echopin_2, INPUT);
  pinMode(trigpin_3, OUTPUT);
  pinMode(echopin_3, INPUT);
  pinMode(motor_1, OUTPUT);
  pinMode(motor_2, OUTPUT);
  pinMode(motor_3, OUTPUT);
}

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

  long duration, distance;
  digitalWrite(trigpin_1, HIGH);
  digitalWrite(trigpin_2, HIGH);
  digitalWrite(trigpin_3, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigpin_1, LOW);
  digitalWrite(trigpin_2, LOW);
  digitalWrite(trigpin_3, LOW);
  duration = pulseIn(echopin_1, HIGH);
  duration = pulseIn(echopin_2, HIGH);
  duration = pulseIn(echopin_3, HIGH);
  distance = (duration/2) /29.1;
  if (distance > 200)
  {
    analogWrite(motor_1, 0);
    analogWrite(motor_2, 0);
    analogWrite(motor_3, 0);
  }
  else if(200 == distance > 160)
  {
    analogWrite(motor_1, 50);
    analogWrite(motor_2, 50);
    analogWrite(motor_3, 50);
  }
  else if(160 >= distance > 90)
  {
    analogWrite(motor_1, 100);
    analogWrite(motor_2, 100);
    analogWrite(motor_3, 100);
  }
  else if(90 >= distance > 60)
  {
    analogWrite(motor_1, 150);
    analogWrite(motor_2, 150);
    analogWrite(motor_3, 150);
  }
  else if(60 >= distance > 40)
  {
    analogWrite(motor_1, 200);
    analogWrite(motor_2, 200);
    analogWrite(motor_3, 200);
  }
  else if(40 >= distance)
  {
    analogWrite(motor_1, 255);
    analogWrite(motor_2, 255);
    analogWrite(motor_3, 255);
  }

  Serial.print (distance);
  Serial.println (" cm");
  delay(100);
}

but the problem is the DC motors it will be on all the time with 100% duty cycle. if anyone can help me will be thankful

The wiring diagram is very difficult to read. It would be better tor read if you redraw it with the builtin schematic editor.

Does this 'if(160 >= distance > 90)' actually work as intended in arduinoees? I don't believe it does in any flavor of C. You also have 3 lines of 'duration = ...' so you're just overwriting the 1st 2 with the last one.

There is quite a bit wrong with your code I'm afraid.
Firstly the if statements.  If the values are kept in descending order then you can do this:
if (distance > 200)
{...}
else if (distance > 160)  // This point won't be reached unless the value is less than 200.
{...}
else if (distance > 100)
{...}

I think what you were trying to do was:
if (distance < 200 && distance > 160)
{...}

but its not necessary.
You are reading the pulse lengths into a single variable overwriting the previous values.  This means you are only reading sensor 3.  If you want to average the values then try this:
duration = pulseIn(echopin_1, HIGH);
duration += pulseIn(echopin_2, HIGH); // take the result and add it to duration.
duration += pulseIn(echopin_3, HIGH);
duration /= 3;   // divide duration by three and assign the result to duration.

Also I'm not sure about the positioning of your sensors, its possible that they might interfere with each other.  In which case write a function to read from the sensor and store the results in an array.
i.e.
    const int sensorTriggerPins[] = {2, 4, 6};
    const int sensorEchoPins[] = {3, 5, 7};
long readSensor (const int& triggerPin, const int& eechoPin)
{
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(triggerPin, LOW);
  return pulseIn(echoPin, HIGH);
}

void setup()
{
   long duration[3]; // Define a three element array.
   for (int sensor = 0; sensor < 3; ++sensor)
   {
      duration[index] = readSensor(sensorTriggerPin[index], sensorEchoPin[index]);
   }
}

I don't know if this will fix all your problems, but it should help.
(It might have been better if you posted this in the Arduino forum)

PS - You could streamline you setup function if you use arrays for the pin assignments, and you can do the same wit you motors too.

You don't want to use GPIO outputs to drive motors directly.  You'll likely burn-out your Arduino with the schematic you've given.  At a minimum you'll want to use transistors (that can handle the motor current load) to switch the motors on/off.


text:
What is the maximum current for each I/O pin?
Question
As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

The 20 mA is a recommended MAXIMUM current per pin - you should always try to use less current.  There is no problem sinking or sourcing 5 mA, or even 1 mA per pin.

This comes up as first result when Googling your question:

And can be confirmed by page 313 and 314 of the datasheet:

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) schematic.
I provide an excerpt below that shows the Vin and 5V pins at the headers, and the power barrel connection.

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):
*Note that your 12V Gnd and Arduino Gnd have to be connected.

simulate this circuit – Schematic created using CircuitLab

What means the "sink"? English not my first language so I not getting this. By the way is 150 mA total by each of that red square or both together?

"Sink" means that the Arduino is conducting current IN from the pin down to ground.  "Source" means that the Arduino is sending current OUT of the pin.  It is MUCH more common to use the chip to SINK current rather than SOURCE current.

Either way, you shouldn't be coming close to those values, as Richards answer says: if you need to drive significant current, you should use an external device.

@WesleyLee how do I safely get external power? For example I have here some batteries already in serie that gives me 7.2V and a 9V one. Can I just connect and Arduino regulate it for me?

What are you trying to drive? / What is your load?

There are MANY different Arduino models. We cannot answer questions about specific models without knowing what you are asking about.  WHICH MODEL of Arduino are you asking about?  WHAT are you trying to do with it?

It was a general purpose question. It is an Arduino Uno R3. If I for example need to turn on a 12V DC motor, putting it directly in Arduino pins would be stupid, right? This specific motor needs at least 9V.

You will almost certainly burn out your Arduino if you try to drive any motor with it. It is NOT made to do that!  You will destroy the Arduino.  The issue is not really how much voltage the motor takes, the Arduino can handle 9V. The issue is how much CURRENT the motor takes. If it is more than 20mA then do NOT connect it directly to an Arduino.  There are probably NO motors that need only 20mA.

@VitorCosta -- I added a schematic to control external loads. This is the last edit I do to my current answer. Next time I suggest you ask a clear question to begin with. Good luck.

Many questions do not work as "general purpose question". You are asking about details that are DIFFERENT depending on which model Arduino you are talking about.

The power limits per pin and per chip are listed for each model (based on the Atmel chip).  You can look up the Atmel chip number and see the power ratings.  For example, the chip may have a maximum of 40mA per pin, but a total of 200mA for everything on the chip. These numbers are just examples. The actual numbers depend on which Arduino and which chip you are talkng about.
Remember that microcontroller chips are NOT designed to SWITCH any significant amount of power. That is NOT the job of the microcontroller. Its job is to CONTROL external devices (transistors, thyristors,SSR, relays, etc.) which do the actual "heavy lifting" of switching larger amounts of power.
Your last question really does not make any sense. Can you clarify it?
VCC is the name of the main power bus and input to the microcontroller chip. It may or may not be 5V depending on which Arduino you are talking about. The older ones were 5V, but newer chips (including those used in Arduino) are tending more to 3.3V.

See edit. It is Arduino Uno. So when do I use vcc?

You use VCC whenever you want the Arduino to actually operate. VCC is the main power source to the Arduino. Your question seems very strange.

Omg sorry, did remove this strange question, I am truly sorry. I mean the Vin pin and the correct and safe way to use it!

The published specifications for Uno say that Vin can take 6~20V, but the recommended is 7~12V.  Please read the official details at: https://www.arduino.cc/en/Main/ArduinoBoardUno They will answer almost all of your questions

Sorry for one more noob question: if I supply 12V with Vin, will arduino regulate them for pins and they still at 5V?

Yes, if you put 12V into Vin, it will regulate on the Uno board down to 5V for VCC.  What does "regulate them for pins" mean?

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