text:
Atmega328P - SCK pin
I am using Atmega328p with arduino bootloader in a project. There happens to be an LED connected on SCK pin. During Start (or restarts), the LED appears to flicker a couple of times (3 times to be exact). I don't want this to happen. I can change the connections but I would prefer a software solution because hardware change means a PCB modification.
I probed the SCK pin and I got some expected waveforms. There were two different cases:
1) When I powered the arduino using USB to serial programmer i.e. Tx Rx connected to a PC:

2) When I powered the arduino with an external power source (the case with my project):

This is what I think:
1) As mentioned in this thread, the bootloader has a piece of code which makes it act that way.
The bootloader code has a pin definition file which declares SCK pin as a LED and blinks it a couple of times to indicate that it has entered the bootloader. I found the code here:
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
/* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duemilanove */
#define LED_DDR     DDRB
#define LED_PORT    PORTB
#define LED_PIN     PINB
#define LED         PINB5

Other relevant piece of code is here.
In this case, changing the LED definition to PINB4 and burning the bootloader and program again should take care of the issue. However this didn't work out for me. This is what I did exactly:
a) Opened the file D:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot\pin_defs.h
b) Modified the PINB5 to PINB4 on line 6.
c) Saved the file, burnt the bootloader and then program.
d) Powered up the chip and tested whether I am getting those 3 pulses. I got those 3 pulses.
(Even though it didn't work, I am still going to try it a few more times just in case I might have made an error.) :(
2) This brings me to second thought that since atmega328 accepts code through SPI by default, it checks for incoming data by clocking the SCK pins 3 times during startup. In this case, a software fix won't do anything.
What do you guys suggest? Should I go for the PCB modification or is there still some hope left?
Ignacio pointed out that I can disable bootloader to get rid of the issue. I want to program the chip using arduino IDE (preferably via UART) but I can consider SPI as well in case everything else fails.
Note: I am not sure whether this post is more suited for EE or Arduino. In case you guys(mods) think I'd get better suggestions there, feel free to move my post to Arduino.

Can you explain in more detail how modifying the bootloader "didn't work out"?

I modified PINB5 to PINB4, burnt the bootloader, burnt the code and powered the circuit. I was still getting the same 3 pulses.

It might make more sense to set LED_START_FLASHES to 0. There is code in the file you linked to that does that as long as it hasn't been defined elsewhere.

I can try that Dave. I am more of a hardware guy rather than coder. I'll try what you suggested and update my question. Thanks

In that case, you need help from the people who understand the details of the Arduino software. Migrating.

"Saved the file, burnt the bootloader and then program." - didn't you miss out the step where you actually compile the bootloader with your new settings in it?

Do I need to do that? I didn't know that part. Can you please tell me how to do that? I thought arduino will pick the settings on the fly as it does for board definitions. (I changed the extended fuse settings in the boards file and it worked directly)

https://github.com/Optiboot/optiboot/wiki/CompilingOptiboot

As Majenko said, the bootloader is an HEX file, i.e. pre-compiled. You will need to compile it again; search for optiboot and, if needed, download the sources and compile them; you will need to program it with an SPI programmer, though

Thanks majenko and frarugi. I am stuck with the steps that I need to follow. Can you please give me exact steps required to compile? I can do the edits and burning easily. I am just having hard time figuring out the exact command to compile.

I compiled Optiboot a while back using the shell script below. This is for Linux, you may need to adapt slightly for other operating systems.
BIN_LOCATION='/home/nick/Development/arduino-1.6.5-r5/hardware/tools/avr/bin'

$BIN_LOCATION/avr-gcc -mmcu=atmega328p \
    -D__AVR_ATmega328P__ \
    -DF_CPU=16000000L \
    -DBOOTLOADER_ADDRESS=7E00\
    -DBAUD_RATE=115200 \
    -DLED_START_FLASHES=0 \
    -DOPTIBOOT_FIX=1 \
    -Os \
    -gdwarf-2 \
    -fno-inline-small-functions \
    -fno-split-wide-types \
    -fno-tree-scev-cprop  \
    -fno-exceptions -ffunction-sections -fdata-sections \
    -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fno-jump-tables  \
    -fno-keep-inline-functions -fno-common \
    -std=gnu99 \
    -Wl,--section-start=.text=7E00 \
    -Wl,--relax -nostartfiles \
    -Wl,--gc-sections \
    -ooptiboot.elf optiboot.c

rm -f optiboot.hex

$BIN_LOCATION/avr-objcopy -O ihex --set-section-flags=.eeprom=alloc,load \
    --no-change-warnings \
    --change-section-lma \
    .eeprom=0 \
    -R .eeprom optiboot.elf optiboot.hex

$BIN_LOCATION/avr-objdump -j .sec1 -d -m avr5 optiboot.hex > optiboot.lst

You will need to find where your copy of avr-gcc and insert that into the first line above.
Notice I have changed the define for LED_START_FLASHES to be zero above. That should fix the issue.
To save you the trouble of doing that, I have made a "no blink" version for the Atmega328 and put it here:
http://gammon.com.au/Arduino/optiboot_no_blink_atmega328.hex
Warning - the script above compiled the "no blink" version OK, but using the latest version of the Optiboot.c code, and the latest compiler, makes a .hex file that is four bytes too long, for reasons I can't work out. However it compiles fine if you omit the blinks, because there is less code there.

Note re the LED on D13. Because the LED is driven by an op-amp (on the Uno), it will flash even with the above code. However that is because the op-amp has a high-impedance input. If you use a pull-down resistor on D13 it won't flash.

Now that I look at the download, it is so short I may as well include it here:
:107E0000112482E08093C00088E18093C10086E065
:107E10008093C20080E18093C40084B714BE81FFC8
:107E2000C8D088E1809360008DE080936000259A3F
:107E300018E108E033E0F32EEE24EA94DD24D39435
:107E400045E0C42E51E1B52EA7D0813429F481E05C
:107E5000BED083E09AD096C0823419F484E1B7D0C2
:107E600091C0853419F485E0B2D08CC0853599F481
:107E700093D0C82FD0E0D0930102C09300028CD0E1
:107E80009E01382BC901880F991F9093010280939E
:107E9000000297D077C0863529F484E098D080E03E
:107EA00074D070C0843609F042C07ED0E0910002E8
:107EB000F0910102F0925700E895C0E0D1E002C0D5
:107EC0006BD089938C2F90910202C917C8F38C1B39
:107ED00001C0E9929C2F980F9034D8F372D007B666
:107EE00000FCFDCF40910002509101029A01A0E0F8
:107EF000B1E08C911296FD013197608190E0962B54
:107F0000F9010C01D0925700E89511242E5F3F4FE4
:107F1000A038F1E0BF0769F7FA01C0925700E89571
:107F200007B600FCFDCFB0925700E8952BC0843710
:107F3000B1F43AD046D0E0910002F0910102CF01B5
:107F40000196909301028093000284911ED080914B
:107F500002028150809302028111EDCF13C0853758
:107F600041F42FD08EE111D085E90FD08FE00DD0F4
:107F700009C0813531F4109360000093600021D076
:107F800001C01FD080E101D05FCF9091C00095FF6C
:107F9000FCCF8093C6000895A8958091C00087FF0C
:107FA000FCCF8091C6000895F7DFF6DF80930202D0
:107FB000F3CFE0E6F0E088E180831082EE27FF2730
:107FC0000994EADF803209F0F4DF84E1DECFCF9359
:0C7FD000C82FE2DFC150E9F7CF91F3CFDA
:0400000300007E007B
:00000001FF

Just save that as optiboot.hex.

Thanks a lot, Nick. I'll be using the hex file that you generated for me. I really appreciate your help and efforts. I'll give it a go and update you about the results. Have a nice day, Sir.

I downloaded the file and burnt the bootloader. The issue went away. Thanks a lot Nick. You helped more than I asked for.

Hey Nick, the bootloader seems to be causing some RESET issues. Can you check once. Sometimes I feel that I am having difficulty uploading code or resetting the chip by grounding the RESET pin. Can you check if you disabled the reset pin in the bootloader? Thanks

It isn't possible to disable the reset pin, whatever bootloader you use. You might do it with a fuse setting, but the bootloader itself can't do it.

I posted a new question here. Can you please take a look? Thanks

There is nothing in the default megaAVR initialization that causes SCK to behave in this manner; it is all caused by the bootloader.
Fortunately all you have to do to solve this is disable the bootloader. Unprogramming the BOOTRST fuse (ext:0) will cause execution to start at address 0 instead of the beginning of the bootloader on reset.

But then I won't be able to program the chip using Arduino IDE. I need that functionality. Any other suggestion?

Sure you will. You'll simply program it via ISP instead of serial.

Ohh that's what you meant. I can consider this option. However is there a way I can keep UART programming feature intact?

If I was going to then I'd just remove the whole LED blinking part. Which I wouldn't, because I'm far too used to ISP to put up with serial programming.

Dave suggested something in comments - seems equivalent to deleting the LED blinking part. I was just hoping that there is a code way to do which is there it seems after reading your answer and his comment. I'll give it a try and let you guys know. Thanks a lot for posting the answer. (+1)


text:
I’m having a tough time trying to program 2 fsr sensors
Can anyone help me please?
I’m having a tough time trying to program 2 fsr sensors.                                                                                The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed?                     I have got only one to work by using this code:
/* FSR simple testing sketch.

Connect one end of FSR to power, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground

For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading

  // We'll have a few threshholds, qualitatively determined
  if (fsrReading < 10) {
    Serial.println(" - No pressure");
  } else if (fsrReading < 200) {
    Serial.println(" - Light touch");
  } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze");
  } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze");
  } else {
    Serial.println(" - Big squeeze");
  }
  delay(1000);
}

So what would be the correct code in order to get two sensors to work at the same time?

Do you get ANY output on the serial monitor? If so can you share it?

Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:
int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);
  delay(5);
  fsr2Reading = analogRead(fsr2Pin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading
  Serial.print("\t");
  Serial.print(fsr2Reading);

Just started on forum, don't know how to format code yet, sorry.

There's a {} button in the editor.

source: Stack Exchange

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

sort: votes


text:
Value of joystick reduces when I send it over serial
I've got two arduino cards and two bluetooth bluesmirfs. I am currently trying to read value from a joystick and send it over to the other arduino card and use that value to control my servo motor.
Here's my code.
       //Master Code
void loop()
{
    yVal = analogRead(yAxis);   (value between 0 and 1023)
  if(bluetooth.available())
  {

    bluetooth.print(yVal);
  }
  else if(Serial.available())
  {

    Serial.print(yVal);
  }
  delay(100);
}

//Slave code
void loop(){
  while(Serial.available())
  {

    int c = Serial.read();
    Serial.print("Joystick value: ");
    Serial.println(c);
    int val = map(c, 0, 1023, 0, 255);
    Serial.print("Map value: ");
    Serial.println(val);

      myServo.write(val);
    }
  }

Am I doing something wrong? Instead of getting something between 0 and 1023 I get something below 50.

A fundamental lack of understanding of how serial communications works is what you have.
Serial sends bytes. You are attempting to read an int. The two don't match. Not only that, but you are sending the value as text, not a number, so you're interpreting it as gibberish.
My suggestion: do the map on the master not the slave, and send a raw byte between 0 and 255 not a string of text between "0" and "1023".
bluetooth.write(map(yVal, 0, 1023, 0, 255));

I noticed my mistake right after I posted this, but thank you for clearing some doubts :)

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


text:
Using an Arduino to drive a digital RGB LED strip
I recently purchased a 5M strip of digital RGB LEDs, that is compatible with the "Adafruit_NeoPixel.h" library.
Is maintaining the original order of the LEDs important?  Could I cut the strip in say four sections, and then reconnect those sections out of their original order?
Just to be clear these are digital 3-pin(+5V,DI,GRN) strips, not analog 4-pin(+12V, R, G, B) strips.
I'm just not finding good info regarding if the individual LEDs are pre-assigned an ID by the manufacturer, or if they somehow use a serial-timing way to assign IDs at startup.
Before digging through the Adafruit_NeoPixel.h, I wanted to see if I could get a quicker answer here.
THANKS!

I can not find detailed information regarding the 5M LED strips you bought.
I have used Adafruit addressable LED strips.  What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.
Here is an Adafruit image which may help you:

I would think the order does not matter.  But you do need to connect the data such that "outs" go to "ins".  And you need to connect them in a row.  That is you need to connect them in one loop.
Added later...
Assuming we are using the WS2812:

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses.  8 bits for each color: red, green & blue.  That there is 1 such "word" of 24 bits for each pixel.  That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero.  And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.
In other words, it doesn't matter what order WS2812 are assembled in.  Also that WS2812 have no idea where they are in the sequence.  All that matters is that each succeeding WS2812 gets its data from the previous WS2812.
One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off.  When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!

I think "ins" and "outs" is confusing, as there really is only one data connector, it's just that when connecting one strip to another you must maintain the +5V and GND polarity, from one strip to the next.

I do not think, for example, connecting a DIN pin to a DIN pin will work.  Look at the picture.  Look at the silk-screen around the soldered strip connection.  Further, I think the data going into the DIN pin is altered by the NeoPixel's controller chip before coming out of the DOUT pin.  I believe this is the technique that the NeoPixels use to self address.  Hence why I believe you can connect them in any order.  But only in series.  Not in parallel.

I get what you're saying, but most of the strips I've seen are not labeled DIN and DOUT; just DI. So really the important part is as long as you keep the GRN connected to GRN and +5V connected to +5V, the digital connector will take care of itself. That is a fair point about connecting strips in parallel, that would not work because the addressing is done via serial bit-shifting.

I STAND CORRECTED! There is a DI and a DO, so the "DI" needs to be the "beginning" of the strand(s).  Could you incorporate the serial-shifting-register information from the duplicate post, and I'll then select your answer?

I can do that.  But after looking over the translated specification, I would have to disagree with the duplicate answer and say the first 24 bits is used by the first pixel.  Think about it, how could the 1st pixel use and strip off the last 24 bits as it has no idea how long to wait.  This is, it has no idea how many pixels are being addressed.  There is no address information in the data stream.  It is all brightness levels.


text:
Do I need 3 voltage dividers to control ESP8266
I am buying an ESP8266 and the plan is to control it serially from an Arduino. I am going to use a voltage divider(Using a voltage divider is temporary and I know the cons of using voltage dividers).
I calculated out the values of the voltage divider and I am going to use 220 ohm and 440 ohm value resistors to get 3.3 volts and 250 ma from the Arduino 5v pin so I can power vcc and ch_pd on the ESP8266.
The question is do I need to use a separate voltage divider to connect Arduino TX to ESP8266 RX and Arduino RX to ESP8266 TX. Or will it be safe to connect RX and TX directly to Arduino RX and TX.
Honestly I am extremely new to this and I don't even know if I am going at this right. If I am tell me.

You have to convert Arduino's 5V TX so that it'd be compatible with ESP's 3.3V RX.

You're planning on using a voltage divider to provide 250mA current? How much voltage would be dropped across a 220 Ohm resistor with 250mA drawn through it? 55 Volts.

For ESP 3.3V power supply, I'd recommend a distinct 3.3V regulated supply.
Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.
Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.
You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or Vin directly if your UNO is powered through the DC power jack, not USB)
For ESP RX a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a MOSFET based level shifter:

The advantages of this circuit are:

it has the fastest switching response time
it can work in both directions (3.3V -> 5V and 5V -> 3.3V)

You can also buy some cheap ready-made breakouts using this circuit and offering several level shifters.
For ESP TX, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).

The RX pin is 5V tolerant (at least it is on all of my boards!) and almost certainly your arduino will recognize 3V as logic high for the TX pin. So you don't really need any level conversions there (no other pin is 5V tolerant).
Are you sure your ESP8266 board doesn't already have a 5V to 3V3 regulator? I've never seen one!

Yes there are some development boards by adafruit that do come with voltage regulators. I am going to be writing a blog on how low cost arduino can be in the future maybe so I am not going to be using dev boards. I will say that the dev boards are worth  the extra $8 though for anyone reading this.


text:
Is it safe to place a capacitor across vin and gnd?
I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.
The ATX is gated by a relay on its DC side and seems to cause enough of a current drain that it causes the Arduino to reset.
I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?
Standard?
EDIT:
Here's a very basic sketch..

12V Transformer powers arduino on VIN/GND pins, other pins are 5V, GND and control for relay

If you directly drive the relay from an Arduino pin (as it seems on the provided drawing), then you should probably consider using a transistor (or a MOSFET) to drive it. Finally, don't forget to use a flyback diode to avoid ruining your Arduino because of high flyback voltage.

I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.
What you have implemented is called a reservoir capacitor and is a common use for large value capacitors like that.

Perfect..That makes sense. Thanks.  reservoir eh! Hope the drawing makes the first statement clearer.


text:
IR sensor does not work well on carpets
I have facing a problem since long and cannot solve it. I built Arduino car and place 2 IR sensors shown in image, to check down distance to avoid falling from stairs. One is at back and other at front. On hard surface they work well but on carpet always give wrong reading like no object there which translates unsafe to move and my car stops. How can we solve this problem? I also tried Ultrasonic but it has same problem on carpets or fabric.
I tested this that on carpet it was giving a big distance reading but when I place a white paper, suddenly it was fixed and detected surface.

Maybe a contact switch may work?  Maybe one of those end stop switches with rollers.

It may highly depend on what type of carpet you have. But you might get away with adjusting the IR's sensitivity.
I believe it's also a good thing to place something between the receiver and transmitter, to avoid them making "contact" directly instead of by reflection.

Paul, the blue thing on IR sensor is for adjusting distance and I tried it but this adjusting will not work here.

You may have noticed that this product is no longer available from well known parts distributors like adafruit.com, sparkfun.com or trossenrobotics.com. I would recommend using a Sharp distance sensor designed for the distances you are interested in:

It is about 10 times the price, but produces a variable voltage that you can read with the Arduino's ADC.  Then you can compensate for floor irregularities in your code.
If you care to experiment, I obsurved that the better distance measurement devices angle the emitter and sensor to light up & observe the same spot at the desired operating distance:

You might try this with your current sensor.  However, it does not appear the manufacture left you enough lead length to make such an adjustment.

Thanks @st2000 for detailed reply. I have 1 sharp sensor after failing with cheap IR sensor and Ultrasound sensor. I am using it for front distance. I came up with few results. Ultrasound sensor failed on fabric objects i-g. sofa or carpet. I used sharp sensor which fails on dark objects like black surface or very shiny steel sheets. Also I read that it will also fail on sun light or very bright light. I know there are some LDR sensors on ebay but cheapest one is C$300 plus. Other lasers are around C$130 plus. Can you provide the name and product # etc. for this. I can check on ebay.

I have never used a LDR so can not recommend a part.  You could combine the ultra sound and Sharp sensor in software to cover more surfaces.  Also, what about micro wave sensors like those found in construction-wall-sensing devices.


text:
How do I pass an Int Array into void for a foreach loop?
I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:
int example[] = {1, 2, 3, 4, 5};

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

    #define foreach(item, array) \
        for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)
    }
}

void Words (int w[]) {
    foreach(int *v, w) {
        Serial.println(*v);
        delay(500);
    }
}

void loop () {
    Words (example);
}

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?

The problem lays in sizeof array which can not be correct when foreach is called from Words(int v[])  function. If you put Words code directly in loop then it should work: did you check that?

Yes that does work, but I just want to be able to call from the void to save space and keep my code clean and more readable, I will be calling it many times with different arrays so to have many foreach loops is going to get rather messy.

Then your only option is to explicitly pass the array size (number of items) as an extra argument.

How is that done?

What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between
void f(int* array)

and
void f(int array[])

In particular, inside f() the compiler won't be able to know the actual size of array: for the compiler sizeof array will always be the same as sizeof(int*), i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.
If you want your foreach macro to work correctly, you have to pass it the actual array count of items as an additional argument:
#define foreach(item, array, size) \
    for(int keep = 1, \
        count = 0;\
        keep && count != size; \
        keep = !keep, count++) \
    for(item = (array) + count; keep; keep = !keep)

And also pass the count of items in Words:
void Words(int w[], size_t size) {
    foreach(int *v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

In loop() you can use sizeof example, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):
void loop() {
    Words(example, sizeof example / sizeof example[0]);
}

You could even define a macro to compute the count of items in an array:
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

It will work as long as you use it with an argument that is completely known by the compiler:
void loop() {
    Words(example, ARRAY_SIZE(example));
}

Important comments on your original code
You mentioned that you want to "save space", but defining a macro will not help in this regard, as a macro is NOT a function, hence its binary code will be repeated everywhere it is used. It can just help make your source code shorter and possibly clearer.
The way you defined your macro seems weird and overly complex to me: why use 2 for loops when you need only one?
It would have been possible to define it in a simpler way, for example:
#define foreach(type, var, array, size) \
    for(type* var = array; var != array + size; var++)

It would be used as follows:
void Words(int w[], size_t size) {
    foreach(int, v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.

Adding to the reasons why it's a bad idea to define that macro:

If you want to keep your code readable, inventing syntactic sugar and implementing it with macros is the wrong way of going about it. If the language designers did not do provide a construct, there is probably a reason. This is particularly true if you are not a complete master of the language.
Premature optimization is always a bad idea. First, modern compilers are very good about optimizing stuff. Second, unless you have measured the performance of your code in great detail and deemed the performance unacceptable, you are wasting effort and making the code harder to maintain. Third, what you think may be an optimization may result in worse code in a future version of the compiler, or in a different hardware architecture. The list goes on.
Never use preprocessor macros unless there is no other way of doing what you want to do (there usually is). There are countless articles detailing why you should not, but here is a short summary: macros pollute the global namespace, are hard to test and thus hard to debug, have no type checking, introduce subtle (and not-so-subtle) bugs, obscure calling semantics, and generally make the code unreadable. That we are having this discussion here is proof enough :)
In this particular example, you are relying on the fact that the array example[] is defined (meaning: declared and storage is allocated, and in this case initialized, for it) in the same translation unit as your macro. Had this not been the case, sizeof would not have worked
If you want to inline code, use inline functions. If you want to define constants, use const. And so on.

In your case, you are far better off declaring your arrays as vector<int> and using either iterators or the range for in combination with auto type declarations:
#include <vector>
std::vector<std::vector<int>> example = {
  {3, 1, 4, 1, 6},
  {2, 7, 1, 8, 2, 8, 1, 8},
  {5, 7, 7, 2}};

...

  for (auto v: example) {
    for (auto i: v) {
      // do something with i
    }
  }

Isn't this a lot more readable than your foreach macro?
Needless to say, you need to make sure that your tool chain supports C++11; the 1.6.7 version of the Arduino IDE running on Linux definitely does.
Obviously, there are occasional reasons to break the rules I mentioned above, but until you know exactly what you are doing, it's better not to.


text:
Code doesn't seem to work when trying to program 2 sensors
Can anyone help me with this issue
I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.
The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.
The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin
This is the code that I've written
/* FSR simple testing sketch.

 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;
int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
int fsrReading ;
int fsr2Reading;   // the analog reading from the FSR resistor divider

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
}

void loop(void) {
    fsrReading = analogRead(fsrPin);
    fsr2Reading = analogRead(fsr2Pin);

    Serial.print("Analog reading = ");
    Serial.print(fsrReading);
    Serial.print("\t");
    Serial.print(fsr2Reading);

    // We'll have a few threshholds, qualitatively determined
    if (fsrReading < 10) {
        Serial.println(" - Nothing");
    } else if (fsrReading < 200) {
        Serial.println(" - Light");
    } else if (fsrReading < 500) {
        Serial.println(" - Lightness");
    } else if (fsrReading < 800) {
        Serial.println(" - Medium");
    } else if (fsr2Reading < 1100) {
        Serial.println(" - No-Pressure");
    } else if (fsr2Reading < 1400) {
        Serial.println(" - Light-touch");
    } else if (fsr2Reading < 1700) {
        Serial.println(" - Light-squeeze");
    } else if (fsr2Reading < 2000) {
        Serial.println(" - Medium-squeeze");
    } else {
        Serial.println(" - Big-squeeze");
    }
    delay(1000);
}

So could anyone tell how to edit this code correctly in order to get two sensors to work?
The one connected to the A0 pin is working but not the other

The picture is not really easy to check connections, so I'll take it for granted they match the diagram (which is correct). First, using analogRead will give values between 0 and 1023, hence why do your tests check thresholds above that (i.e. 1100, 1400, 1700, 2000)? Then your code is testing the second FSR only if the first one is pressed enough (analog read must be >= 800). That-s because of the first else if checking fsr2Reading: else if (fsr2Reading < 1100). You should remove the else there.

As JFPoilpret says you if logic is wrong.
It might make it easier if you took that whole if block out and made it into a function that accepted the value from the sensor as a parameter.
void CheckReading(int reading)
{
    if (reading < 10) {
        Serial.println(" - Nothing");
    } else if (reading < 200) {
        Serial.println(" - Light");
    } else if (reading < 500) {
        Serial.println(" - Lightness");
    } else if (reading < 800) {
        Serial.println(" - Medium");
    } else {
        Serial.println(" - Big-squeeze");
    }
}

Notice that the values only go up to 800, going larger than 1023 won't work anyway.

The error message says that a function-definition is not allowed here before the token click this link http://postimg.org/image/7uy3kqwch/

@rich1234 That's brilliant, as Holmez said functions can't be declared inside other functions (Lambda functions can, but don't worry about them for now) so moving the code should make the error go away.  However you have called the parameter fsr2reading which is also the name of a global variable, this is a bad idea, it could be confusing.  Finally you could call the function from within you setup function by doing this fsrReading(analogRead(fsrPin)); fsrReading(analogRead(fsr2Pin)); and you don't need the global variables fsrReading and fsr2Reading.

Try changing the pins to use A0 and A1, as pins 0 and 1 relate to the digital pins.
int fsrPin = A0;
int fsr2Pin = A1;   // the FSR and 10K pulldown are connected to a1

As has been mentioned by Matt, make sure you also only test for values between 0 and 1023.
You are also missing the pinMode, which sets the pins as input/output in the setup function
void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);
    pinMode(fsr2Pin, INPUT);
}

Hi I have received this error when typing the code matt has suggested do u have any idea how to fix it have a look at the link here http://postimg.org/image/7uy3kqwch/

It looks like you are trying to declare a function within a function. If you cut the function as suggested by Matt, and paste it at the bottom, after the last }, then that should fix the error you're receiving.

@Rich1234
I have taken your code, JFPoilpret's, Holmez's and my answers and put them altogether.  Hopefully this explains what we mean and will give you something to work from.  It does compile, but I don't know if it works, because I don't have two sensors to try it with.  The code is by no means perfect, but its a start.  If there are any problems, give us a shout.
/* FSR simple testing sketch.
 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

const int fsrPin = A0;      // Change to A0 so it refers to the correct pin
const int fsr2Pin = A1;     // Change to A0 so it refers to the correct pin
// int fsrReading ;     // Change Not required
// int fsr2Reading;     // Change Not required

// Function     : Read the data from the pin and write a meaningful description to the serial output.
// Parameters   : The analog pin to read from.
// Returns      : The value read from the pin
int checkReading(int pin)
{
    const int reading = analogRead (pin);       // Get the reading from the pin. (const because it won't change within the scope (life) of this function)
    Serial.print(reading);
    Serial.print(" - ");
    if (reading < 10) {
        Serial.println("Nothing");
    } else if (reading < 200) {
        Serial.println("Light");
    } else if (reading < 500) {
        Serial.println("Lightness");
    } else if (reading < 800) {
        Serial.println("Medium");
    } else {
        Serial.println("Big-squeeze");
    }
    return reading;
}

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);     // Change to define the pin 'direction'
    pinMode(fsr2Pin, INPUT);
}

void loop(void) {

    Serial.print("Analog reading A0 = ");
    checkReading(fsrPin);
    Serial.print("Analog reading A1 = ");
    checkReading(fsr2Pin);

    delay(1000);
}

Yes it all works for me now thank you very much everyone I really appreciate your help


text:
Is it possible to have an array of int arrays?
I have a huge number of arrays, each with a series of numbers each referring to an LED on a strip. I want to be able to address each one by a number, so the logical solution to that for me was to make the whole thing into an array. Can that be done, or is there a better work around that can be implemented?

Yes t is possible: you should take a look at http://www.cplusplus.com/doc/tutorial/arrays/ and search for "multidimensional arrays" there.

My word, my mind is blown. Thanks for that @jfpoilpret. I'll see what I can do with that.

I have question. What if wee have array a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; and then use another array to gather arrays before defining, za[] = {a[], b[]};
or za[] = {a, b};
I try it before with led array, who another person defining letters as binary code, and I was trying update that code and use next array to store set of letters which will use defining arrays from rows with binary code.

Yes you can have arrays inside arrays.
The array would be declared as:
int arrayName [ x ][ y ];

where x is the number of rows and y is the number of columns.
The example below declares and initializes a 2D array with 3 rows and 10 columns:
int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

To access the value of 27 (and save it into myValue):
myValue = myArray[2][6];

What if I want an array of pointers to arrays?

https://stackoverflow.com/q/11363226/6075112 and https://stackoverflow.com/a/936702/6075112

It would be worth adding than this 2D array is actually an array of 3 arrays of 10 numbers. Not all programming languages use row-major order.

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


text:
How to import data from SDcard on Arduino to the computer using Arduino serial/COM port?
I have Arduino UNO with Adaruit wifi shield. I store some data on the sd card successfully and now I need to import that data on to the computer.
I am sending some token, say "1", to the UART port of Arduino (COM port), there is a code written on the Arduino which responds to that token and sends data (byte by byte) in the bulk amount on the serial of the Arduino. I have to accept bytes and store in a file on the local machine (computer) and upload to the server ultimately at the same time.
(It will be good if the process has the browser support i.e I will send request from web browser to API and that API will connect to serial port/ COMP port of my Computer and somehow the file will be created on the local machine and the data from the Arduino will be saved in that file; the file created will be uploaded to the server ultimately.)
What is the proper way to this, is there any API or software for it?
Please help me out.
Thanks in advance!

There is an example for the ESP8266 (using the Arduino IDE) called SDWebServer which might give you some ideas, I would suggest you try it but I doubt the libraries would work on an Arduino.
If you are going to support a web API, I would suggest you implement a REST API on the Arduino, that is a commonly used API for these type of things.

The client (PC) sends a HTTP GET request to the server (Arduino) with the token you want.
The server responds with the data the token corresponds to.

You are using standard HTTP (you can do it through a browser), so it should go through firewalls without a problem.  Its a very common format, there are plenty of tools to debug it and tutorials for all sorts of platforms that you should be able learn from.
The problem is REST API isn't the best solution for Serial comms, I'm not saying its impossible you could send the network messages via serial, but it wouldn't be pretty.  I think you would be better keeping your custom interface for the serial and moving as much of the code into common functions so you can share it between the two interfaces.
Hope that helps


text:
Use of two external power sources for a power cell - charger
I have a SparkFun Power Cell - LiPo Charger/Booster and want to use the external 5V charge capability. Now my question:
Can I directly hook up a DC jack (for a 5V power supply) and an inductive charging circuit to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that either the power supply via the dc jack or the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...
Have anybody experience with an similar setup?
Thank you in advance for your answers.

A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.
I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work.  You could practice any solutions on a breadboard with some LEDs.


text:
Can I use Arduino Nano V3 to program another arduino (Pro Mini)?
I was planning to buy serial to USB converter (FT232RL) to be able to program Arduino Pro Mini.
But the shop nearby offers Arduino Nano V3 at almost the same price.
Could I use this Arduino instead (and gain new microcontroller platform for free ;-)?

Have you tried Arduino as ISP?

I did read: http://www.arduino.cc/en/Tutorial/ArduinoISP but it says about programing bootloader and does not clarify if Nano V3 can also b used.

You can flash any sketch with Arduino ISP.

Yes!
Yes, you can substitute the Arduino Nano V3 for the Arduino Uno and follow the instructions here, providing that the Arduino Pro Mini is a 5V version. (Otherwise, you will have to do some voltage conversion.)
Both boards have the same SPI pins as the Arduino Uno. The connections would be as follows:
Arduino Nano --> Arduino Pro Mini
5V  ------------------->  Vcc
GND  ---------------->  GND
D10  ----------------->  RESET (10uF between RESET & GND)
D11  ----------------->  D11
D12  ----------------->  D12
D13  ----------------->  D13
The process detailed in the link can be summarized as follows:

Load the ArduinoISP sketch into the Arduino that you will use as programmer. You find it under Examples > 11. ArduinoISP > ArduinoISP.
Select the serial port of the Arduino Nano (target): Tools > Port > corresponding port number.
Wire up the two Arduinos as described.
In the Tools menu, set the programmer to the Arduino as ISP.
Select the target board: Tools > Board > Arduino Pro Mini.
Open the program to be loaded to the Arduino Pro Mini and program it by selecting Sketch > Upload using programmer

please note, that 10uF capacitor should be connected on Nano board (programmer), instead of pro mini (target)


text:
connect arduino to battery with 12V motor
I am looking  at this(instructable with circuit picture) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino. I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply. How should I get a charger cable and solder on the battery wires to the charger? If so are there any tutorials? Is the connection to the Arduino necessary?
(please look at the Firizing diagram in the instructable)
Thanks

I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot.
  However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino.
Which is bullshit.
You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.
I'm not sure what you mean by "Green device", the HC-05 or the L293D?
Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino).
You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

How should I get a charger cable and solder on the battery wires to
  the charger?

You can't charge regular 9V batteries.

Is the connection to the Aruino necessary?

The specific connection he shows? No.
Power to the Arduino board? Yes.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino. Which is bullshit. - It's an instructable... what do you expect? It's a repository for complete rubbish and bullshit. The rule is: if you don't have the slightest clue what you are doing, do it anyway and then post it on instructables.

@Majenko that's true, but wanted to highlight it since it really confused the person who asked the question ;)
I was thinking of adding, and would like to add: "You should use reputable sources, this instructable is full of mistakes."


text:
What does this error mean?? Arduino Due loop warning
I am getting this error on compilation of the code given further below;

warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations]
leds[XY (x, y)].r = redarray[x][y];
note: containing loop
for(uint8_t x=0; x < MatrixWidth; x++){

Code:
 // the header files for the RGB data

#include <FastLED.h>
#include "redarray.h"
#include "greenarray.h"   //g data header file (hex or dec)
#include "bluearray.h"   //b data header file (hex or dec)*/

 //matrix parameters

#define MatrixWidth 36 //columns (x)
#define MatrixHeight 1 //rows (y)
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

void setup() {

   FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
   FastLED.clear();
         }

void loop() {
   for(uint8_t y=0 ; y<1 ; y++){
     for(uint8_t x=0; x < MatrixWidth; x++){
         leds[XY (x, y)].r = redarray[x][y];
         leds[XY (x, y)].g = 0;
         leds[XY (x, y)].b = 0;

         FastLED.show();
         delay(50);
     }
   }
 }

  uint16_t XY( uint8_t x, uint8_t y)
  {
      uint16_t i;

      if( MatrixSerpentineLayout == true) {
          if( y & 0x01) {
          // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
    } else {
         // Even rows run forwards
         i = (y * MatrixWidth) + x;
    }
}
   return i;
}

The following is redarray header -
//RED
const byte redarray[3][36] PROGMEM = {
{0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
};
How to remove this warning. The redarray is not being read properly by arduino. THe above code should make the 36 LEDs turn off (black) as per the header file. They are randomly lit red... I am totally perplexed!
Plz help if somebody can.
Thanks!

MatrixWidth is 36. redarray[] has 3 elements. The compiler has detected that your code will likely blow up on the 4th go through the loop. Make sure your code is accessing the dimensions correctly.

(great name btw! :P) ...I referred to this link http://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm and it says that the brackets around indvidual elements are optional. So, by that , my redarray is a 3 row 36 column array. Which one is correct? Any could you please tell how to access the dimensions correctly. I am stuck on this since quite a long time. the leds[XY(x,y)]= redarray[x][y] ....is this accessing of array and allocating to leds correct???? Thanks!

What do you mean which is correct? Your first dimension only has a fixed 3 elements. Attempting to access beyond that is a bug.

I declared my redarray as { {r,r,r,r...36 elements}, {e,e,e,e,e...36 elements}, {t,t,t,t,...36 elements} }; in three rows...isn't that a 3*36 matrix? On the link, it is defined like this only....each row within {} ?? Thats my confusion....

You're too mired in trivialities. Your first dimension has three elements. If you try to access it with a value greater than 2 then your code may blow up.

Varquez-Abrams ..i do understand the point you are trying to put across, however, I cannot spot the mistake still.. Or what correction i need to make..Sorry brother... Would have to think more about it... I asked this yesterday something like this too, did the changes but now a new error.will have to see... Thanks though...

What values can x take on?

So, here i what I understand or see - y takes only one value 0 and that is the first row of the matrix. X goes from 0-35 (36 LEDs) and thus I am calling out the entire first row of the matrix (which itself is one row only). redarray is 3*36. based on my understanding that signifies 3 rows with each row having 36 elements(rows are explicitly defined). And thus I am mapping one-to-one with the leds and redarray. But in reality that aint happening. I am wrong I know..trying to figure out sir

The problem you're having is that you're thinking of it in "rows" and "columns", and that is hopelessly confusing you. Think in dimensions and their order instead.

I completely understand the left hand side of the line leds[XY(x,y)] but i am confused ( and u r right abt the rows and columns thing.. M lost there only) about the redarray part. How does Arduino "move" through this array with the given for loop? The ans to this depends on how does one define "elements" in a 2D array? A one D array is linear ( one dim) so a [m][n] array is a 1D array of length m replicated n times in the other dimension. I think i get what u r saying.. But then how do you define a 3*36 array if my style of decl is wrong? Thanks

You've already defined the 336 array. But you're treating it like a 363 array.

After thinking about your last comment, I finally managed to see the mistake - on RHS i.e. redarray[x][y] ..In place of this it should be redarray[y][x] I got the correct pattern. And I also realised that where I was getting lost, leds[XY(x,y)] employs the coordinate system concept as per FastLED. I was getting confused between this coordinates and dimensions of array. It works perfectly now. Thank you so much and more than that..thanks for not telling me directly the mistake..but through hints ;) :) ..I learnt something. I hope I am correct now. :P :)


text:
Electric interference from cnc spindle
I've got a CNC machine and I recently started using a spindle for it. At first it was running smoothly with no issues, but after the first brush pair wore off (I've replaced them later on) it started interfering with the Arduino/gshield and pc monitor. The monitor displays a "no signal" message, although after turning off the spindle or turning it to a low speed the signal comes back. The other problem is that after running a long job, sometimes the gshield disconnects and the job stops midway.

What part could be causing all this interference?
How can I shield that part so it stops interfering with other electronics?

I am using the following hardware:

600 watt spindle
600 watt power supply with variable speed
the wires from the spindle to the power supply are not shielded, although Ive tried covering them with aluminium foil, not sure if that should be of any benefit, I've read it somewhere so I gave it a try.
Gshield with Arduino, connected to a Raspberry pi.

All the electronics are within 70 cm radius.

What part could be causing all this interference? If the interference started when you replaced the brushes then suspect the brushes are causing arcing and so generating interference. Try some better quality ones.

"At first it was running smoothly with no issues...", which is good, but then "the first brush pair wore off" and "I've replaced them". I would suggest that you stop focusing on the country that manufactured the spindle and look instead on what changed to make the problem occur.

Brushes often need to "wear in" so that the ends of them fit nicely to the curvature of the commutator. Until that point you can get a lot more sparking than normal.

if the X  part dicsonnects, there probaly is arcing and making interference.

I would guess that arcing in the spindle causes spikes that travel through the power supplies and power wires. One thing you could try is to use a really long extension cord (say 15 meters or more) to power the spindle power supply. You can insert this cord to a different power outlet to gain additional distance.

@Omar K : It might be useful for others encountering similar issues if you described what you did and what results you got. That's what is great about stackexchange / stackoverflow: a huge knowledge base is created, piece by piece.


text:
Need Help with Switch Case commands/receiver and lcd screen project?
I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working.
Edit:
`
#include <LiquidCrystal.h>
#include <VirtualWire.h>
LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  lcd.begin(16, 2);

  // Print a message to the LCD.
}

void loop()
{
  if (vw_get_message(message, &messageLength)) // Non-blocking
  {
    switch(message[1])
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("O.O");
      break;
    case 1 :
      lcd.setCursor(0, 1);
      lcd.print("Hi! :)");
      break;
    }
    {
      Serial.print("Received: ");
      for (int i = 0; i < messageLength; i++)
      {
        Serial.write(message[i]);
      }
      Serial.println();
    }
  }
}

Show what you've tried.

Ive changed my code so many times so far, but at this moment it is:

Okay! I finally got my code to post correctly!

Please read How do I ask a good question?. You have described what you want. Now tell us what happens, and compare that to what you expected to happen.

Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

The output you get (both in the LCD and the serial console)
The message sent

One thing that strikes me as a potential problem is the
switch(message[1])

line. If you want to check the first character received, it should be
switch(message[0])

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):
  lcd.setCursor(0, 0);
  lcd.print("Initialised!");

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.
Give us more information and we 'll be able to help more.


text:
Arduino Uno's RX and TX lights not blinking. Unable to upload sketches!
When arduino starts up, RX TX lights doesn't blink. Only the PIN 13 and Green light turns on. Pin 13 light blinks thrice before getting stable. RX TX lights are not blinking at all. I am not able to upload any sketches. The error I get is "Not in sync resp=0x00" or "Programmer not responding" or "Not in sync resp=0x95" or "Not in sync resp=0x69" and so on. A new error everytime. Most probably the error is with serial communication.
A brief history of what I have done
I have a Relay which is operated at 12V. But Arduino works at 5V logic. So I used a comparator (IC741) to improve the logic (By setting Vcc and -Vcc at 12 and 0 and the input pins connected to arduino). I also connected HC-05 bluetooth module to use the relay using my cellphone. You know what I was trying was home automation. Also Arduino was connected to 12V DC supply (I think this was my mistake). Everything was going right.
Suddenly IC741 started burning,maybe I shorted some pins when I was trying to measure the voltages using multimeter. I quickly removed it. Suddenly HC 05 started burning. I immediately removed all the connections. After some time I turned on Arduino again (This time using USB connected to laptop). I connected HC05. The bluetooth module heats up again. I thought the module is now gone. I turned to check Arduino and as I stated I am unable to upload any more sketches. Most probably the bluetooth module cause an error in serial communication. May be not.
So my question is
1. What's the real problem. Is my bluetooth module gone? Or is Arduino gone? If arduino is still fine, how can I get the serial to work back and enable me to upload sketches?
2. If Arduino is gone, most probably the microcontroller Atmega328 is still fine. How can I use it now without Arduino (I don't have any extra Arduino)?
Things I have already tried :

Loopback test : No echo back. Serial data can neither be sent nor received.
When I open the Serial window, Arduino doesn't resets as it it earlier.
RX TX Vin and 5V pin reads 4.99V. I hope they are fine.

say goodbye to the arduino.

@MarkoBuršič Could you please state a possible cause?

I'm not going to write a speculative answer, but you've probably shorted 12V through to something and fried the comparator, the Bluetooth module, the ATMega328 serial pins if not more of it. If you remove the ATMega328 and connect the TX RX pins together on the Arduino, then send data through the serial monitor, do you see it coming back? If not, you've probably fried the serial pins of the ATMega32U4 as well.

Same here. I am pretty sure the damage was done when testing various things, never plugged a motor in AFAIK but it turns out capacitors on the wrong pin (eg D6) can sometimes send a spike back down into the USB chip and fry it.
The actual 328P works fine in my other Arduino.
Incidentally an out of spec 16MHz crystal can cause strange problems too.

Pin 13 light blinks thrice before getting stable.

It is supposed to do exactly that. See What happens when code is uploaded using the bootloader?

RX TX lights are not blinking at all.

That's not so good. See Have I bricked my Arduino Uno? Problems with uploading to board

Can you test the bluetooth module separately? i.e. just connect the power pins directly to the correct voltage source, and check if it overheats.  In this way you may be able to find the source of the short circuit.
If you shorted one or more of your arduino's I/O pins, you may have damaged your Atmega328 chip, since there's no protection between the chip and IO headers.  The other circuitry on the Arduino board is mostly power conditioning/regulation.  So I'm assuming that's not the problem.
Check if your 328 is getting the correct voltage at the VCC pin, to eliminate the power circuitry as the problem.

If you are getting three blinks, most likely bootloader is fine but don't take it for granted. Also, post a schematic and picture of your original setup to get better answers in future.
Here is how you should start the debugging process:
1) Disconnect everything from Arduino especially from Tx Rx pins, and try to dump the blinky sketch. If it works, then arduino is good. If it doesn't work, follow this article to burn a fresh bootloader in your atmega. Check again. If not able to burn bootloader or code afterwards, get a new atmega IC for cheap and replace the damaged one.
2) Check the voltage requirements for HC-05 whether it's 3.3V or 5V. Make sure you are not giving it a higher voltage. If it starts to smoke as soon as you connect the GND VCC, then probably it has been damaged. Measure the resistance between GND and VCC of HC-05 before attaching. If it's less than 10-20 ohms, you already know that it's damaged.

authors: Алексей Кузнецов


text:
Ethernet Shield: Failed to configure Ethernet using DHCP
I am currently making a design that uses the Arduino's Ethernet shield. I am using the PushingBox API for Arduino, and have tried it with my Arduino Mega (2560) with the ethernet shield attached to the router. When I did this, however, it displayed a message on my serial monitor saying Failed to configure Ethernet using DHCP. The model for my Ethernet Shield is a W5200 Seeed Studio Ethernet Shield, and I am using the libraries that Arduino provides. I do not have an SD card inserted and the DHCP on all other wired devices works. Any help is greatly appreciated.
The code (in case):
#include <SPI.h>
#include <Ethernet.h>

  /////////////////
 // MODIFY HERE //
/////////////////
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x19 };   // Be sure this address is unique in your network

//Your secret DevID from PushingBox.com. You can use multiple DevID  on multiple Pin if you want
char DEVID1[] = "{[I have replaced this with my DevID]}";        //Scenario : "The mailbox is open"

//Numeric Pin where you connect your switch
uint8_t pinDevid1 = 3; // Example : the mailbox switch is connect to the Pin 3

// Debug mode
boolean DEBUG = true;
  //////////////
 //   End    //
//////////////

char serverName[] = "api.pushingbox.com";
boolean pinDevid1State = false;                // Save the last state of the Pin for DEVID1
boolean lastConnected = false;                 // State of the connection last time through the main loop

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  Serial.begin(9600);
  pinMode(pinDevid1, INPUT);

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Serial.println("Please reconfigure the settings and try again.");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  else{
    Serial.println("Ethernet ready");
    // print the Ethernet board/shield's IP address:
    Serial.print("My IP address: ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop()
{
      ////
      // Listening for the pinDevid1 state
      ////
      if (digitalRead(pinDevid1) == HIGH && pinDevid1State == false) // switch on pinDevid1 is ON
      {
        if(DEBUG){Serial.println("pinDevid1 is HIGH");}
        pinDevid1State = true;
        //Sending request to PushingBox when the pin is HIGH
        sendToPushingBox(DEVID1);
      }
       if (digitalRead(pinDevid1) == LOW && pinDevid1State == true) // switch on pinDevid1 is OFF
      {
        if(DEBUG){Serial.println("pinDevid1 is LOW");}
        pinDevid1State = false;
        //Sending request to PushingBox when the pin is LOW
        //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable
      }

      //DEBUG part
      // this write the respons from PushingBox Server.
      // You should see a "200 OK"
      if (client.available()) {
        char c = client.read();
        if(DEBUG){Serial.print(c);}
      }

      // if there's no net connection, but there was one last time
      // through the loop, then stop the client:
      if (!client.connected() && lastConnected) {
        if(DEBUG){Serial.println();}
        if(DEBUG){Serial.println("disconnecting.");}
        client.stop();
      }
      lastConnected = client.connected();
}

//Function for sending the request to PushingBox
void sendToPushingBox(char devid[]){
  client.stop();
  if(DEBUG){Serial.println("connecting...");}

  if (client.connect(serverName, 80)) {
    if(DEBUG){Serial.println("connected");}

    if(DEBUG){Serial.println("sendind request");}
    client.print("GET /pushingbox?devid=");
    client.print(devid);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(serverName);
    client.println("User-Agent: Arduino");
    client.println();
  }
  else {
    if(DEBUG){Serial.println("connection failed");}
  }
}

If the code for the DHCP error is removed, it does display an external IP address, but actual HTTP requests do not work. I tried port forwarding and that did not work either.
EDIT:
Now, unusually, it gives me an IP address WITHOUT the ethernet cord connected.

can you get it working without all the pushingbox stuff?

No, not even the WebClient sample that Arduino provides works.

so what was the point of putting in all the pusingbox code?

also: how do you know you don't have a defective shield?

If you have connected directly to the router are you sure you have the right sort of cable.  Some older router/switches/hubs require crossed network cables.  Can you switch the cable with a cable that is connected to a device that you know is working?

@JayEye The point of the pushing box code is because I am trying to make a doorbell that sends notifications to my phone and computer. I don't know if I have a defective shield, but I do know that if I use WebClient and comment out the DHCP error, it does return a public IP address, but when I actually make an HTTP request, it says Connection failed. @Matt Both the iMac and the router display a public IP address, but when I go to the router's configuration, it doesn't appear to be connected on either the iMac or the router.

i meant, if you can't get it working at all, there was no point in posting the pushbox code. When you are trying to figure out what's wrong with a piece of code, you test individual pieces. If you are not confident that the network code is working, there is no point in including the pushbox code in the test!

The reason that I added the Pushingbox code was to state that I was using Pushingbox as a server to connect to. I didn't mean for it to be a big part of it, but even connecting with www.google.com doesn't work. Also, I have tested individual pieces. That is what I mean by the "Connection failed" part of the edit, was that the HTTP request part was displaying that, and I was confused on why it would be doing that. When I tested the actual Ethernet.begin(mac) part, it always showed Failed to configure Ethernet using DHCP, yet showed an external IP when I ignored that part.

If I understood your problem correctly then you might want to check this out,
it's more or less the same thing :D
DHCP Failing on Arduino Uno

The page is no longer available


text:
Getting RGB values from camera
I have a camera I'm planning on attaching to an arduino uno, that I want to take pictures and extract the average RGB value from each image.
This is the camera I have, but I've now realized that it takes pre-compressed JPEG images, and so I cannot make use of the data it's giving me.
I realize that an arduino is not the optimal tool to use in this case, but I'm curious as to whether there would be any way to decompress the images and convert them to a format I could use. It does not need to be fast, and I do not need to take the pictures quickly. I have experience with programming but have not done many projects with the arduino, so any help or advice is appreciated.

Here is the JPEG decoding algorithm if you want to give it a try. You only need the DC coefficient of every block, so you can skip a few parts of the decoding.

No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.
I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.
You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.
Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.

Notice that for getting the average color you only need the DC coefficient of every 8×8 block, which should significantly simplify the problem (at least you do not need to reverse the DCT). I'm not claiming it will fit in 32 KiB, but the OP may try if he finds it amusing.

Alright, this was what I was expecting to hear. Thanks!


text:
How can I maintain PWM output while still performing other tasks?
I want to generate a PWM signal that I can turn on and off with a button press without using interrupts.  Is there a way to keep the PWM output going while running other processes?

PWM just runs once started. It's all managed by a completely separate bit of silicon inside the chip.
Once you have done analogWrite(...) the PWM will just keep going until you tell it otherwise.

I was running this with Serial plotter yesterday and for some reason it kept interrupting the PWM when I was reading one of the analog channels.  I finally tested on an oscilloscope and it does work. Thanks!


text:
Error saying an included library is not
The IDE tells me the included library isn't? I tried restarting the IDE and my computer but it doesn't work. The other libraries work fine it's only with Keyboard that it fails.
My code:
#include <Keyboard.h>

int buttonState = 0;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);

  Keyboard.begin();
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState == HIGH) {
    digitalWrite(13, HIGH);
    Keyboard.press('A');
  } else {
    digitalWrite(13, LOW);
    Keyboard.releaseAll();
  }
}

Error log:
Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

D:\Documents\Test\Test.ino: In function 'void setup()':

Test:9: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();

   ^

D:\Documents\Test\Test.ino: In function 'void loop()':

Test:16: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
 Keyboard.press('A');

 ^

Test:19: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
     Keyboard.releaseAll();

     ^

exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

I see you are using an Arduino Uno.
An Arduino Uno cannot act as a USB keyboard - therefore the Keyboard library doesn't exist for it (the file Keyboard.h is seen as being empty).
You can only use Keyboard.h on boards where using Keyboard.h makes any kind of sense, such as the Leonardo.

Ok thanks. Should I delete the question because that seems obvious now?

@Atom: Did you find any other questions asking same?

@IgnacioVazquez-Abrams If he'd looked I'm sure he would have done. I know for a fact that I have answered the same question before.

No but I think they say it here https://www.arduino.cc/en/Reference/MouseKeyboard, it just isnt clear


text:
Enabling keyboard feature on Arduino with CH340G
I've seen here that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?

Maybe you can find/write a c/c++ program for the PC that reads a COM port and sends it as keystrokes. The hardware is pretty much fixed in your project. Unless you use an Arduino with 32uX aa a serial/USB interface chip.

No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.


text:
Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device
When I try to upload my program on the Arduino Uno Chinese clone, It says
 -> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

My Arduino Programmer: ArduinoISP
My Arduino Software version: 1.6.8
My OS: Linux Mint

Can you help me fix this error?

What is the serial port of your arduino?

My Serial port is /dev/ttyUSB0 . I am using Linux Mint .

if you do ls /dev/ttyUSB0 does it show something? If so, are you a member of the dialout group_

Run from a terminal: test -w /dev/ttyUSB0 || echo Error - if it tells you Error you don't have permission to access the device. If it tells you nothing then your permissions are fine.

@frarugi87, when I type  'ls /dev/ttyUSB0' , it shows me a message -> /dev/ttyUSB0

@Majenko , I typed your command, it shows nothing. It executes well.

You may have done this, but...  Did you install the Linux serial port driver for the serial-port-chip on the Arduino Uno?  Also, might you have more than one USB device emulating a serial port plugged into your computer?  That is, do you see /dev/ttyUSB0, /dev/ttyUSB1, ... ect?

"Arduino UNO chinese clone"...  Also consider the possibility of your Arduino containing a counterfeit serial-port-chip (FTDI chip).  There are versions of the FTDI Windows Driver that will reset counterfeit FTDI chip USB ID's to an unusable value. And other versions of the Driver that will inject extra characters (I think "COUNTERFEIT") into the serial stream.

@frarugi87 Hi, I encountered the same problem and I did your command and received No such file or directory  answer from the terminal. However I was formerly able to run programs, even "blink".

@Marine1 look at the dev folder, and see if you have a ttyUSB peripheral..

This could be any number of different problems.  Here are several common causes:

You have multiple USB serial port devices connected to your computer. Try using the command ls -l /dev/ttyUSB* to check if your computer thinks there are more than one terminal USB device.  Disconnect all of them, then only connect the Arduino Uno.  Then repeat the check.
You do not have permissions.  This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm.  You should NOT make a habit of this, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.
You have a counterfeit FTDI chip on your Arduino Uno that has been rendered useless by certain versions of the Windows FTDI Driver.  The USB IDs can get reset to useless values.  I believe the current FTDI Windows Driver no longer does this.
You did not install the Linux FTDI driver.  A driver is a program to abstract the hardware from the application.  In this way, different hardware can be treated the same by the application, simplifying the application.  However, the wrong driver/hardware combination may not work as expected.

FTDI drivers are not a separately installed item on most Linux distributions in the way they are with Windows.  Generally they would only need to be manually added to a very odd Linux such as might be found on an embedded or special purpose system or a custom build from scratch - the code has been part of the kernel source effectively forever and will be built and shipped as an automatically loading module in any ordinary full-featured Linux.

Don't run arduino IDE as root to test if permissions is at fault here. Run this command instead: sudo chown root:YOURUSERNAME /dev/ttyUSB0 to give yourself access to the tty device

I had the same problem and solved with the suggestion of ndemou:
sudo chown root:YOURUSERNAME /dev/ttyUSB0

This is a bad idea, in particular on a typical dynamically configured linux with udev or similar managing /dev nodes you will have to do it every time you connect the device.  Add your user to the appropriate group instead, which is a lasting fix.

@Greenonline - please don't make trivial edits of bad answers.

@ChrisStratton - Please, kindly refer to the Review Queue.

That means absolutely nothing.  This is a fundamentally bad answer, and that fact cannot be changed by format editing.  Additionally, even if this were a good answer, your edit would be pointless.  Such pointless edits waste everyone's time.  Kindly desist.


text:
Using Blynk to control stepper motor is jerky
I am using Blynk to try and control a 28byj-48 stepper motor using the ULN2003 driver and an Arduino UNO from my iphone via USB withe the iOS Blynk App.
Without using Blynk, my stepper is smooth and works fine:
  #include <Servo.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor  pins to Arduino pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);

  int pos = 0;    // variable to store the servo position

  void setup() {
    myStepper.setSpeed(600);
  }

  void loop(){
     myStepper.step(-500);
  }

But when I use Blynk, the stepper is so jerky and stutters terribly:
  #include <SoftwareSerial.h>
  SoftwareSerial SwSerial(10, 11);
  #define BLYNK_PRINT SwSerial
  #include <BlynkSimpleSerial.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,4-step mode
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor pins to board pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4 blah blah
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);
  char auth[] = "my auth key here";

  void setup(){
    SwSerial.begin(9600);
    Blynk.begin(auth);
    myStepper.setSpeed(600);
  }

  BLYNK_WRITE(1){
    myStepper.step(param.asInt());
  }

  void loop(){
    Blynk.run();
  }

I am using a slider on the app to control the stepper by the way. I am not sure what I am doing wrong, any suggestions?

Blynk runs over a network and therefore cannot respond in real-time nor consistently. You could have the Blynk slider control set a local variable which the motor controller would use for motor speed, but the basic motor-drive timing needs to be locally controlled and independent of network operations. The SimpleTimer library is one way; a timer interrupt would be another.

Ah I see, I'll look into the library and try come up with a solution! Thank you so much.

My guess would be you are suffering from a comms latency issue.

Are you using a local server or the cloud?
Is you iOS device connected over WIFI or 2G, 3G or 4G?
Is you device on the same subnet as you iOS device and local server?

I've never used blynk (I might do this weekend though), my best thought as to how to fix it would be to revise your approach.  When you are controlling devices over an unpredictable connection (Ethernet) you can't rely of messages to arrive in a certain order or at certain times.  You need to tell the device to do something and keep doing it until its done or its told to stop.
So in this case tell the device to rotate clockwise at a certain rate until it travels n degrees or it is told to stop.  Now you can't just tell the motor to make 20 turns, because that will make your app unresponsive.  What you need to do it tell it to turn 50 steps and then return to the control loop, if no new order has come in it should then go and do another 50 steps, if there is a new order then off it goes with the new task.
Hope that makes sense and helps.

Great! I have a better understanding of the cons when it comes to my current setup now. I am using the cloud and my iOS connection is independant of my PC's internet connection (connected to Arduino). My servo motors however work almost instantaneously and without any issues! I might have to consider swapping out my stepper for a servo which in my case would also work fine. I hadn't thought about using control loops, i'll definitely give it a go! I just started using Blynk yesterday and it seems absolutely awesome so far. Thanks for the help!


text:
BMP280 sensor not initializing
I am successfully using a BMP280 sensor via SPI connection with an Arduino Uno R3 board. I'm trying to run the same code with the same setup on an Arduino Ethernet. However the sensor is not initializing.
The setup function looks as follows:
void setup() {
    delay(1000);
    dht.begin(); // starts DHT sensor
    chk = dht.read(DHTPIN); // reads DHT status
    while ((!bmp.begin()) || (chk != 1) ) {
      // checks DHT and BMP status and shows red LED, in case one of them
      // wasn't found. Loops and resets timeout each time.
      wdt_reset();
      Serial.println("Could not find a valid sensor, check wiring!");
      digitalWrite(RED, HIGH);
      delay(300);
      digitalWrite(RED, LOW);
      delay(1000);
      chk = dht.read(DHTPIN);
    }
}

The code only returns the error message and does not initialize the BMP sensor (DHT is fine).
Full code:
#include "ThingSpeak.h"
#include <SPI.h>
#include <DHT.h>
#include <Ethernet.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xE5, 0xBF};
IPAddress ip(10,42,0,69);
EthernetClient client;

// --- Libraries --- //
#include <avr/wdt.h> // Watchdog, interrupts and reboots
#include <Adafruit_BMP280.h> // BMP library for BMP280

// --- Constants --- //
// DHT22
#define DHTPIN 7
// BMP280 (SPI)
#define BMP_SCK 13 // Serial clock pin for BMP (10k pullup to +5V)
#define BMP_MISO 12 // SDO, has 10k pullup
#define BMP_MOSI 11 // SDI, no pullup
#define BMP_CS 9 // CS, has 10k pullup
// LEDs
#define RED 5 // pin for LEDs
#define YELLOW 3
#define GREEN 2

unsigned long myChannelNumber = 115634;
const char * myWriteAPIKey = "***"; // removed for privacy reasons
float dht_temp;
float dht_hum;
float bmp_temp; // values from sensors
float bmp_press;
int chk; // DHT status (0 or 1)
int k; // counter variable
int number;
char COLOR;

// --- Initialization --- //
DHT dht(DHTPIN, DHT22); // initializes sensors
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);

void setup() {
  wdt_disable(); // disables watchdog for initial communication
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  pinMode(YELLOW, OUTPUT); // LED pins set as output
  pinMode(RED, OUTPUT);
  digitalWrite(YELLOW, HIGH); // starts yellow LED
  Serial.begin(9600); // begin serial connection with 9600 baud
  delay(500); // delay to get connection and sensors ready
  wdt_enable(WDTO_8S); // start watchdog timeout (4 sec might be too short)
  blink(RED, 3);
  Serial.println(bmp.begin());
  dht.begin(); // starts DHT sensor
  chk = dht.read(DHTPIN); // reads DHT status
  if ((!bmp.begin()) || (chk != 1) ) {
    // checks DHT and BMP status and shows red LED, in case one of them
    // wasn't found. Loops and resets timeout each time.
    wdt_reset();
    Serial.println("Could not find a valid sensor, check wiring!");
    digitalWrite(RED, HIGH);
    delay(300);
    digitalWrite(RED, LOW);
    delay(1000);
    chk = dht.read(DHTPIN);
  }
  Ethernet.begin(mac, ip);
  ThingSpeak.begin(client);
}

// --- Loop --- //
void loop() {
  wdt_reset(); // resets watchdog
  pinMode(GREEN, OUTPUT); // gets green LED ready
  digitalWrite(GREEN, LOW);
  delay(1600); // delay for sensors to be read. In total, at least 2 sec!
  dhtread();
  delay(5000);
  wdt_reset();
  bmpread();
  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  delay(5000);
  wdt_reset();
  delay(5000);
}

void blink(char COLOR, int number) {
  for (k = 1; k <= number; k = k + 1) {
    // blinks 3x to show that Arduino rebooted
    digitalWrite(COLOR, HIGH);
    delay(100);
    digitalWrite(COLOR, LOW);
    delay(100);
  }
}

void bmpread() {
  bmp_temp = bmp.readTemperature(); // reads BMP sensor
  bmp_press = bmp.readPressure();
  Serial.println(bmp_temp);
  Serial.println(bmp_press);
  if (bmp_press > 0.0) {
    // if sensor isn't attached, it shows 0.0 or negative pressure.
    // This is used as check criterion
    digitalWrite(GREEN, HIGH); // blinks green for good BMP values
    Serial.println("bmp ok");
    ThingSpeak.setField(3,bmp_temp);
    ThingSpeak.setField(4,bmp_press);
    delay(150);
    digitalWrite(GREEN, LOW);
  } else {
    // if pressure is 0.0 or negative, blink red
    // and print 0.0 to keep formatting
    digitalWrite(RED, HIGH);
    Serial.println("Error, BMP280 missing");
    delay(150);
    digitalWrite(RED, LOW);
  }
}

void dhtread() {
  chk = dht.read(DHTPIN); // checks if connection to DHT sensor is ok (0: no connection, 1: ok)
  if (chk == 1) {
    dht_temp = dht.readTemperature();
    dht_hum = dht.readHumidity(); // reads DHT sensor
    digitalWrite(GREEN, HIGH); // blinks once for successful DHT sensor values
    ThingSpeak.setField(1,dht_temp);
    ThingSpeak.setField(2,dht_hum);
    delay(150);
    digitalWrite(GREEN, LOW);
    delay(100);
  } else {
    // if no connection, blink red instead and print "nan"
    // (keeps formatting ok)
    digitalWrite(RED, HIGH);
    Serial.print("Error, DHT22 missing");
    delay(150);
    digitalWrite(RED, LOW);
    delay(100);
  }
}

The problem now is that it seems to initialize (bmp.begin() returns 1), but the sensor is still not reading a correct value (either 0.0 for both pressure and temperature, or a large negative pressure and very large temperature (-2602 Pa, 185°C). What might be the problem? I have tried it with another sensor of the same type, same result. Where else can I attach the CS wire to?

To what pins did you connect the BMP280? It could be that you are using a pin that the Ethernet module already uses. I suspect you are using Pin 10 as the chip-select for the BMP.

Ah no, I am using an Arduino Ethernet, that has the Ethernet module built in (not a shield). I am using 13 for SCK, 12 for MISO, 11 for MOSI and 10 for CS (for CS Ive tried the other free pins I have, 9, 8 and 7).

There is also a DHT22 sensor connected to it (on pin 6), which works fine: https://thingspeak.com/channels/115634
The bottom two fields show the BMP280 values (it returns 0.0 if it isnt connected)

As an update, I managed (somehow) to initialize the sensor by putting the CS on 7 (10 also works though) and disabling the SD card by pulling pin 4 high as output. It still fails to read the correct value though (and returns 0). Any other ideas?

Pin 10 is already used by the W5100.

But regardless of if I put it on 7, 8, 9 or 10, it doesnt work in either case..

You can only enable one 'chip-select' (CS) line at a time, that's how the devices know who you're talking to.   You say you got something to work by disabling the SD card... that would be your issue then... You're selecting the SD Card AND the BMP280 at the same time, they're both talking on the SPI bus.

Hm. When the SD card is disabled, it only sometimes initializes the sensor, but in either case, it never shows a valid value, no matter what pin. Is this an issue with the Ethernet board I am using? Maybe the SPI.h library can be changed to accommodate another pin?

Update the image and code in your question. Also include other stuff that you've tried so far.

The software must be OK, because it runs on the other board, so it has to be a hardware fault. The sensor is OK, because it works on the other board. Assuming the board isn't defective then it must be the way you have connected it.
You haven't included your pin designations. Some Ethernet shields use certain pins and prevent them being used by other devices. Is it possible that this could be the cause of you problems?

Documentation says to use pins 13-10 for SPI connections. This is how I defined the pins: #define BMP_SCK 13 (and the others in the same way), and later initialized the sensor with Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK); which worked fine on the Uno board.

From Arduino.cc - "Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega."
I don't know if this applies to you board.

I think you will need to change BMP_CS pin, but not to 4 because that's used by the SD card.

I changed it to 8 and 9, both seems to have the same result


text:
problem in integrating the slave code in attiny 84
I tried the whole process by using two arduino unos.It worked perfectly.
Though when i tried to replace the slave uno with attiny 84 uC it showed following errors in compiling.
Arduino: 1.6.7 (Windows 7), Board: "ATtiny24/44/84, ATtiny84 @ 1 MHz  (internal oscillator; BOD disabled)"

WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void setup()':

sketch_may12c:12: error: 'SPCR' was not declared in this scope

   SPCR |= bit (SPE);

   ^

In file included from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/WProgram.h:12:0,

                 from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/Arduino.h:4,

                 from sketch\sketch_may12c.ino.cpp:1:

sketch_may12c:12: error: 'SPE' was not declared in this scope

   SPCR |= bit (SPE);

                ^

C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/wiring.h:158:25: note: in definition of macro 'bit'

 #define bit(b) (1UL << (b))

                         ^

sketch_may12c:15: error: 'MISO' was not declared in this scope

   pinMode (MISO, OUTPUT);

            ^

sketch_may12c:22: error: expected unqualified-id before '.' token

   tinySPI.attachInterrupt();

          ^

C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void SPI_STC_vect()':

sketch_may12c:30: error: 'SPDR' was not declared in this scope

 byte c = SPDR;  // grab byte from SPI Data Register

          ^

exit status 1
'SPCR' was not declared in this scope

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Sounds like a bug in the core.

It has to do with SPI.

Could you post the content of sketch_may2c.ino as it seems this is where the erroneous code is.

#include <SPI.h>
char buf [100];
volatile byte pos;
volatile bool process_it;
void setup (void)
{
Serial.begin (115200);   // debugging
// turn on SPI in slave mode
SPCR |= bit (SPE);
// have to send on master in, slave out
pinMode (MISO, OUTPUT);
// get ready for an interrupt
pos = 0;   // buffer empty
process_it = false;

continued.....................
// now turn on interrupts
SPI.attachInterrupt();
}  // end of setup
// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
// add to buffer if room
if (pos < sizeof buf)
{
buf [pos++] = c;
// example: newline means time to process buffer
if (c == '\n')
  process_it = true;

}  // end of room available

}  // end of interrupt routine SPI_STC_vect

continued..................
// main loop - wait for flag set in interrupt routine
void loop (void)
{
if (process_it)
{
buf [pos] = 0;
Serial.println (buf);
pos = 0;
process_it = false;
}  // end of flag set
}  // end of loop

You are trying to compile the wrong program for the wrong chip.
The nice thing about the Arduino core library is that it enables you to
write code that is portable across various Arduino boards. However, this
library provides very limited access to the capabilities of the
underlying hardware. Then, it is quite common for users to mix Arduino
code with C statements that directly access the hardware registers.
Doing this provides full control over the hardware, at the cost of
reduced portability.
Just an example from your code:
SPCR |= bit (SPE);

This line is accessing the control register of the SPI port (SPCR means
“SPI Control Register”) in order to set to 1 the bit named SPE (for “SPI
Enable”). This is the “bare metal” way of turning on the SPI port.
Now, your problem is that, unlike the ATmega328P powering your Unos, the
ATtiny84 does not have a hardware SPI port. Thus the line above just
makes no sense.
The solution: you have to figure out some other means for your chip to
talk SPI. You could emulate it purely in software, but it would
certainly be more efficient to use the USI port. The USI (“Universal
Serial Interface”) is a multipurpose serial port found in many ATtinies.
It can be configured to do SPI, I2C or simplex/half-duplex UART.
Recommended readings:

AVR319: Using the USI module for SPI
communication, an
application note by ATmel
Using an ATtiny2313/4313 as SPI
master on the Arduino
Playground

You may be able to find ready-made libraries for doing this.