text:
How to connect a varying output voltage to the Arduino?
I have a smart meter and I want to connect my output pulse meter to the Arduino in order to count the pulses, but the problem is my  output pulse voltage is varying (between 1V to 17V approximately) and the Arduino accepts only a stable voltage (5V).
Therefore, how can I make my output pulse voltage stable to connect it to the Arduino?

Your question isn't clear about how many meters are involved, what you want to measure or find out, or the source of whatever it is you want to measure.  Explain better, and include a schematic if possible.  (You can draw a schematic by clicking the Schematic icon on the editing toolbar)

I have only one smart meter, this meter has a pulse output. what I want is counting the pulses of my meter using the Arduino. Now, my problem is the output voltage of my meter is varying. In addition, to connect my pulse output to the Arduino the output voltage should be stable and = 5V. Therefore, my question is how can I make the voltage stable since it's varying? (please see my circuit diagram I updated my question)

What is it varying between?

it's varying between 1V to 17V approximately

How about using an optocoupler? http://www.electronics-tutorials.ws/blog/optocoupler.html This would isolate the two circuits.

the Arduino is accepte only a stable voltage (5V). if so, get a real Arduino: a real arduino allows you to accept a logic 0 or a logic 1 and anything in between.

Your schematic contradicts your question: The question implies a voltage output from the meter, whereas the schematic shows the output as being electrically equivalent to a switch. Please clarify.

If “what I want is counting the pulses of my meter” means that you want to count the number of pulses the meter produces, you can use a circuit like the following to clip the voltage into the 0-to-5V range (as acceptable for inputs on Uno digital pins).

simulate this circuit – Schematic created using CircuitLab
Then, to count pulses, write a sketch that repeatedly reads the selected input pin.  Each time it changes from low to high, add one to your count of pulses.
If you don't have 5.1V zener diode like the 1N4733A, you could instead attach the anode of an ordinary diode to the junction of R1,R2 and its cathode (the cross-bar end) to 3.3V on the Uno.  This will clamp the voltage on the input pin to at most about 4V.  (Note, with such a diode clamp, there would be high-current problems if you subsequently changed the pin to a high output.  You could of course put a 100Ω resistor in series with the clamp diode if you are concerned about that.)

Thank you so much for that great answer!! So, if my voltage is still varying but in the range of 1 to 5V I still can connect it to the Arduino?

@fahd, right.  The resistor ratio shown will divide 17 volts down to about 4.6V.  Input voltages higher than 0.6*Vcc  (ie, 3V on a 5V system) are read as 1's, per Table 30-1. Common DC characteristics on page 313 of ATmega328 specs.  The absolute max voltage on any Pin except RESET is Vcc+0.5V, or 5.5V on a 5V system, so 4.6V is an ok input level.

If your pulse low-voltage is 1V, the divider will divide that down to 0.27V, which is adequately below 0.3*Vcc, or 1.5V on a 5V system, to read as a 0.

Can you be more specific on Vlow and Vhigh of the pulses? I would suppose that Vlow is always 0, and that the crest of the pulses can vary between 1 and 17V. Is that the case? That's quite different than when Vlow is 1V and Vhigh is 17V.

If, as I read it, the meter's output pulses between 0 for LOW, and [1v - 17v] for HIGH, then the signal will need to be conditioned by Schmidt trigger to bring pulses less than the MCU's minimum input HIGH level (~2v) up to something higher than than that level, to ensure they will be read as HIGH.

@JRobert, yes, a comparator would be needed in that case.  But because Fahd hasn't answered kxtronic's question about Vlow and Vhigh and hasn't provided a meter spec or part number, I'm going to leave my answer as it is.


text:
What are the unused pins in an Arduino L293D motor shield?
What are the unused pins in an Arduino L293D motor shield? I want to connect the shield using wires instead of directly mounting on top of the Arduino board.

Please edit your question to include shield's maker and part number and  tutorials, etc.   Add a link to its schematic if you have one.

It's similar to Adafruit's motor shield and works with Adafruit's motor library.

What if I don't use servo motor, Can I still use pin 9 and 10 as normal digital pins ?

Check out this Link. Here, you can find this explanation in Code. I hope it will helpful for you.
Pin usage with the Motorshield
---------------------------------------
Analog pins: not used at all...
A0 ... A5 are still available...
They all can also be used as digital pins.
Also, I2C (A4 = SDA and A5 = SCL) can be used.
These pins have a breadboard area on the shield.
Digital pins: used: 3,4,5,6,7,8,9,10,11,12
Pin 9 and 10 are only used for the servo motors.
Already in use: 0 (RX) and 1 (TX).
Unused: 2,13
Pin 2 has an soldering hole on the board, easy to connect a wire.
Pin 13 is also connected to the system led.
I2C is possible, but SPI is not possible since those pins are used.

source: Stack Exchange

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

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

sort: votes


text:
Use an electromagnet for reading induction as well
I have an electromagnet that I wish to use to pull a neodyne magnet closer.
I'm thinking of having the electromagnet sensing when the magnet is close, but when the magnet is running I'm pushing 12 volts through it and I don't want to fry my Arduino. How can I do the wiring to achieve this?
I only have to be able to use the magnet as a sensor while it's turned off.

You could drive the electromagnet with 12 V and at the same time read back the current through a small shunt resistor.

Just add a resistor an a clamping diode to the analog pin. That way overcoat age can't damage the Arduino pin.

You can use a hall sensor from an old computer fan.
If the magnet is not moving you are not going to be able to sense it with the coil of your electromagnet.
You can also decouple de input of your arduino with a cap in series with the coil, but again if the magnet is not fast enough you will have to use a bigger cap.
You can also make a voltage divider between your coil and sense from there. When the 12V are applied just add some code to offset the input signal.

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


text:
Did I damage my Arduino?
I was trying to build a Bluetooth controlled car. I was near completing it but what I did wrong was that I connected the 5 V output of L298 motor driver to 5V pin of Arduino where I was supposed to connect it in Vin. My Arduino got heated for a couple of seconds. Knowing that I immediately disconnected. Now serial port doesn't work in my Arduino. The serial port option turned gray. I even tried replacing the ATmega IC but got the same result. What might have happened?

sounds like you should be able to reprogram it with another ardunio and still use gpio

Yes, it sounds like you fried something.
I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.
What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino [ATMega16U2] or a clone [CH340G]) or one of the voltage regulators is unknown.
You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.

Ok I did the way you told me to do. The 5V pin is showing 5,03V and 3.3V pin is showing 3.3V exactly and I have powered up board for almost 15 minutes and none of the components got heated up..but what I noticed is that when i press crystal(applying certain force) in arduino D16 000l2 the light in L led turns off. And it also happens when I put my fingers in the soldered portion of 13th pin and below that.

Precisely which Arduino do you have?

Arduino uno r3 and I dont know if it is orginal or clone..

Where did you buy it?

Ok I live in Nepal. I purchase in local market of my area..

Can you post a photograph of it?

yes sure but I dont see any option to upload the photos. Please can u guide me . I have just joined this forum

Go to edit your question, then insert a picture where the cursor is by clicking the picture icon (a square with two triangles and a dot in it - it's supposed to represent a picture of mountains).

Thank you sir . Here you go . I have uploaded the picture when the board is normally powered on

That looks like a fake (clone) Arduino to me. Subtle, and it took close inspection, but the telltale signs are there. The biggest giveaway is the use of the serif font the Chinese fab houses seem to default to where it should be sans-serif (e.g., the word Digital).

Have you tried the normal things of changing the USB cable, and plugging in to a different USB port?

Yaa I did all the possible things but none of these worked....I even changed the ic but the same problem exist..I dont know if I shud install a bootloader manually or not..although I was informed that the bootloader was pre installed

Changing the main IC won't fix it since the problem is with the USB interface and that's a separate chip entirely (the small square one next to the USB socket).

I get it ..If I recall that chip also got humongously hot at that moment. I guess its probably better if I get a new one. Thanks for your support

The chip may have survived but just the soldering may have melted and the chip is no longer attached to the board properly. Or the chip may be toast. As you say, buy a new board, it's simplest. With a counterfeit board like that you can never be sure that the components are particularly any good.

Yes thats definitely right..

You fried it you should ALWAYS double check connections before powering on your arduino but I do suggest doing a normal power up without any connections to see what happens

I did the normal connection but nothing happens. Neither heating effect nor any other. Just the L led and on led powers on . And I cant use Serial Port . The option is greyed. When I upload any code consider the blink code it tells the com port missing. Is there anything I can do with this board or purchasing a new one shall be better.

I would prefer you to buy a new original Arduino as it would be quite difficult to repair any hardware issues (which is your issue) which would include soldering replacing and etc° and would be even expensive to buy new parts.

I guess so..Thanks fotlr the recommendation and help

The ATmega328 on these boards is 5V tolerant on GPIOs so it depends on where exactly you connected the cable.
GND pins, for example, would've been fatal.

I connected the positive 5V coming from motor driver to 5V pin of arduino and GND for both motor driver and arduino was made common..Everything happened when I connected in 5V pin when I was supposed to connect in Vin pin of arduino

it feel sad to hear that you just fried it up. Every mistakes gives opportunity to learn tons of knowledge.
In this case you supplied 5v supply to 5v output pin. If you've seen the datasheet of  8-bit AVR Micro-controller ATmega328/P you'll know that it just possess VCC for 5v supply pin (input) neither an output 5v pin. Its the job of voltage regulator attached next to the power jack to supply 5V to provide the necessary juice to the chip. If you supplied 5v to GPIO output pin then you may or may not have burnt the chip but for sure you burnt the arduino board ,technically its power control system. So i think it'll be better buying a new board rather then fixing it.But i salute your attempts.

Thank you bro..I appreciate that. And I wont make such mistakes from next time


text:
How to control Arduino robot wirelessly?
I have a few potentiometers connected to analog inputs in an Arduino UNO. These are then processed and then the servo motors start moving to move the bot.
I would like to keep the motors with the uno and send signals from the pots to the uno. I do not want to use a laptop or another arduino as the remote control. However.. XBEE and other related stuff will do... Thanks
Edit- The wireless solution has to cover a long range preferrably 1 mile.(I dont think I will get any that will cover a mile but I'll give it a try.)
Edit 2- I have 8 servos and 4 potentiometer. I don't necessarily need an xbee. However it may be used.

Do you have any ideas of how to start this, or are you hoping someone else will do it all for you?

I have googled all over and nothing seems to address what I need.... BTW - I am 13 years old

Nothing will address all of what you need. Build it up piece by piece.

I think this guy did something similar. E.g. XBee-PRO® 900HP has 4 ADC pins. Personally I'd use a second arduino to read the pots and send the data over e.g. IR. Cheaper that 2 XBees. Best of luck.

@Spiked3 - an RC set like that is basically a 2.4 GHz transceiver chip and the functional equivalent of an Arduino, on each end.  The only real arguments against the poster's idea are the complication of DIY vs. an off-the-shelf solution, and the price/size/power premium of an Arduino vs. a comparable bare microcontroller.  NRF24L01+ won't have quite the desired range, but is used a lot in DIY projects of this sort.

There are many different solutions for doing so.  Remember you only need to output one PWM pulse at a time.

You can use so many methods to achieve it,as you are a newbie.i would prefer bluetooth and an android app.use bluetooth hc-05 module and use an android app to control.use this app and send string and control arduino.
https://play.google.com/store/apps/details?id=mobi.dzs.android.BLE_SPP_PRO&hl=en

You need to find a way to do this without having individual wireless communication from each pot. There are boards that can communicate wirelessly that are small, however, most of these are around the size of a quarter developed by an electrical engineer. This presents two problems, first the wireless modules will be too big, second, you will need to do a lot of work before you have the experience necessary  to build something like this. I recommend changing a design decision.
Thus, in order to help you further we will need to know more information about your setup.


text:
How to flash the "atmega328" with AVRDUDE?
I have an external device using an ATmega328, not a ATmega328-P as used by the Arduino Uno.
Now I want to use AVRDUDE and an Arduino Uno to flash a hex file on this chip. Therefore I removed the ATmega that came with the Arduino and popped in the one without the "-P".
With the Arduino IDE, it doesn't work, so I tried AVRDUDE:
avrdude -c arduino -P com3 -p ATMEGA328 -b 19200 -U flash:r:sdint.hex:r

However, I'm doing something wrong here, because it does not work:

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
  ...

What commandline should I use to flash an Arduino Uno with an ATmega328?

Does it give any error messages?

I'm sorry I didn't provide them. I would have to get my whole setup here and disassemble the other device again. But I get different error messages with different command lines I tried. And I tried a lot of them.

When posting an issue on SE, if there is an error message, include it in the post - the error message usually says exactly what's wrong, if you can decode it. I think you are unlikely to get an answer if you don't post the error message.

I will update it then. Give me just a few minutes.

I have updated it with the error message.

I always had troubles getting these to work :(

do you know if the atmega328 has the bootloader in it?

It's probably a blank atmega328, so without a bootloader, right? Try uploading the sketch using Arduino as ISP

I don't know if it has a bootloader. Could be that it doesn't. Uploading a sketch using the Arduino IDE doesn't work. So how do I burn a bootloader (without modifying its functionality)?

This seems to be quite a common problem, and there are a number of problems, each with their own solution.

Make sure you have selected the right chip
Make sure you have selected the right serial port (when you unplug your board, it should disappear).
Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).
Make sure your Atmega chip has a bootloader on it
Try another cable
There may be a problem with your computer - try another computer
If using another helps, try reinstalling the USB serial driver
Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.
make sure nothing else is trying to use your serial port
Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).

If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (which I never got working) or you can use an ICSP like the http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs (which is what I use) - works great. They can be had for a few dollars from China.

I'm not even using the Arduino IDE, have you read my question? And... another cable........

I am sorry for offending you by mentioning the IDE, I have corrected it. As mentioned in my post, this error is a common error, and to save others from having to post another question, I have given as many possible answers as I could think of. Also note the answer at the bottom, which I have just added

Most likely I don't have a bootloader. The chip I'm using didn't come with an Arduino. It was part of a DIY circuit board. Can I burn a bootloader using an Arduino, without buying additional hardware?

Yes - using the first of the two links at the bottom - you'll need a working Arduino (with a bootlloader - you don't mention why you bought the new chip, so this may not be possible), and the separate chip (without the bootloader). Your mileage may vary, and if you have problems, I recommend getting the ICSP, which is cheap, and I've never had a problem with.


text:
Using an array as a queue
I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:
/*Setup Variables here*/
int nextState;
int currState;

/*Fill enum with all case names*/
enum cases{

  init;
  idle;
  case1;
  case2;
  leave;

};

/*Begin Program*/
void setup(){
  Serial.begin(9600);
  currState = init;
}

void loop(){
  switch(currState){

    case init:
      /*Prepare program here*/
      nextState = idle;
      break;

    case idle:
      if (input1){
        nextState = case1;
      }else if (input2){
        nextState = case2;
      }else{
        nextState = idle;
      }

    case case1:
      //Code for case1 here
      break;

    case case2:
      //Code for case2 here
      break;

  }

  currState = nextState;
}

I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?
Thanks in advanced for all the help!

You can use an array as a queue, if you use resetting indicies (or pointers) to circularize it, but if you end up with more than one thread (anything in an interrupt) be careful of consistency.  You could also I guess do it using a linked list, but that's a heavyweight solution for a chip with such limited resources.

Have an array with fixed size, and have two indexes. One pointing to the first/current item in the queue, the other to the last item in the queue.
(It actually better/easier to have the second index point to where the next item has to be written)
To add an item to the queue:

Check that that the queue isn't full (second index is the same as the first)
If not write to second index.
Increment second index, and modulo array/queue size, so it wraps around.

To read from the queue

Read value at the first index
Increment first index, modulo array/queue size

What Gerben says. This is the exact way to do it, and is explained clearly and simply. (Voted)


text:
STEPPER MOTOR CONTROLLER Using LEONARDO PRO MICRO
I want to Use LEONARDO PRO MICRO and A4988 Stepper Motor DRIVER to control Nema 17 Stepper Motor.

Please let me know how to hookup these together.
Please give me a circuit for this type of assembly with Arduino code.

You can simply make a google search;

Here is some code to get you started
// Declaration of variables
#define Step 7     // Pin that transmits the "step" order to the board
#define Dir  6     // Pin that indicates the direction of the rotation
int vit  =   10 ;   // Speed of the rotation (smaller means faster rotation)
int sens =   1  ;  // Rotation direction (0 or 1)

void setup()
{
  pinMode( Step  , OUTPUT );
  pinMode( Dir   , OUTPUT );
}
void loop()
{
    digitalWrite( Dir   , sens);
    digitalWrite( Step  , LOW);
    // Fabrication d'un "Pas"
    digitalWrite( Step, HIGH );
    delay(vit);
    digitalWrite( Step, LOW );
    delay(vit);
}

Just a google search and I got on [this site][2] which had the code I gave you.
I think you can also find some libraries that can do the work for you.
in case that you need to wait less than a millisecond, millis() won't be useful for you; instead, use delayMicroseconds() which will make you wait a thousandth (at minimum) of a millisecond.
EDIT
For what you asked you have to first get the voltage:
float voltage = analogRead ( 0 )  * (3.0 / 1023.0);

You just have to adapt your speed relatively to the voltage.
To do this, I suggest you the map function directly from Arduino site.
Be careful just because whatever you are doing, analogRead takes 100 microseconds to get the voltage, so if you need to go very fast you can't.  I suggest you to work with a different type of communication, like Serial, SPI or I2c.

Thanks, Can you tell me how can i control motor speed/RPM using a analog voltage which came from some other device. The voltage are range in 0-3V.

There you go. I edited the answer for your question


text:
Compile error in Ubuntu 18.04
I'm trying to compile a code to arudino pro micro, I have the right option for compiling like the port and the type of the board,but I get an error,I can't copy

did you start with Arduino on Linux now? did it ever work? did you set the access right to USB port?

Welcome to Arduino Stack Exchange. you have a issue about include <keyboard.h> . What your the library using?

I open arduino ide using ubuntu,this is my first time compile a code in linux

then please read the "Please read" for Linux https://www.arduino.cc/en/Guide/Linux#toc6

And I believe I chose the correct port

Did you join the dialout group as instructed in the guide?

post your code in proper tags, not an image.  Please read Arduino SE tour if you don't know how.

This is likely a permission problem.  The user likely does not have permission to read from and write to the port created when plugging in the Arduino.  This can be temporally fixed using the following command:
sudo chmod 666 /dev/ttyACM0

However, this procedure is only temporary as the port is recreated every time the Arduino is reconnected to the computer.  And upon recreation the permissions are reset to their defaults for security reasons.
A better solution is to determine the group which the port belongs to and to add the users expected to access these connected devices to that group.
Plugin and list the port to determine its group:
ls -l /dev/ttyACM*

or
ls -l /dev/ttyUSB*

The group the ports belong to will likely be "dialout".  Add the user to that group:
usermod -a -G dialout user_name

...where user_name is replaced by the name of the user who needs access to the port.  If you don't know the name of the current user you can use this command:
whoami

Sorry for the late reply,it worked in the ide that I download from the web,apparently ide from the ubuntu software won't work.
Thank for the answer

It's not the new IDE. It's the setup script that comes bundled with it that issues the usermod command suggested by st2000.

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


text:
Why does this code not respond promptly to changes in the LDR reading?
So, I wrote some simple code like this :
void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  Serial.begin (9600);
}

void loop() {
  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);
  delay(50);
}

The line will print the value of LDR sensor simultaneously, but when I add this "if" condition inside the loop :
 if (LDRValue < 100) {
   colorWipe(strip.Color(255, 0, 0), 50);
   colorWipe(strip.Color(0, 255, 0), 50);
   colorWipe(strip.Color(0, 0, 255), 50);
   colorWipe(strip.Color(0, 0, 0, 255), 50);
   theaterChase(strip.Color(127, 127, 127), 50);
   theaterChase(strip.Color(127, 0, 0), 50);
   theaterChase(strip.Color(0, 0, 127), 50);
   rainbow(20);
   rainbowCycle(20);
   theaterChaseRainbow(50);
  }

the LDR  value only printed once..
Is it a wrong "if" condition code ? I know it's kinda lame, but please give me some starting point, doesn't need to be fancy just a small lead will do, thanks!
edit : complete library

Guess: Try putting the delay before serial.print(). Sometimes LCD can prevent serial from working for a short time.

How are your functions inside the if block implemented? With delays?

Visual Micro, it has nothing to do with LCD tho, @gre_gor its just looping one after another, no delays in it. It's a LDR + WS2812b LED code, with neopixel library if anyone else need extra information.

Did you try @VisualMicro's suggestion of putting a delay in?

How are you supplying power to the ledstrip? Does it work without the strip attached? It may be that you're trying tot supply the ledstrip with power from the Arduino, and it may simply dip if you try to set the leds on.

Alternatively the code may loop endlessly or get a watchdog timeout.

You ought to post your complete code if you hope for a good answer rather than best tries and guesses at best. What is strip, how are all values declared and initialized, where do all functions colorWipe... come from?

Your code matches this example and those functions are blocking execution with delays.

Thank you all for your concern, and gre_gor, thanks for pointed the real problem, is there anything i can do so the LDR value could printed normally? what should i change? void colorWipe(uint32_t c, uint8_t wait) {   for(uint16_t i=0; i<strip.numPixels(); i++) {     strip.setPixelColor(i, c);     strip.show();     delay(wait);   } }

After all effect, the value should be printed neverthless?  You said it would only print once?

that is correct Paul, my mistake, it does printed again after all the loop called, never waited that long before you pointed that out

I'm going to lever off gre_gor's comment on the question.
The code you are calling (for example, rainbow) has delays in it:
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

So we can see straight away that calling rainbow(20); is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!
Then you call rainbowCycle(20); and then theaterChaseRainbow(50); so you won't get back to the main loop for a while.
How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.
An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {

    int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
    if (LDRValue >= 100)
       return;

    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

Suggested improvement to example
The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

typedef bool (*AbortFunction) ();

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// function prototypes
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

const byte LDRSensor = 0;

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

void loop() {
  // start with black
  colorWipe(strip.Color(0, 0, 0), 0); // Black

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
  colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
  colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
  theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
  theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

  rainbow(20, checkLDR);
  rainbowCycle(20, checkLDR);
  theaterChaseRainbow(50, checkLDR);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    if (fAbort && fAbort ())
      return;
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      if (fAbort && fAbort ())
        return;
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    if (fAbort && fAbort ())
      return;
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.AbortFunction fAbort
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

The important addition is to add another optional argument AbortFunction fAbort to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns true then the display function exits (thus avoiding the delays), like this:
if (fAbort && fAbort ())
  return;

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.
The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:
bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

That function is passed as an argument to the other functions, eg.
rainbow(20, checkLDR);

I have a page about writing callback functions.

i'll try this out now, i'll get back to you with the result in a couple hours, thank you very much everyone!!

Sorry Nick, i can't make it to try this out yesterday, but I went to your page and this solve the problem, thanks for the answer and your time to explain them all, thank you very much Nick, and everyone else here too!

authors: ร้านสามารถ โปรเจ็ค


text:
Arduino Motor Shield

It seems that I can't get the DC Motor function to work while also having servos driven off the other ports :(
#include "Arduino.h"
#include <Servo.h>

int pinI1=8;//define I1 interface
int pinI2=11;//define I2 interface
int speedpinA=9;//enable motor A
int pinI3=12;//define I3 interface
int pinI4=13;//define I4 interface
int speedpinB=10;//enable motor
int spead =220;//define the spead of motor

Servo SteeringServo;  // create servo object to control a servo

void setup()
{
  // Steering servo pin setup
  SteeringServo.attach(5);  // attaches the servo on pin 9 to the servo object

  pinMode(pinI1,OUTPUT);
  pinMode(pinI2,OUTPUT);
  pinMode(speedpinA,OUTPUT);
  pinMode(pinI3,OUTPUT);
  pinMode(pinI4,OUTPUT);
  pinMode(speedpinB,OUTPUT);

  Serial.begin(9600);

}

void forward()
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,LOW);//turn DC Motor A move anticlockwise
     digitalWrite(pinI1,HIGH);
}
void backward()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void left()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void right()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,LOW);//turn DC Motor A move clockwise
     digitalWrite(pinI1,HIGH);
}
void stop()//
{
     digitalWrite(speedpinA,LOW);// Unenble the pin, to stop the motor. this should be done to avid damaging the motor.
     digitalWrite(speedpinB,LOW);
     delay(1000);

}

void loop()
{
  left();
  delay(15000);
  stop();
  right();
  delay(1000);
 stop();
 // delay(2000); Already commented out
  //forward();
 // delay(2000);
 // stop();
// backward();
  delay(12000);
  stop();
}

Your code:
int speedpinA=9;//enable motor A
...
int speedpinB=10;//enable motor
...
 analogWrite(speedpinA,spead);//input a simulation value to set the speed
 analogWrite(speedpinB,spead);

See https://www.arduino.cc/en/reference/servo

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

(My emphasis).
So, you can't do that, exactly. Perhaps choose other pins for the analogWrite, pins that analogWrite supports, that are not 9 and 10.


text:
Renaming folders in Arduino Uno' SD card
I want to rename folders through the SD shield but it does not rename them, because It renames It in another default name
How Can i rename it using the name that I want?

According to this post (https://forum.arduino.cc/index.php?topic=73265.0) this library should be able to rename the folders (https://github.com/greiman?tab=repositories) but there are a lot of posts out there saying they are having problems.
It might be worth checking you can rename them on a PC, there may be problems with name lengths etc that will just complicate matters.

It looks like all of the problems mentioned in the forum.arduino.cc post are due to the obtuse asker insisting on keeping duplicative calls to the obsolete SD.h wrapper alongside using SdFAT for renaming.  In other words, all self-inflicted problems.


text:
Arduino Mega PWM doesn't work in C Code
Why such horrible Arduino's Mega PWM doesn't work??
Below is my code.
I try to set Fast PWM 8-bit to dim and light up a LED connected to OCR1A Pin. I try to do it in C language, completelly without Arduino's lbraries and it doesn't work at all.
I'm working with documentation and the code seems me to be correct. Almost the same code worked on ATmega8 and ATmega16 (obviously, with special setting for those special ATmegas) but this one doesn't.
The comments in this code point out, that I tried to use few other flags to  check if it work with some of another settings.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

//Anode of LED connected to OCR1A (digital pin 11)
#define LED (1<<PB5)

int main()
{
  DDRB |= (1 << LED);

  //FAST PWM 8-bit, set OCR1A at the Bottom
  TCCR1A = (1 << COM1A1) | (1 << WGM10);    // | (1<<WGM11) | (1<<COM1A0)
  //Prescaler :1024
  TCCR1B = (1 << CS12) | (1 << WGM12);     //| (1<<WGM13); //Presc :1024  (1<<CS10) |
  //Enable to interrupt Compare Match A
  TIMSK1 = (1 << OCIE1A);

  uint8_t i;

  sei();

  while (1)
  {
    for (i = 0; i < 255; i++)
    {
      OCR1A = i;
      // _delay_ms(5);
    }

    for (i = 255; i > 0; i--)
    {
      OCR1A = i;
      //_delay_ms(5);
    }
  }
}

}

In what way does it "not work"?

The program has been compiled and send to Arduino board (via Arduino IDE) but the LED, which should be  dimmed and lighted up doesn't work.

I'm not sure this is right:
#define LED (1<<PB5)

Since later on you use:
DDRB |= (1<<LED);

That would expand out to:
DDRB |= (1<<(1<<PB5));

That would equate to:
DDRB |= (1<<(1<<5));

Take it a step further:
DDRB |= (1 << 32)

Shifting 1 to the left 32 times on an 8 bit register results in:
DDRB |= 0;

Which of course does nothing.
I can't comment on the rest of the code, other than to say "without delays in your loops you won't get much sense out of it".

My oversight.... Obviously, You're right. Now the LED is active. It means that it lights. But lights constantly without any charges in brightness. So, I tried to add small delays (several ms) within "for" loops but it doesn't influence the LED brightness changes. Changing in delays just causes that the LED lights darkly or brightly, but still constantly.

Majenko showed you one of your mistakes.
Then you wrote:
//Enable to interrupt Compare Match A
TIMSK1 = (1<<OCIE1A);

And this is your other mistake. You should not enable an interrupt
unless you have defined an ISR for it. Otherwise your program will
restart every time the interrupt fires.

My advice. Stay simple. Try to get your code to output a duty cycle first. From there try to get your code to vary the duty cycle.
Once you do that the issues with your code will be clear.


text:
Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield
I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.
When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.
When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.
When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.
Any ideas as to why this is?

Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from BLEshield
Therefore the BLE shield uses 6 pins e the Braccio uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.
You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example

This really helped, I managed to get a Bluetooth module and find the pins that were not in use.


text:
Arduino Uno Wunderground weather station - Ethernet connection failed
I'm new to Arduino. For my first project, I've decided to build a weather station where data is collected via sensors and is then sent to Wunderground. I'm using an arduino uno, an ethernet shield as well as a DHT22 sensor for temperature and humidity.
Everything worked for an hour and then I'm getting "connection Failed" constantly.
I would really appreciate it if you could look into my code. I've tried everything and it doesn't explain the sudden failure of the project. I occasionally get a successful upload after dozens of connection failed messages.
Here's my code. I've removed my weather station password for security reasons.
#include <Wire.h>
#include <SPI.h>
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "DHT.h"

// Sensor Pins
#define DHTPIN 7
#define DHTTYPE DHT22
// Variables
float temp;
float hum;

byte mac[] = {
  "de,ad,be,ef,fe,ed"
};
EthernetClient ethernetClient;
unsigned int localPort = 8888;
// Wunderground server details
char SERVER[] = "rtupdate.wunderground.com";
char WEBPAGE[] = "GET /weatherstation/updateweatherstation.php?";
char ID[] = "ICHESTER24";
char PASSWORD[] = "iwqnrlex";

DHT dht(DHTPIN, DHTTYPE);
unsigned int connections = 1;
unsigned int timeout = 30000;

void setup(void) {
  Serial.begin(38400);
  Wire.begin();
  dht.begin();

  // Connect to internet
  Serial.print(F("\nInitialising Ethernet module"));
  if (Ethernet.begin(mac)){

    Serial.println("Initialisation completed successfully!");
  }
  else {
    Serial.println("Something went wrong during ethernet module setup!");
  }
} //END OF SETUP

void loop(void) {
  hum = dht.readHumidity();
  temp = dht.readTemperature();
  float tempf = (temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  float dewptf = (dewPoint(tempf, hum));
  Serial.println("++++++++++++++++++++++++++");
  Serial.println("temp = ");
  Serial.println(tempf);
  Serial.println("Humidity = ");
  Serial.println(hum);
  Serial.println("DewPoint = ");
  Serial.println(dewptf);
  // Send all data to WUNDERGROUND
  if (ethernetClient.connect(SERVER, 80)) {
    ethernetClient.print(WEBPAGE);
    ethernetClient.print("ID=");
    ethernetClient.print(ID);
    ethernetClient.print("&PASSWORD=");
    ethernetClient.print(PASSWORD);
    ethernetClient.print("&dateutc=");
    ethernetClient.print("now");
    ethernetClient.print("&tempf=");
    ethernetClient.print(tempf);
    ethernetClient.print("&humidity=");
    ethernetClient.print(hum);
    ethernetClient.print("&dewptf=");
    ethernetClient.print(dewptf);
       ethernetClient.print("&softwaretype=Arduino%20UNO%20version1&action=updateraw&realtime=1&rtfreq=2.5");//Rapid Fire
    ethernetClient.println();
    Serial.println("New data uploaded");
  }else{
    Serial.println("Connection Failed...");
  }
  delay(2500);

}
void resetEthernet() {
 ethernetClient.stop();
 delay(1000);
 Ethernet.begin(mac);
 delay(1000);
 ethernetClient.available();
}
double dewPoint(double tempf, double humidity)
{
  double A0= 373.15/(273.15 + tempf);
  double SUM = -7.90298 * (A0-1);
  SUM += 5.02808 * log10(A0);
  SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
  SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
  SUM += log10(1013.246);
  double VP = pow(10, SUM-3) * humidity;
  double T = log(VP/0.61078);
  return (241.88 * T) / (17.558-T);
}

I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection.
This means after sending u need to close the connection. (else it will work 4 times).
ethernetClient.stop()
Just before or after
Serial.println("New data uploaded");
https://www.arduino.cc/en/Reference/ClientStop


text:
How to measure relay current draw from Arduino
How does one measure the amount of current a relay is drawing from an Arduino?
Do I connect a multimeter in series with the digital pin to which the relay 'IN1' is connected (in this case pin 7), the 5V pin or GND pin?
Provisional testing gives me the following results (when the relay is ON):

Pin 7: 3.93 mA
5V pin: 70.2 mA
GND pin: 66.8 mA

Also, assuming I pull more than 40 mA through digital pin 7 for a number of seconds, is the pin likely to fail immediately? Or slowly degrade over time?

What relay has an "IN1" pin? All mine have two coil pins and three or six switched pins.

My guess is you are using a relay (breakout) board, not a bare relay. 70mA sounds about right for a 5v relay. Which is indeed more that a digital pin can handle.

Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?
Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground.  Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.
So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.
In answer to your second question, read the datasheet.  It quite clearly states:

Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:
ATmega48PA/88PA/168PA/328P:

The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.
The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.
The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.

If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

And also a similar note for sourcing current.
So although they can sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.
Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down.  Hence the note about under steady state conditions.
So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.
Furthermore, the MOSFETs in the IO pins act like resistors when turned on.  As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor.  Increase the current and you increase the voltage across the resistor.  Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin.  So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.

You are correct, the relay is a module board identical to that of the SainSmart 5V. Thanks for the detailed reply.


text:
Reading a part of bitmap image on Arduino
I'm pretty much a beginner when it comes to programming and have only recently started learning C++. Right now I'm stuck trying to covert a bitmap into a binary array. This is for a Robotics competition I've entered. The bitmap is a 54*96 pixel monochromatic 1 bpp image. I'm confused with the offset positions while trying to read the header. This is the code I've written so far and would greatly appreciate any help. I think the error lies in increment of the lineNo variable which needs to be in hex, but how to increment such values?
What I want to ultimately achieve is to read only some parts of the bitmap particularly the boxes with cross on them (see image below). How do I find out the pixel locations?
#include <SD.h>
#include <SPI.h>
File bMap;
File Text;
void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  int height = 0;
  int width = 0;
  int  bitmapOffset = 0xa;
  bMap = SD.open("map.bmp", FILE_READ);
  Text = SD.open("test.txt", FILE_WRITE);
  \\bMap.seek(0xa);
  \\bitmapOffset = bMap.read();
  \\Serial.println(bitmapOffset, BIN);
  \\Serial.println(bMap, HEX);
  bMap.seek(0x16);
  for (int i = 0; i < 4; i++) {
    height += (bMap.read() << (8 * i));
    Serial.println(height);
    int lineNo;
    int fileposition = 0;
    for (lineNo = 0; lineNo < height; lineNo++)
      fileposition = bitmapOffset + (lineNo);
    bMap.seek(fileposition);
    //Serial.print(lineNo);
    Serial.print(fileposition);
    //Serial.print(bitmapOffset);

  }

  bMap.seek(0x12);
  for (int i = 0; i < 4; i++) {
    width += (bMap.read() << (8 * i));
    Serial.println(width);
    if (Text) {
      Text.println(height, width);
      Text.close();
    }
  }
}

void loop() {}

Is it an actual Windows BMP image file format?  That's not a trivial format and you need to understand it intimately.

Yes, it is. I have been reading about them and this helped greatly https://upload.wikimedia.org/wikipedia/commons/c/c4/BMPfileFormat.png but still confused as of how certain values correspond to certain positions. I haven't been able find a comprehensive guide on it yet.

Any coordinate in a bitmap (note: the term bitmap here [all lower case] refers to the concept of a grid of pixels, not the Windows BMP file format which I will always refer to as BMP all in capitals) can easily be calculated as long as you know the width.  The height is only needed to stop you going too far.
Any pixel offset in a buffer of pixels is calculated as y * width + x assuming a left-right / top-down pixel arrangement in the buffer.
The information you are really interested in with your bitmap is actually considerably less than is in the BMP that you show.  Your BMP is 56x96 pixels, but the information you actually care about is actually only in a resolution of 7x12 blocks.
It would be far simpler if you could pre-process the provided BMP on a PC to create an array of 84 entries each with a different tag or value to represent what it is.  Your image there could then be represented as the array:
{ 3, 3, 3, 3, 3, 3, 3,
  3, 1, 0, 0, 0, 1, 3,
  3, 0, 0, 0, 0, 1, 3,
  0, 0, 1, 1, 0, 0, 3,
  3, 2, 1, 0, 0, 0, 3,
  3, 1, 0, 0, 1, 0, 3,
  3, 0, 1, 0, 0, 0, 3,
  3, 0, 0, 0, 2, 0, 3,
  3, 0, 0, 1, 0, 0, 3,
  3, 1, 1, 0, 1, 0, 3,
  3, 0, 0, 0, 0, 0, 3,
  3, 3, 3, 0, 3, 3, 3 };

Where 0 is an open white space, 1 is a closed black space, 2 is a black space with a cross and 3 is a border space.
The two crosses would then be calculated as (1,4) = 4 * 7 + 1 = 29 and (4,7) = 7 * 7 + 4 = 53.
Working with BMP files is somewhat more tricky.  They come in multiple depths and multiple bit arrangements, as well as different versions with different header sizes.  They also have different padding requirements for different line lengths and bit depths, and are generally a rather nasty file format all round.
And on top of that they are upside down.  BMP is the only file format I know of where 0,0 is at the bottom left instead of the top left.  Consequently you have to invert all your Y coordinates to make sense of it, and parsing a BMP file from the top down is really slow because you have to keep jumping backwards in the file.
So it would be much better if you could write a program on a PC using software which already understands the BMP format and can render it into a buffer for your program to then parse each block to work out what it is and build up a small 84 byte file of the actual information you need for your robot.
If you must read the BMP file directly on the Arduino then I have code you use to help you.  It's not designed for the Arduino but for the chipKIT boards (though it's very similar) and is designed as part of my DisplayCore framework for chipKIT (and other more powerful) boards, but you are welcome to take whatever bits you like, or just use bits to give you more insight into how BMP files work.  You can get the code from Github here: https://github.com/MajenkoLibraries/DisplayCore/tree/master/ImageReaders/BMPFile
To parse your bitmap into an array you would have to take each 8x8 block of pixels and work out what shape is in it - whether it's all black, all white, a cross, or a border piece.

Wow, Thanks just the explanation I was looking for.


text:
Arduino Uno not able to handle 2-dimensional array

Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.
Code:
void setup()
{
  Serial.begin(9600);
  int image_width = 56;
  int image_height = 96;

  int image_result[image_width][image_height];
  for (int i=0; i<image_height; i++) {
    for (int j=0; j<image_width; j++) {
      image_result[j][i] = 5;
    }
  }

  Serial.print("code works");
}

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?
Do 2 dimensional arrays work differently in Arduino or is it a space issue?

Even a one-dimensional array of 5376 bytes, on a processor with 2048 bytes, will fail.

I meant, 10752 bytes. I overlooked that each array item is 2 bytes. Bear in mind you don't even have all of those 2048 bytes available. The Serial transmit and receive buffers alone use up 128 bytes.

Well if I connect a micro-SD car is there some method to declare array in that memory?

You can connect a SD card and write data to your heart's content. However you can't "declare the array in memory" on it. What is your application here? An Arduino with 2 KB of RAM isn't the best thing for image processing.

I need to read a small BMP file in an array of ints in Arduino and need to do some processing on it. And the file size is 56 by 96 pixels.

You are going to have to re-think this. You can't read and "do processing" on 10752 bytes of pixels on an Arduino with 2048 bytes of RAM. Maybe on a Due you could do it. Do 2 dimensional arrays work differently in Arduino or is it a space issue? - it is most definitely a space issue.

What is different on Due? Plus can Mega 2560 work for this?

What if I save the image data on flash memory and if I do some processing save the results to flash memory too. Will this approach work?

Plus can Mega 2560 work for this? - the Mega has 8 KB of RAM, if that answers your question. You want 10.5 KB.

The Due has 96 KB of RAM. That looks more appropriate.

2D arrays work fine on arduino, but you run out of space very quickly.
An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.
I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.

Not only over memory, but probably also over all the I/O registers.

16 bit addressing, with SRAM starting from 256. So that's 65279 bytes of address space. So you won't reach that. Also, I'm pretty sure there is some kind of protection preventing this from happening.

There is no protection. The CPU registers are memory-mapped starting at address 0, then the I/O registers from address 32, then the statically-allocated RAM starts at address 256.

You are trying to use more memory than you have available: 96 * 56 * 2 = 10.752KBytes. Not much that the MCU can do when this happens.
If you look into the datasheet, you'll see that your microcontroller (ATmega328p) only has 2KBytes of RAM.
I guess the question then, is to ask yourself if you really need that large an array. You may consider getting an external flash chip or an SDcard shield. If you only need it for read-only purposes (such as a lookup table), you can use some of your flash program memory (you have 32KBytes).

I'm using a SDcard sheild but I'm reading the data into an array declared like this. How would I be able to use the SD Card memory.

You don't usually need to deal with all 5376 elements of your array at one instant. Consider dividing up your image into smaller chunks for processing. Depending on the kind of processing that you do, you may require different smarts to optimize the process. ;-)

Can one write data on the flash memory again and again. What do you mean by read-only? How does one write the data once on it. For example I want to write the image data on the flash memory one. How will I be able to do it?

I am referring to your program flash memory. AFAIK, you can only write to the program flash during programming. One you boot your MCU, the program flash is used as read-only memory (so that we don't mess up the program when it's running.) Since you want to write your data, the program flash is not suitable.

Do you really need to process the whole image in one go? As I've mentioned before, you can divide your image to smaller blocks, say chunk[8][8] would be a comfortable size for Arduino to swallow, and it works well even if you use convolution filters. (Having said that, I must stress that the Arduino Uno is ill-suited for any serious image processing application.)

This is what I fed my Uno:
#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

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

  int i, j;
  int image_result[IMAGEWIDTH][IMAGEHEIGHT];

  for (i = 0; i < IMAGEWIDTH; i++) {
    Serial.print("\nIMAGEWIDTH ");
    Serial.print(i + 1);
    Serial.println(":");
    for (j = 0; j < IMAGEHEIGHT; j++) {
      image_result[i][j] = i + j;
      Serial.print("image_result[");
      Serial.print(i + 1);
      Serial.print("][");
      Serial.print(j + 1);
      Serial.print("]: ");
      Serial.println(image_result[i][j]);
    }
  }
  Serial.println(F("\nDone!"));
}

void loop() {
}

This will run over the whole array, while printing progress over Serial, which then print "Done!" once it is. I suggest changing:
#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

To lesser values, unless you have a few good minutes at hand.

This is not at all going to solve his problem. It isn't time, it is the size of the array. 56 * 96 * 2 (an int is two bytes) uses 10752 bytes. Your Uno has 2048 bytes. The issue is not time, it is storage.

Nick was right, this hasn't solved my problem. Anyway, thanks for trying.

Indeed, this is an issue of RAM available. If you do not need 8 bits per piece of data (if you are perhaps willing to reduce image quality, for example), consider compacting your data such that you have multiple piece of data per bit. For example, hex values or BCD (binary coded decimals) could work, depending on the size of each piece of data.

The OP wants to read a BMP file into memory, so I doubt it can be turned into BCD very usefully.

That's a good point. Perhaps he's willing to significantly decrease his image quality? Either way, additional storage would be wise.

In case the matrix is mostly empty or anyway has values that can be calculated programmatically, sparse arrays might come to the rescue. It requires memory allocation and hopping, so the access time to individual elements is not deterministic, but you can calculate the worst-case scenario.

As others have noted, your array is larger than the available RAM in your Arduino. Others mentioned Flash memory which could be a solution for you. Your Arduino has 32 KB of memory which could hold your array. See the following reference for more info about Flash memory. Keep in mind that Flash and EEPROM have a limited number of write cycles before becoming unreliable.
Hidden Powers - storing data in Flash and EEPROM


text:
UltraSonic sensor in rain?
I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.
I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?
Is there any alternative solution for ultrasonic sensors?

Try it and see? Wrap your sensor in something waterproof like a latex glove finger, and then put it in the rain. See if you get false readings. Or just take it into the shower with you. ;)

@NickGammon Wouldn't you just be sensing the distance of the latex from the sensor?

Yup, @Majenko is right!

There are special weather proof ultrasonic sensors available, like the one at the bottom of this page: http://www.futurlec.com/Ultrasonic_Sensors.shtml  Note: that is just the transducer, it needs extra circuitry to get it to work (similar to the circuit on the SR04) so don't just buy one and plug it into your Arduino then complain that it's not working.

Wouldn't you just be sensing the distance of the latex from the sensor? - possibly. That's why I suggested trying it. assuming i somehow achieved to water proof the sensor - in what way would you waterproof it without some sort of covering?

No i thought of making a case where in which drill 2 holes for trig and echo meshes and hot glue them from inside.i hope you get my point. Just like this http://www.amazon.in/Clear-Case-Arduino-UNO-Transparent/dp/B00HFSWC06?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=54a371d4-b4ac-459e-b9c7-31f5e1299310&kpid=B00HFSWC06 where in they did for debug and power cords

Those sensors have a minimum range they can detect. Something like 2cm. So anything nearer than 2cm will not be detected.

@narzan I think the person asking the question was referring to water droplets in front of the sensor (assuming i somehow achieved to water proof the sensor).

oh ok :)  "1 up"

I tested the idea of covering the sensor with latex and can confirm that it does not work. :)

will the buzzer make continuous sounds

If you mean the sensor will detect the rain drops in the air
Nop it's tiny to read it in the air
But if there is drops on the sensor your sensor will not gives you the right reading
There is a water proof ultrasonic sensors available.
I am working on water level devices, after long path of searching in different ultrasonic sensors and after I tried a lot of method like using water proof Cloth, I found the best way is using water proof sensors PLUS water proof cloth.
water proof sensors work perfectly in high humidity but at the same time if there is a water drop on the sensor the reading will be different, and for that some cars manufacturers used not only one sensor, to avoid the errors. and calculate the differences.

The left car used old technology with separate sensors, but that's make errors the only good thing was to detect more things, in the next generation they mix them together.
water proof cloth will make the water drops not stuck at the sensor, but you will need to replace it every 5-6 months. "in your case because the sun will destroy the cloth" in my case and because my sensor inside tanks that's will least more.
I tried to spray the sensor with a different material to make my sensor not catch any water drops, it dose not work too.
And to make my cheap sensor water proof, I tried to use ceramic layers, and that's not work too, they use it with ultrasonic fog maker, these layers not work with cheap ultrasonic sensors, it's need a lot of power to vibrate it and different frequency. and of course you need to replace the layers "depending on the environment"
If you find ultrasonic car sensor with special material for water drops just let me know, I am searching on that too.
NOTE These days car manufacturer use different ways, in the past the cover was vibrate itself and made from aluminum, now they cover it and make different filters to ignore the plastic cover, How?! maybe it's different plastic or material maybe they find away to vibrate the plastic! sorry I could not find the secret.

thanks for sharing the information:) ,,,,As you said i will  use two sensors and compare among the data to make decisions ..

Ya that's will be more better :) you are welcome

It would probably be easier to use an IR distance sensor.  That would also be easier to waterproof.

Just a thought, a lot of cars use them, why not try your local salvage yard you may be able to get them on the cheap.


text:
expected primary expression before ')' token
#define ANALOG_IN 0

void setup() {

  Serial.begin(19200);

  analogReference(INTERNAL);

}

void loop() {

  int val = analogRead(ANALOG_IN);

  Serial.print(0xff, byte);

  Serial.print( (val >> 8) & 0xff, byte);

  Serial.print( val & 0xff, byte);

}

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

if you want to send a byte use Serial.write()

Why are you putting byte there? That isn't in the Serial.print reference page.
This compiles OK:
#define ANALOG_IN 0

void setup() {
  Serial.begin(19200);
  analogReference(INTERNAL);
}

void loop() {
  int val = analogRead(ANALOG_IN);
  Serial.print(0xff);
  Serial.print( (val >> 8) & 0xff);
  Serial.print( val & 0xff);
}


text:
How useful could the Arduino Yun be in computer vision in a robotics project?
I've recently ordered an Arduino Yun and several other components to begin on a small robotics project (based on an old 4x4 RC Truck).  Although not mandatory for what I'd like to do, I was wondering how feasible it would be to mount a small camera or two and write some software for the Linux portion of the Yun to do basic image/video analysis such as face detection and computer vision based path finding?
Mostly this is a question about the processing power capabilities of the Yun.  Has anyone had any luck doing simple image analysis/recognition on this processor?
(Also, if anyone with 150+ rep could edit this to create and add the "computer-vision" tag that would be great)

Probably possible to a degree (64MB should give enough room to store and analyze a few frames even if existing components claim a lot of memory) but likely disappointing in terms of speed and perhaps difficulty of setup as well if off-the-shelf packages are hard to port.  You might want to look at a beaglebone?  You might want to see the various Yun + OpenCV threads on various sites that turn up in a search.

It probably has enough memory and speed to run basic object recognition software, but I there's a better solution, and that's to do your image capture and your object recognition with another device, and use the Arduino to act on the incoming data in some way. That would give you enough juice to do object tracking or searching. I plan to do this for my copter gimbal hopefully to be able to track objects on the ground, like criminals running from the cops for example.
This product will work great for that. Since you need a camera anyway, I think this is a pretty good deal... http://petapixel.com/2013/09/01/pixy-low-cost-camera-recognizes-follows-objects-color/
Can be purchased here: http://www.adafruit.com/products/1906
AdaFruit has tutorials to help you get started.  (Computer-vision doesn't exist as a tag right now and I can't create it, but I tried, sorry)

That's actually really cool. I'll probably look into that after recovering from the cost of my initial component shopping spree.

For this application the Arduino YUN is the worst possible solution because

Low RAM
Terrible Processor
No storage (you can add a microSD card though)
High Cost

The raspberry Pi 2, UDOO, RADXA, Ordio, pretty much anything with a quad core processor and 1GB of RAM will do a decent job.
Face detection is RAM intensive, so you will need to worry about it lagging.
Alternatively you could also have the image processing part be done elsewhere like on a server (on a local network this could be your laptop) or something.
Personally,I would never recommend the Arduino YUN because it just simply isnt worth paying the 75$ for when for about the same price you could have a arduino pro micro and a raspberry pi (with a WiFi adapter, mircoSD card etc.) which is capable of doing probably way more than you actually need to.

Maybe you can consider adding Raspberry Pi board to run OpenCV which is well supported by hundreds of books and tutorials.  See 20 tutorial from initial setting up to running typical functions in http://www.stemapks.com/opencv.html
Also, http://opencv-srf.blogspot.hk/
Then, there are many examples / tutorial / book on linking Arduino to RPi.
On the other hand, from web demo, Pixy CMUcam5 seems very good as a semi-ready-made solution. Watch the demo and see if it does what you want. If yes, then, it is easy solution. OpenCV is a library, it can do many tricks but need learning.
Hope this helps

I am guessing not very useful. Image recognition is quite CPU-intensive, and Arduinos are slow, memory-starved, 8-bit processors.
The Unix side of the Yun runs at 400 MHz, which is quite a bit faster than the Arduino part, but still quite slow compared to a mobile phone or desktop computer. And 64MB of RAM isn't enough to hold even a single HD image, never mind the data you would need to have in RAM to do image analysis. You'd probably have to limit yourself to 640x480, and the slow processor and lack of enough flash for large code libraries would be a problem. (You've only got 16 MB of flash memory on the LINUX processor.) I don't know if you can run programs from an SD card or not. That might solve your code storage problems, but you're still going to struggle with 64 MB of RAM.

What's with the drive by down vote? If you think my answer is wrong or not helpful, explain yourself!


text:
Why is no PWM signal generated using Timer 2?
I managed to work with timer 0 and 1 but am unable to generate a PWM with timer 2 in my atmega328p.
This is the code:
#include <avr/io.h>

int main(void)
{
    /* PD6 output */
    DDRD |= (1 << DDD6);

    /* 50% duty cycle */
    OCR2A = 128;

    /* fast PWM  */
    TCCR2A |= (1 << WGM21) | (1 << WGM20);

    /* prescaler = 8 */
    TCCR2B |= (1 << CS21);

    while (1);

}

Could someone explain what the issue is and why I am not seeing a pwm signal on pin 6 of my arduino uno board?
Thanks

The post is definitely on topic.  I don't understand why it has attracted a vote to be closed.

I am the one who up-voted the question, one of the three up-votes for the answer, and just up-voted your comment :)

It's a shame that multitudes of "leave open" votes don't cancel our erroneous "off-topic" votes. Clearly on-topic. And timers are always such fun! :)

The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs.
Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.
You also have to set COM2A1 in TCCR2A. Otherwise OC2A is disconnected from the output compare unit (ref: Table 17-3 in datasheet).
The effect of COM2A0/1 depends on the configuration in WGM20-WGM22.
The same applies to OC2B respectively.

I tried what you suggested, but that doesn't seem to work: https://paste.ubuntu.com/p/K8KmKnqyvV/
Any suggestions?

I compiled/flashed your code and I found that in TCCR2A you have to set COM2A1 (see my edit).

@traducerad: The comment // enable timer 2 in your code is wrong. It should be // disable timer 2 in order to be consistent with what the following line actually does.


text:
Code causing Servo motor not to work!
My sketch is compiling and loading, but when the program runs, the Servo motor does not work. The buttons work, the LED light works, Piezo buzzer plays the melody, the Stepper motor works but not consistently. The Servo/Stepper motors and LED worked until I introduced the code for the Piezo buzzer to play a melody. I'm new to programming and want to learn from others in a constructive way. I hope this forum is a place where people at all levels of knowledge and experience want to lend a helping hand. Here is my sketch:
#include <Stepper.h>
#include <Servo.h>

/*ARDUINO MOTOR SHIELD
 * The pin breakdown is as follows:
 * Function          Channel A   Channel B
 * Direction         Digital 12  Digital 13
 * Speed (PWM)       Digital 3   Digital 11
 * Brake             Digital 9   Digital 8
 * Current Sensing   Analog 0  Analog 1
 */

const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
const int dirChA = 12;     // assigning name "dirChA" to pin 12
const int dirChB = 13;     // assigning name "dirChB" to pin 13
const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
const int brkChA = 9;      // assigning name "brkChA" to pin 9
const int brkChB = 8;      // assigning name "brkChB" to pin 8

const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

const int pButton1 = 4;    // assigning name "pButton1" to pin 4
const int pButton2 = 5;    // assigning name "pButton2" to pin 5
const int pButton3 = 6;    // assigning name "pButton3" to pin 6
const int pButton4 = 7;    // assigning name "pButton4" to pin 7

const int ledLight = 2;    // assigning name "ledLight" to pin 2

Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
Servo myServo;  // initialize the servo library to logical name myServo

int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
int pButton4State = 0;     // variable for reading the pButton4 state as LOW or HIGH

int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

int myServoPos = 0;      // variable for when servo has reached it's position
int myServoFlag = 0;     // variable for servo when any of the 4 pButton are pressed

int tonePin = A3;        //variable for buzzer

void midi() {
    tone(tonePin, 233, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 412.325976562);
    delay(458.139973958);
    delay(4.82252604167);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 233, 555.555);
    delay(617.283333333);
    delay(77.1604166667);
    tone(tonePin, 233, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 412.325976562);
    delay(458.139973958);
    delay(4.82252604167);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 233, 555.555);
}

void setup() {
// Serial.begin(9600);   // initialize the serial port for messaging & troubleshooting

 // 1 Stepper Motor
 pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
 digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)

 pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
 digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)

 pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
 digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)

 pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
 digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)

 pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
 digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)

 pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
 digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)

 myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM

 // 4 Push Buttons
 pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
 digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)

 pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
 digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)

 pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
 digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)

 pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
 digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)

 // 1 Led Light
 pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
 digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
}

void loop() {
  //Read button state (pressed or not pressed?)
  pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
  pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
  pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
  pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

  // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
  if (pButton1State == HIGH) {
     pButtonFlag=1;  // change pButton1Flag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(40);          // step forward 40 steps to position 1
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        myServoFlag=1;             // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000); // hold position OPEN for 2 sec

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }

        myServoFlag=0;         // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
        midi();

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-40);          // step backward 40 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    // disable power to stepper

        digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
        delay(2000);
     }

  // position 2
  if (pButton2State == HIGH) {
     pButtonFlag=1;  // change pButtonFlag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(80);          // step forward 80 steps to position 2
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
        delay(2000);

        myServoFlag=1;    // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000);

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }
        myServoFlag=0;                // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
        midi();

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-80);          // step backward 80 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
        delay(2000);
    }

    // position 3
    if (pButton3State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(120);          // step forward 120 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;                // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
          midi();

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-120);         // step backward 120 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
     }
    // position 4
    if (pButton4State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(160);          // step forward 160 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate
          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;   // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
          midi();

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-160);         // step backward 160 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
       }
}

As expected, you want to control servo with pin 3,  but it’s been explained in other questions that ‘tone()’ interferes with PWM on pins 3 and 11. Servos are controlled by PWM signals.

I'm using a motor shield. I'm using Pin 10 to signal the Servo. Shouldn't that work? Pin 3 & 11 are being used by the Stepper

Code causing Servo motor not to work!   ..... disconnect the servo from the arduino ... i bet that it still will not be working .... it is not the code causing it not to work

@jsotola it's exactly the code causing it not to work

@RobertoLoGiacco, that is not true .... you do not require any code at all for the motor to be inoperative  ...... the code is not causing the motor to work is the correct statement ...... in other words, the code is not making the motor run

As already reported in the comments, the Tone library uses Timer2 an hardware module of the Atmega328P microcontroller, which is also in charge of generating the PWM signal on pins 3 and 11.
As pins 3 and 11 are both used by your code to pilot the servo motor, it should be of no surprise the motor starts to behave erratically once you added the code to play tones on the buzzer.
A solution would be not to use the PWM pins 3 and 11 as PWM (you can still use those, just not to generate PWM signals)
That is clearly reported in the docs:

 PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match:

Pins 5 and 6 are paired on timer0
Pins 9 and 10 are paired on timer1
Pins 3 and 11 are paired on timer2

And also:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).