text:
Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react
Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.
int button_prev = 0;
int button = 0;

void loop(){

    button_prev = button;

    button = digitalRead(12);

    if (button_prev != button) {

      digitalWrite(act_pin[j], HIGH);

      j = (j+1) % 5;

    }
}

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...
[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]
[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.
But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
Serial.println as well just spits out one character, similiar looking to a d.]
Can anyone point out my mistake to me?
This is the circuit

and this is the old code of the sketch
int act_pin[6] = {A0, A1, A2, A3, A4};

int j = 0;

void setup(){

  Serial.begin(9600);

  for (int k = 0; k < 5; k++) {

     pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

     digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

     pinMode(12, INPUT); //sets pin connected to button as input

}

}

void loop(){

  char button = {digitalRead(12)}; //stores if the button was pressed

  Serial.println(button);

  if(button == HIGH){

    digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

    j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

    button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}

}

Other than the fact that you don't do any debouncing?

Care to explain to me what you mean by debouncing? (And if it could be the cause of the problem.)

http://en.wikipedia.org/wiki/Switch#Contact_bounce

Okey, I edited the question: I don't even press the button before the failure happens. Also: "The effect is usually unimportant in power circuits, but causes problems in some analogue and logic circuits that respond fast enough to misinterpret the on‑off pulses as a data stream." and I am not using an analog input or output(I do use the analog pins, right, but with digitalWrite).

A MCU is a giant logic circuit.

The debouncing that you should be worried about is that your code loops so fast, even pressing the button for an instant activates the "button is pressed" code multiple times. you need to recognize when the button has turned from off to on, not just when it is pressed.

You might want to add a delay, or the leds will turn on, one after another, faster than your eyes can see.

@BrettM I already thought that this could be a problem, but as Gerben said, this would make the lamps turn on very fast. Right now, the lamps do not react at all.

@Gerben See the comment above this one.

change "button" to a boolean and the serial output will start making sense; with more understandable serial output how about putting a large delay in the loop (1s maybe?) and then looking at the output to see if button is reacting correctly.

@BrettM I put a delay of 2 sec at the end of the if. When I output button as a boolean, I get 0 until I press it, when, because of the delay, the output stops, then, I get a 1 and then it goes back to writing 0. So I think the button is reacting correctly.

I think you're looking for the action (in pseudo-code):
ONCE (Button Pressed):
    Light LED j;
    j++

But you have an IF(button) in a Loop{}. Something like:
WHILE (Button Pressed):
    Light LED j;
    j++

So when you press the button j will increment every iteration of Loop {}  (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.
Try printing j instead of button at the line:
Serial.println(j);

and that should highlight the problem.
I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
    ...code
    }

EDIT: Dealing with Contact Bounce
Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.
See Measuring Switch Bounce

You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:
ONCE (Button Pressed):
   WAIT(20ms)              // wait for the bounce to stop
   IF(Button Pressed):     // Ensure the button is still pressed
    ...code...

Try the following Arduino Code:
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
       delay(20);                 // Wait for debounce
       if(digitalRead(12))  {     // Make sure the button is still pressed
        ...code
       }
    }

So, I wrote a piece of code which works so far, as the LEDs do react to the button, but somehow, they always turn on two at a time. See edit.

I found the error. I wrote the piece of code different from yours because I didn't fully understood your if statement when I first read it(hadn't used boolean operators in C yet), but I thought my code does the same as yours, while it does not. It also reacts when I let the button go. You solution is right, thank you!

You say the LEDs also change when you release the button? That's just contact bounce which means the switch bounces on/off for about 10ms after you've pressed it (on or off) due to the mechanical nature of the switch contacts. I'll add a section to my answer on how to deal with that.

No, that wasn't because of the bouncing, but because of a mistake of mine in the if statement. It became true if I pushed button, but as well when I released it but I used your statement and now it works just fine. What, indeed, is caused by debouncing, is that the program sometimes processes two pins at a time instead of just one.

Thanks for the code, I think I'll rather use that one instead of the code from the Arduino site(which is probably basically the same, but it seems far more complicated to me).

Your way of debouncing works, I didn't think it would be that easy to do, thanks! :) (Would mark your answer right a second time, if I could.)

Your code has a serious bug here:
if(button == HIGH){

    digitalWrite(act_pin[j], HIGH);

    j = j+1;

    button = LOW;
}

You increment j without any boundary so it will have the following cycling values:
0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly act_pin[j] will return garbage...
The solution is easy, you must limit j to [0,1,2,3,4], just replace the j = j + 1 line as follows:
j = (j + 1) % 5;

% is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.

Thanks, I did that, this does not solve the problem about the lamps not reacting. (Actually in the whole context of the project it wouldn't make sense to press the button more than five times, so I did not thought about a limit, but still, its much cleaner like this, thank you!)

if(button = HIGH)

Oops.
if (button == HIGH)

And see the Debounce example sketch to learn how to debounce inputs.

Oh...okey. I am a blind man. The random on-off stopped. But now nothing happens when I push the button, could this be because of this debouncing? I am just wondering because I did something similar with a button before(the second project in the starter book), and there was no concern about debouncing whatsoever.

As they say there: "Without debouncing, pressing the button once can appear to the code as multiple presses." but nothing happens when I press the button.

None of the LEDs turn on?

Yes, none. I also tried pushing longer, but I get no reaction.

The braces around the call to digitalRead() are suspect. Remove them.

Changes nothing. I also tried giving button a fixed length of [6](HIGH + \0) but that returns the same result.

authors: Вадим Клементьев


text:
Necessary sampling rate
I'm using an Arduino pro mini to receive the analog signals from three sensors. I was wondering what sampling rate I should sample at in order to properly represent these signals. I know it should be twice the highest analog frequency, but I'm not sure what frequency theses sensors operate in. They're an ECG, a 3 axis accelerometer, and a stretch resistor respectively. To my knowledge, Arduino defaults at a sampling rate of 10kHz, which I believe should be more than enough to quantize the sensor signals. I'm then sending these signals out using bluetooth mate to an android phone. Is there a specific baudrate I should send the data at?
Here is the initialization of my code:
void setup()
{
  Serial.begin(9600);
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
  setTime(0);
}

Thanks so much

What exact sensors are you using?

It's not just the bandwidth of your desired signal; ultimately you also have to consider the bandwidth of your noise and potential spurious signals.  To design a good system, your sampler needs to be able to capture the entire bandwidth of the preceding analog stage (filter an/or amplifier) without undesired aliasing.

Just an addition to the great answers you got: you should run the baud on your bluetooth faster than 9600 if you can. 115200 is pretty good. The reason is that your Arduino can only do one thing at a time. You will be waisting time printing to bluetooth when you could be sampling your next analog voltage. Run it as fast as you can without any errors in the printed / transmitted values

The sampling frequency you are referring to (twice the highest frequency) is for capturing waves, but is not really a concern for the sensors you are using and the types of data they are used to measure.
If you wanted to analyse the magnitude of a 40kHz vibration in a structure, you should worry about sampling rates on your accelerometer; however, if you want to measure the accelerometers current angle to the ground (assuming its not accelerating), you only need to take one sample.
With the ECG, there will be a signal among all the analog voltages you read of a heartbeat (I'm assuming its hooked up to a person). This signal will never get much over 200 beats per minute, or 3.3 Hz. To capture a 3.3Hz signal you need a minimum sampling rate of 6.6Hz, which as still incredibly slow. The same goes for capturing a gait with your accelerometer.
If you capture the analog voltage of your sensors output with analogRead 100 times a second, you should have a very clear and well defined view of the very low frequency signals you are trying to track, and should not have any issues with transferring that much information over serial.
5, 16 bit values can theoretically be sent at 120Hz over 9600 baud, and its very easy to use faster speeds then that if you want more information.

The ECG waveform is nowhere near sinusoidal. I would guess there are frequency components in the tens (possibly hundreds) of hertz range. So a sampling rate of 6.6Hz would be inadequate if the shape of the waveform must be maintained.

As a second to this: you might try running your ECG sensor by itself and sampling as fast as possible. Now begin to add delays so that you drop the sample rate. Take the data into excel and graph it. Find the lowest sample rate where your waves don't look too shitty for your needs. I would guess about 200 hz would be about right. 6.6 will only allow you to recover most basic features of the ECG.  NOTE: sampling slower than required will causing aliasing which is basically higher frequencies appearing as lower ones. This is bad and is impossible to fix without sampling faster

Since I think BrettAM already gave a pretty good answer, I'm going to expound just a little upon that.
First off: I think you're misunderstanding sample rate. The sample rate here is simply the number of analog readings per second that you are doing of a given signal.
If you want to know the maximum sample rate of the Arduino, you simply have to take a ton of samples as fast as you can and see how many you were able to take in a given second. For the Arduino with default settings, that's ~9600 per second maximum. If you just take 1 single sample though, your sample rate is......I don't know.....how often do you do this!? If you take 1 sample and then stop your sketch for an hour, your sample rate for that one sample was 1 sample per hour. Now, what are you sampling? If what your're sampling is changing faster than one noticeable change (ADC resolution step) per hour, then you need to sample faster than once per hour. If your signal (what you're sampling) is changing at 100 times per second (100Hz), however, then you need to sample at at least 200 Hz to even detect it's changing at 100Hz, and at approximately 1000Hz or higher to actually plot what that 100Hz signal looks like. Note: sampling at 2x the rate of the sampled signal is the minimum sample rate required to detect the frequency of the sampled signal, and is called the Nyquist Frequency. Sampling at 10x the sampled signal is the generally-accepted rule-of-thumb for minimum sample rate required to capture the waveform, or shape of the sampled signal.
Now, let's look into data smoothing. If you just take a single sample, it might bounce around. How do you stop this? One method, is to take many samples and average the result. A library I wrote does this, among many other things, so I'll present it here.
Taking many samples in a row then using the average of the samples in any calculations helps to remove the noise component from your signal. I have written an oversampling library that among other things, does just that. An (outdated..will be updated eventually) page on it is here: Using the Arduino Uno’s built-in 10-bit to 21-bit ADC (Analog to Digital Converter).
The current version of the code is V2.1 alpha, and the download link is currently highlighted in yellow at the link above.
In case you need to take faster samples, you can also speed up the ADC sample rate to 50+ kHz, using my library...as opposed to settling on the default 9600Hz of the Arduino.
Play around with sampling and smoothing and stuff.  One technique is to speed up the ADC (so you don't waste too much time sampling), then take the avg. of many samples in order to help remove noise from your sensors. This may be unnecessary, if noise is minimal or changes over time on the signal are slow, but for the sake of learning I'll present this.
Here's an example sketch:
//include the library
#include <eRCaGuy_NewAnalogRead.h>

//Global Vars
byte pin = A0;
byte bitsOfResolution = 10; //commanded oversampled resolution
unsigned long numSamplesToAvg = 50; //number of samples AT THE OVERSAMPLED RESOLUTION that you want to take and average

void setup()
{
  //Configure the adc how you want it
  adc.setADCSpeed(ADC_PRESCALER_16_CLOCK_1MHZ); //this speeds up the ADC clock by a factor of 8
}

void loop()
{
  //local variables
  unsigned long analogReading;

  //take a reading on the analog pin
 analogReading = adc.newAnalogRead(pin,bitsOfResolution,numSamplesToAvg);
}

You'll see that I am speeding up the ADC and taking and averaging 50 samples to smooth the data. I have yet to test the speed, but I estimate this could prob. run at 500Hz or so max sample rate (returning an average value each time)...assuming that's all you did.
Doing this and taking a single sample is fine for what you need I believe.
Now, for baud rate. Baud rate is essentially "bits of data sent per second." It's how fast your communication signal is. Lower baud rates are generally less susceptible to electrical noise, and the data is less likely to get corrupted, but higher baud rates send the data values much more quickly and waste less of your code time sitting around transferring data. I recommend you speed it up to maximum, unless you have data transfer problems or dropouts, in which case you should slow it down a bit.
NOTE: for more detailed examples on the library download it and look in the examples folder.

source: Stack Exchange

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

sort: votes


text:
Breadboard-to-Arduino wiring with flat flex cable assemblies?
I want to wire Arduino Due connectors to a breadboard 8-at-a-time, so they're easier to remove and more reliable.
I tried these Flat Flex Cable Assemblies (FFC assemblies) terminated with "solder lugs" from Digi-Key, but the pins are just a little too short to penetrate the Arduino connectors well.  Similarly they barely reach into to the breadboard contacts, so they tend to fall out.  Anyone find a workable product for this?

This solution is good but requires a lot of manual soldering.  Looking for prepackaged.

For now, you could solder some male headers to those flatflex cables, making them easier to work with.

When I had to breadboard 8-bit computer projects, I'd wire all the busses with 4 colors of discrete hookup wire used in spectral order.  That way if anything came out it was easy to tell where it should be reconnected.  (I also tied the bundles down with little jumpers in the supply rows or unused rows, but that wouldn't apply here).

http://www.youtube.com/watch?v=GkbOJSvhCgU looks like being a possible solution.

You may be onto something, @yeti.  Male-to-male pre-crimped wires for 0.1" spacing connectors.  http://www.pololu.com/product/1808

Search for male-male jumper wire. Some of what you'll find is individual wires but there are also many that are connected together and you can rip off the width you need.
Here's one from Adafruit but there is no shortage of them on ebay/amazon.

Thanks, Sachleen!  Are any of them spaced at fixed 0.100" centers?  I am actually now using breadboard jumper wire and it works fine, but I was hoping for quicker interchange, something that didn't require error-prone unplugging and plugging dozens of individual wires.

Not that I know of. I've seen some that are groups of four wires but they aren't specifically designed as breadbaord jumper wires but for a specific product.

Bought a handful from China to try out.

Again similar to Sachleen's answer. You can crimp your own connectors onto a ribbon cable, that way you can have the desired header size.
I've just done this manually with some pliers (I couldn't afford the crimping tool) a bit tricky but I'm pleased with the results. I got all of the bits I needed from www.hobbytronics.co.uk. Anywho I'm happy with the results now after a few failed attempts.

Very close, Nick J Adams.  Thanks to a tip from @yeti I just bought some pre-crimped wires from Pololu and some 0.1" headers to try out.  It looks as if you are using headers here that space the contacts 0.1" apart?

Yes that's right, so would work on a breadboard, perf board and of course Adafruit's combination of both as shown in the photo.

Although Sachleen's answer is preferable in a lot of situations, there are a few other options that you have.
Quick note on his answer: I find clamping a row of those wires together and rubbing a thin line of superglue over the connectors a useful way to keep them together. It's not very neat, but it works pretty well and, with that many wires connected, can make it more stable than before.
There are two main alternatives I see:

Ribbon cable: very similar to the wires pointed out in Sachleen's answer, only the connectors come already as one piece.

Source: http://www.adafruit.com/blog/wp-content/uploads/2012/06/window-207.jpg

They are typically two rows, but I've seen them before with one (although pretty rare). You could just ignore one row of those and use some male headers to connect the same side of the ribbon cable to the breadboard/Due.
DIY: although you said that you didn't like soldering, it's still the best solution here IMHO. You'll need soldering later on, and breadboards aren't reliable beyond just simple development, so you'll need to learn at one point or another. This is a great entry project because it's pretty hard to mess a simple thing like this up, unless you accidentally bridge two joints. However, you won't damage an expensive chip if you mess up (which you will on the first few times you solder), you can just clean the joints and start over.
Anyway, just grab some perf board and some wire (twisted pair (similar to CAT5e)/ribbon cable with or without an adapter and plug/loose wires, and a few rows of male headers. The type of wire you choose doesn't really matter, just don't get something too thick or too thin. Anyway, solder some headers to the perf board and then you can solder the wires/the socket (if you choose a ribbon cable with ends) together. You can then cut the perf board to size (you can do this step before soldering) and you're done!

Close, mister penguin.  Good suggestion with the inserted headers.  DigiKey has plug-to-plug ribbon cable assemblies for $8 each.

And now I understand what you mean about the superglue-variant on @sachleen 's answer.  Do they end up 0.1" apart when you do that?

@BobStein For the ribbon cable, that's definitely a cleaner and easier variant, but it does cost a little more (especially costing experience with soldering). As far as the superglue, yes, mine did fit perfectly with some 0.1" headers. I didn't try with a breadboard, but the headers are the same spacing as a standard 2.54mm breadboard.

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


text:
Arduino Stepper Motor Standing Desk help!
I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.
I would love some help determining what I would need for this task.
What kind of motor should I use?
  -Stepper motor?
  -High/low rpm?
  -High/low torque?
What sort of power would I need?
Looking forward to hearing people's suggestions!

For playing,  battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. These typically have a  two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction.

I think this might end up being more of a fun way to electrocute yourself, but let's find out...
Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface...  E = mgh = m(9.8)h
So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules
How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.
Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.
So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...
http://www.electricscooterparts.com/motors24volt.html - bang! Scooter motors! Nice!
So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of those people). I simplified a lot, but you get the idea.
The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.
Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.
You're going to need a good power supply for that motor - a 24-volt 200-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.
This should get you started on finding those parts...
https://www.sparkfun.com/categories/145 - these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.
Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.
What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.

For initial playing,  and possibly for a final solution, battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. Drills are often discarded when the batteries die and may be available free or at lo cost.
For relatively low duty cycle use 9V drills operate OK on a small 12V battery and drills rated at up to 18V usually operate well enough on 12V.
Use of a 12V lead acid battery charged by a trickle charger makes high current peaks easy to accommodate. Almot any condition battery will do - one which is too dead for eg motorcyle use probably works well enough here. Floating 12V lead acid batteries at 13.7 V allows them to be permanenetly connected to the "charger".  A power pack can be used without a battery if enough current is provided.
Battery powered drills typically have a  two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction.
Dismantling the gearbox can be educational but may be a one way journey. Beware a flood of ball bearings.

That's a great idea, those have plenty of torque!


text:
Arduino uno AVR assembly with LEDs
I am currently in an introductory assembly language class.
My assignment is to use a sparkfun joystick shield kit to do something with an arduino uno. I figure turning on LEDs is the easiest. We must program it in AVR assembly(note: we have only used nasm assembly all semester).
I don't really know how this needs to be done, but I would like the lights to turn on when a button is pressed (one LED per button). I also want to use the analog pins to have the joystick LEDs fade in and out.
below is the code I have right now, and don't have the equipment to test it.
Am I on the right track, or is it a horrible mess?
The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values.
Thanks in advance.
.include "/usr/local/include/atmega32u4.def"

        .global  main

        .section .text

main:

        cbi     PortD, 2            ; joystick button
        cbi     PortD, 3            ; right button
        cbi     PortD, 4            ; up button
        cbi     PortD, 5            ; down button
        cbi     PortD, 6            ; left button

        cbi     PortC, 0            ; joystick vertical output
        cbi     PortC, 1            ; joystick horizontal output

        ldi     r16, 0x7c           ; select pins 2-6 for button input mask
        in      ddrd, r16           ; set digital button pins as input
        ldi     r17, 0x03           ; select pins 0 & 1 for joystick input
        in      ddrc, r17           ; set analog joystick pins as input

        ldi     r18, 0x1f           ; select pins 8-12 for button LED output
        out     ddrb, r18           ; set digital button LED pins as output
        ldi     r18, 0x0c           ; select pins 2 & 3 for joystick LED ouput
        out     ddrc, r18           ; set analog joystick LED pins as output

loop:

        ldi     r20, PortD          ; read in from digital pins 0-7
        and     r20, r16            ; apply button input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortB, r20          ; turn on LEDs of pushed buttons

        ldi     r20, PortC          ; read in from analog pins
        and     r20, r17            ; apply joystick input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortC, r20          ; turn on LEDs of joystick movement
        rjmp    loop

"The professor was referring to the arduino pins with hex..." I'm not sure that I understand what this means...

PORTD and PORTC are the input registers. There is no point in clearing (cbi) them. Do you have external pull-up/pull-down resistors? As for the joystick; your just reading the digital value (0/1), not the analog (0..1023). You also need to use PWM to output different brightnesses. For readability I'd probably use sbi ddrb, ddb0; set PB0 to output. That way you don't have to use unreadable hex values. It also makes changing pin assignments a lot easier. It also saves a register. Though I now see your using it as a mask to set all leds at once (nice trick).

The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values - Well let's say you need to affect pin 10, in hex that would be 0A.

mov     r20, r20 >> 2       ; shift left twice  - looks like shift right twice to me, but whatever.

.include "/usr/local/include/atmega32u4.def" - the Uno uses the Atmega328P processor, so this is not the right file to include.

Did you know that the Arduino Uno uses the Atmel ATmega328P processor?
using the ADC for analog input in assembly language
You may want to skim through Chapter "24. Analog-to-Digital Converter" of the ATmega328P datasheet.
You may want to read application note "AVR126: ADC of megaAVR in Single Ended Mode" and browse through the corresponding AVR126 example software.
(It's in the C language, but it mentions all the registers you'll need to read the ADC in your assembly language program).
(As you can tell from the ATmega328 datasheet, the ATmega88 has exactly the same ADC as the ATmega328).
"Assembler source code for the conversion of an analogue voltage to an 8-bit-number",
"AVR ASM Introduction: A moron's guide to ADC"
and
"ATmega8 ADC Example"
have a pure assembly language program for reading the ADC on a Atmel AVR chip
-- alas, on a slightly different chip that may have slightly different registers than the ATmega328P.
Good luck!

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


text:
Supply arduino through Vin pin with a battery

is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?
is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?
in case i don't connect GND arduino pin with -12v , does arduino works?
in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?

You seem to be confusing ground and negative voltages an awful lot...

if a want to supply arduino with a battery which should be the connections?

there is no -12v in a battery, it is GND. So all -5v and -12v you have there are GND. Unless it is an ACTUAL negative voltage derived from the same power source, then it is irrelevant

Change your diagram's three '-5v' and one '-12v' to GND and the "+voltage" to be  "+5V".

Voltages, being a potential difference are always measured relative to another voltage.  Normally that reference voltage is referred to as ground, though may not always be.
The + and - on the battery refers to the polarity of the battery not the polarity of the voltage.
For instance, relative to the - terminal the positive terminal is 12 volts higher, or +12V.  Relative to the + terminal the negative terminal is 12V lower, so -12V.
When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V.  So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V with respect to ground.  The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V with respect to ground.
If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V lower than ground, so would be -12V with respect to ground.  The + terminal would be 0V with respect to ground.


text:
It seems as if there is a 220K pull-down resistor on analog pin 0
So I am building a project that uses the analog pins for precise measurements of resistance through a voltage divider and I have been having some seemingly unsolvable problems with nonlinear response to linearly changing resistances when using the A0 pin to measure.
I first realized this was the problem when I had a voltage divider consisting of a 76.8K and 100K 1% resistors with Vout connected to A0, and I was consistently getting wrong values. I measured the output voltage of the voltage divider and got 1.7V, instead of the ~2.7 volts I should be getting with my supply. When I disconnected the wire to A0, the voltage rose to the expected level.
I disconnected power and measured resistance between the analog pins of the Atmega328 I was using and ground and found that A0 had 220K of resistance, while all other pins measured as infinite. When using the other pins, the voltage divider returned the expected values and was able to measure a wide range of resistors with values just as accurate as my multimeter. I know I have changed a lot of low-level things with code (analog reference, the comparator, ADC clock prescalers, using analog pins as outputs, etc.) but I don't think any of this could persist while the chip is not powered on. Does doing any of these things connect a resistor in the way I was describing, and is there anything that could cause this to stay "stuck" this way?

The datasheet says: The ADC is optimized for analog signals with an output impedance of approximately 10 kΩ or less - your voltage divider of 76k and 100k does not appear to satisfy those requirements.

Try adding a small capacitor between the voltage you try to measure and ground.

@NickGammon The voltage divider's impedance does not seem to be an issue, as it works perfectly on pins A1-A5 with a wide range of resistor values as the one being measured. The question is asking why there is the internal 220K resistance to ground that is causing it to work incorrectly on analog pin 0.

This is a raw chip is it? Not on some board? Try another chip, maybe this one is faulty.

Yes, it is a raw chip. I will try another one soon.

They don't connect a resistor as such, but analog input pins do have an impedance which can affect your readings.
If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results.  This is normal.  The input impedance is somewhere in the region of 1MΩ - 10MΩ.
You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.
If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.
Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.

This does not answer the question. I am not experiencing skewing of the results as you said when I use any pins except A0. In fact, when using the other pins I can read a resistor and match the value my multimeter gives me. The question is asking why my Atmega has 220K of internal resistance between A0 and GND, but not any other analog pin.

It may be a faulty chip. I have never experienced differences between the different analog pins.  Nevertheless, you should watch that impedance and keep it within the specifications of the input pin.

It's also worth noting that the primary load impedance of an ADC is not something you can measure with the power off.  In fact on some chips (though perhaps not the ATmega) it actually changes depending on the ADC clock rate, and can become a rather heavy load at the higher ones.  What resistance an ohm-meter will see on a pin of an unpowered MCU depends in part if the test voltage is high enough to bias the protection diode into a measurable degree of conductance, and also on the test polarity.


text:
How to use the analog comparator to determine when an analog pin has reached a certain voltage?
I am trying to find some information on how to use the analog comparator on an Atmega328 to detect when an analog pin has reached a certain voltage (3.16 volts).
I cannot find any example code that says how to do this, although I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin. I do not understand how this would work as the PWM pins do not output an analog voltage, but a pulse width modulated square wave. Is it possible to use the comparator to compare with a certain voltage this way?
I have tried polling with analogRead(), but it is too slow for my application.

I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin - do you really need to vary the reference voltage, or is 3.16V what you want? The analog output pins do not output analog voltages (they are not DAC), they are PWM output.

Alternatively, you could check the ADC voltage every now and then, to see if it's above 3.16V

@Paul: I tried that, but it is too slow for my needs.

@jBot-42 it can be usefull to state timing requirements in your questions, or the things you've tried yourself (:

This works fine to enable comparator mode, but I can't seem to restore normal ADC operation after using comparator mode. Joe

I have a page about the analog comparator that has code:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

This is for a fixed reference voltage, for example:

I might be missing something, but in this diagram won't the voltage on AIN1 always be lower than that on AIN0 ?

Er, yes, my example resistances were not well chosen. Probably AIN1 should have a voltage divider more in the middle range (eg. 4.7k and 4.7k making AIN1 = 2.5V which the LDR would be above in one situation, and below in another.

You need a low-pass filter between the PWM output and the comparator input. This will allow you to produce an analog voltage from the PWM output, which can the be used as a reference voltage for the comparator.
Typically, a simple RC LPF is sufficient. Choose a large time constant relative to your PWM frequency (the Arduino defaults to 490Hz) so that you don't have ripple in your reference voltage.


text:
GPS - Speed doesn't update as should - EM408 & Arduino Mega & GSM
I'm developing a system that will get the GPS signal and send it though the GSM with information about position, speed and temperature from some digital sensors.
Currently I'm using the GPS EM408, the Arduino mega plus the GSM board (official one).
The problem is that the GPS (by the library TinyGPSPlus) gives me the same speed for long time or sometimes give me 0km/h.
The sketch works like this:
loop()
{
   getGPSData() - ~ 1 sec to execute and take one data from the GPS.
   getSensors() - ~ 1 sec to execute and take one data from the digital sensors.
   sendData() - ~ 6 n 10 secs to send the data through the internet.
}

The whole process takes around 10 ~ 15 secs to be completed.
If I remove the sendData() and the system starts getting the GPS information each second the speed value works perfectly but if I get the data from the GPS each 12 secs (because of the GSM delay) the speed doesn't work as expected.
I understand that the problem is because the library TinyGPSPlus calculate the speed between two points and the getGPSData() only takes one information each loop and the next point has 15 secs of difference.
Although I've added a "for(i=0;i<=4;i++)" to the getGPSData() enforcing it to get at least 4 times of position before the GSM send it over the internet, now is working better but still getting the wrong value or sometimes it freezes to the same speedy for long time.
I've tried to add a second board and put both to communicate with I2C turning it "dual core", where one board will be getting the data from the GPS each second and another one will send though the data each 15 secs, but the GSM freezes sometimes when the I2C is connected :(.
Does anyone has any clue how to do it?

You will likely have to show more of your code. In your for loop, did you add a little delay after getting gps data? That may help.

Thanks @sachleen
I've checked the serial communication between the GPS and the Arduino, therewith I've detected that the problem was because there is a gap in the middle of the communication. My code has a WHILE() to keep taking information from the serial while data is coming from the serial, but sometimes the connection between both has a small stop (the gap) and it was closing the WHILE(). I added another WHILE() to keep checking the serial for at least 2 seconds and it solved the problem. Thank you


text:
Bluetooth serial readings on 0.96'' Adafruit OLED
I am trying to display the readings of LDR connected to slave arduino through serial monitor of master arduino paired with bluetooth. I got the readings and it is working fine.
But when I connected OLED to the master arduino so that the LDR readings can be displayed on OLED as well as serial monitor, it is not displaying as expected.
So for simplicity I tried sending the word "hello" from slave to master. The code for slave is :
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  BTSerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  BTSerial.println("hello");
  Serial.println("hello");
  delay(1000);

}

Then I tried displaying the same only on serial monitor of master. The code:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
char state ;

void setup() {
 pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
 digitalWrite(9, HIGH);
 BTSerial.begin(9600);
 Serial.begin(9600);
 Serial.println("<Arduino is ready>");
}

void loop() {
 if (BTSerial.available()) {
   state = BTSerial.read();
   Serial.write(state);
 }
}

It is showing valid readings in serial monitor with hello being printed after every one second
<Arduino is ready>
hello
hello
hello
hello

But when I modified the code so that I can get the readings on OLED as well as serial monitor;
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
char sensor;
void setup()
{
  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);// initialize with the I2C addr 0x3C (for the 128x32)(initializing the display)
  Serial.begin(9600);
  BTSerial.begin(9600);
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
}

void displayreading()
{
   if (BTSerial.available()) //checks for incoming data
    {

      sensor = BTSerial.read();//reads data from bluetooth serial
      display.clearDisplay();
      display.setTextColor(WHITE);
      display.setCursor(30,0);
      display.setTextSize(1);
      display.print("LDR Reading:");
      display.setCursor(30,10);
      display.setTextSize(2);
      display.print(sensor);
      Serial.write(sensor);
    }
}

void loop()
{
    displayreading();
    display.display();
}

The OLED is showing one letter at a time clearing the screen after every letter rapidly (since I did not add delay which will add up to the problem of data lag). Like :
h , (clear screen)
e (clear screen)
l (clear screen)
l (clear screen)
0 (clear screen)
The serial monitor is showing the readings as:
<Arduino is ready>
hello
hello
hello
hello

But the word hello is printed letter after letter and not in a whole like in the previous master code.There is one second gap after every printing of "hello".
Can somebody please help me with this problem?
Thanks in advance

BTSerial.read() reads a single byte.

and serial write seems working ok, because there you don't move cursor

Instead of BTSerial.read(); there should be
String content = "";
char character;

while(BTSerial.available()) {
     character = BTSerial.read();
     content.concat(character);
 }

and then you send content to lcd by putting
display.write(content);


text:
Multiple connections on the same pin
I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?
Arduino <> TGAM
Arduino RX (0) <> TGAM T (TX)
Arduino TX (1) <> TGAM R (RX)
Arduino 3.3V <> TGAM + (VCC)
Arduino GND <> TGAM - (GND)
Arduino <> HC-06
3.3v    <> VCC
GND     <> GND
TXD     <> RXD
RXD     <> TXD

if the tgam only uses RX and the BT only TX, that can work;

No, you cannot use one pin (or set of pins) for two functions like that.
To communicate with two serial devices you will need two serial ports. It's possible to (just about) emulate one in software using the SoftwareSerial library. It's not wonderful though - personally I would use a chip that has multiple UARTs in it.

Thank you for the answer. But what about the GND and 3.3v pins. Can I emulate those too?

No. They aren't IO pins, they are just voltage levels. Wire as many things to those as you like. The fact you are having to ask these questions shows you lack the fundamental knowledge to be working with electronics. You are trying to  run before you have even been born.

Would agree and would appreciate if you share with me a nice source for learning the fundamentals. And remember everyone has to go through the stage of being born.

For those who might need it in the future: https://www.arduino.cc/en/Tutorial/TwoPortReceive

http://www.explainthatstuff.com/electricity.html


text:
Help with wiring? Fritzing example inside
I am trying to prep my wiring for a 8x8 Led Matrix w/ Bluetooth according to the following instructable:
http://www.instructables.com/id/Arduino-SPI-7-Bi-color-LED-Matrix-Scrolling-Text-D/?ALLSTEPS
Instead of soldering everything together I'd much rather use a breadboard. I'm new to wiring, breadboards, and Arduino's in general. I was wondering if anyone could look over my sketch and see that the connections I've made are valid.
I'm basing my wiring off this image (See original instructable for higher resolution):

I realize the bluetooth module isn't the same. I'm just using this as a reference. The wires leading off the top of the board will be going to the LED Driver module.
EDIT: Thanks for the feedback guys. I have decided to go with the Innogear HC-05 module. I've adjusted the wiring according to that model.
As per the suggestions, I've switched my power and ground rail and eliminated the resistors and ground for TX communication. (I've still kept a ground for the BT).
Here's my new attempt:

I realize that it's not your fault, but a voltage divider is a terrible level shifter. Also, are you sure you're using a 3.3V Bluetooth module?

Sorry, I'm not sure what a voltage divider is. As I said I'm very new to all this. As for the BT module I plan on using the HC-05, just showing the RN-42 for reference (Power should be coming off the 5V rail). I'm open to any suggestions, and I'm certain this isn't laid out as efficiently as it should be.

Which specific Bluetooth module are you using? The one in the top image is not a bare HC-05.

Planning to pick this one up soon. http://www.amazon.com/Arduino-Wireless-Bluetooth-Transceiver-Module/dp/B0093XAV4U/ref=sr_1_2?ie=UTF8&qid=1406274658&sr=8-2&keywords=hc-05+bluetooth

Looks the same as the original so it's good. Except pin53 should have had a green wire instead of a white. Good luck.

@IgnacioVazquez-Abrams Version 1.05 has the 3.3v logic level printed on the back.

Does the wiring color matter? I believe all are the same gauge but I am unsure. I'm borrowing this kit from someone.

I am the author for the Instructable ethanx94's wiring is based on. It seems like the active and helpful members here have already helped iron things out.
If anyone is using the Arduino sketch downloaded from my instructable but is using ethanx94's wiring, do remember to change the SPI SS (Slave Select) pin in the sketch from 10 to 53 to reflect the correct pin used.
Look for the following line in the sketch and change the pin number 10 to 53:
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX7219

int SPI_CS = 53;// This SPI Chip Select pin controls the MAX7219

Welcome to Arduino SE! It's cool that the author of the tutorial is commenting on a question as that doesn't happen much. Feel free to stick around and ask/answer other questions... One note is what about pins 11-13/50-52? Do those need to be remapped in the code, too? (Arduino documentation: http://arduino.cc/en/Reference/SPI)

Sorry for late reply. I am not active here. There is no need to remap the other pins in the sketch downloaded from my instructable except the SPI SS pin.

Those are, in fact, the same board. When you look at this image (from Amazon)...

...you can see that there are really six pins, just two of them aren't soldered.

Your circuit:

On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. This module (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power and the TX/RX.

I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

tl;dr: it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about that specific part but there was another one that a reviewer specified that this was okay.
Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.

Thanks so much for the feedback. I've updated the OP accordingly, as well as cleaned up the overall shape of things.


text:
Transmit image file thougth the TX TR serial line
I have a digital camera with a USB port for image dowload from the camera SD card.
I will like to be able to capture this image files store in the camera SD card using the Arduino  TX TR lines (serial) then transmit this image file to the computer from the USB connection from Arduino to Computer.
The reason need this scenario responds to that the camera dissables the shutter when sensing a USB cable conneted to computer. I do not knwo why this happens but I suspect is an underdeveloped feature of the camera.
Basically, I will like to use Arduino as a USB hub for external devices but at the same time to power down the line when no longer need the device using the Arduino TX and TX line . This will give tha camera a sense that the camera is been unplugged.

simulate this circuit – Schematic created using CircuitLab

You cannot. The TX and RX lines are UART. UART is not USB. USB is a very complicated protocol, and you need a proper understanding of how it works. It's not a simple serial protocol like UART.
Add to that the fact that the Arduino can in no way handle the amount of data involved in video, and you're already on a non-starter.

Having this said, can you suggest a way to use Arduino to cut off the V data line transmition from the computer to the camera?  I need to fake the same as unplugging the USB.

What is the "V" transmission line? USB has D+ and D-, and they are both required all the time for communication.

@JoseEnriqueCalderon The closest you could possibly get would be to have the Arduino control a relay which disconnects both the D+ and D- lines from your computer, performing the same task as physically unplugging the camera. That means no communication in either direction.

If you want to read data from USB so connect an Arduino to an USB port, you must use an Arduino Leonardo. Arduinos don't have a "full USB", except the Leonardo.

@peter  , Please, I will like you to post this as an answear and in any way  elaborate a simple sketch or diagram. Thanks

@Majenko.... Thanks for the correction, I have found some places that uses this for voltage line and overlook that this is a data line.

The Leonardo's USB is device mode only. It can talk to a PC. It has no relevence to communicating with another USB device.

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


text:
How to measure total energy usage of an arduino board
I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.
Question:
How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?
Thanks a lot.
To clear up some things
No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.
Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.
I would like to know the entire energy consumed, not just the pump.

You want to know the current used by the board, not the volts. The volts will be constant. The current will change as the motor turns on/off.

Or more accurately, you want the energy (in Wh, Watt-hour) consumed since 00:00. To calculate the energy, you need the voltage, which is a constant, and the trend of current (in A or mA, Ampère) over time.

Ok i'll try that

You mentioned a pump: is it directly sourced by an Arduino pin (I hope not). What are the specs for the pump? I guess most energy consumed will come from there, hene you may possibly consider eneegy for Arduino itself negligible.

@jfpoilpret Using solar and wind power, chances are that neither voltage nor current is constant. Otherwise your method is correct. Energy[Wh] = V[V] × I[A] × t[s] / 3600[s/h]

@jippie Yeah but I guess there must be some accumulator in the circuit, that will provide an almost constant voltage. A global vision of the circuit would be useful.

@DLJ is it really the energy consumed by the sole Arduino board you want to know (as suggested by your question)? Or are you interested in the energy consumed by all your system, pump included (which seems more relevant to me)? Can you also confirm that the pump uses the same source as the Arduino, i.e. solar panel and wind turbine (I guess so)?

Basically you have 2 options to compute the consumed energy. First is experimenting and meaasuring currents with a DMM during various operations phases, then integrating this into your Arduino program as you must know how long your pump is on. Second way is to measure current in real-time with a current sensor and perform calculations based on that.

In order to calculate the amount of energy you have to calculate the power first.
The relation is
Energy = (Power * Time of usage)
How to calculate the power?
The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project.
The main thing you have here is the pump and how much does it consume current.
Usually, you will have on the "plate" of the pump the current withdrawal of it.
Say it consumes 2 Amps.
If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.
If there are any other major/important components in your project just calculate the current withdrawal from them.
Now add up all the currents and say you ended up with 2 Amps.
If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage.
WHY?
Because:
P(power) = V(voltage)   * I(current)
If not, just find the power of each component.
Add up all the powers of all you components.
Now you will only have to calculate the energy.
E(Energy) = Power * time
Time here refers to how long is your system working?
Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).
Say your power ended up with 3kW kilo Watt
You've run the system for 2 hours every day
Energy = 3 * 2 = 6 kWh
If you've kept this for a full month.
Energy save in a month = 180kWh.
Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!

I think this formula can't apply asi-is in this case as current consumption will vary dramatically when the pump is on (and that's not always fortunately).

He can find out the starter current ( In rush current) and see how much percentage increase sis that from normal operation. He then can add this percent -just in case- to compensqte for this error. Of course he has to see on avg how many times is he pump turned on. I think that will not make a big difference because the duration of starter current is really small.

I think this can help me a lot. I'll try it and then say what happens. Thanks!

There are some chip that measure current flow (like ACS714). Just be sure to buy a chip that will not fry under your load, and mount it in serie with the pump. That chip will bring an analog (but there a re "smarter" chip witch use i2c or spi) signal to arduino, using the formula on the datasheet you can find out real (well, as always there are small error) current flow.
You should already know the voltage of the pump, but you can easily read it with a similar chip or even a voltage divider, just pay attention if you are using PWM as if it will fake your reading)
Now, as already pointed out by Adel Bibi, you can multiply the voltage of the pump with the current value readed (find power), multiply with the time elapsed from the last measure and sum up with precedent measure (integral of the power by time)
you can do the same on the wind/solar panel, just invert the sign of the current (as you are Producing and not Consuming power) and voilà!

With the accumulator in the system, current draw will increase as that is topped off. The accumulator provides sufficient pressure to drive the system. As system pressure draws down, the pump turns on to bring up the accumulator, with maximum draw nearing cut-off pressure. Taking the total run time of the pump in question (@DLJ) you may chop this up into discrete chunks and measure the draw over those periods, plot that out. I like that greenwall, and I want one. -- Aloha nui loa, MKK
edit -- As an aside, even a 12V pump driving the smallest 1 liter accumulator to 250 kPa, will draw up to 3A for a few moments, given the size of your system. What motor shield are you using?


text:
Read RFID Card Number in Processing over Serial
I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.
Its program for Arduino is below:
int count = 0; // count = 0

char input[12];                                         // character array of size 12

boolean flag = 0;                                       // flag =0

void setup()
{
   Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
}

void loop()
{
   if(Serial.available())

{

count = 0;

while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

{
input[count] = Serial.read();
count++;
delay(5);
}

//Serial.print("Card ID - ");

Serial.print(input);      // Print RFID tag number

}

}

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match.
Hence the mouse doesn't get unlocked.
The program for processing is as below:
import processing.serial.*;
import java.awt.AWTException;
import java.awt.Robot;

Robot robot;
boolean locked = false;
Serial port;
void setup()
{
  println(Serial.list()); //Prints available ports

  port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
  try
  {
    robot = new Robot(); //Creates robot
  }
  catch (AWTException e)
  {
    e.printStackTrace();
  }
}

void draw()
{
  if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
  while (port.available() > 0)
  {
    String input = port.readString();
    //println(input);
    if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
  }
}

void keyPressed ()
{
  if (key == 'l')
  {
    locked = true; //Locks it
  }

  if (key == 'u')
  {
    locked = false; //Unlocks it
  }

  if (key == ESC)
  {
    key = 0; //Disables escape as quit
  }
}

Please point the incorrect syntax and suggest correct one.

input has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before Serial.print(input), you write input[12] = 0. Also the argument to string.equals() should be a String as well; you must write the statement like this: input.equals(String("11006F26DC84"));


text:
Can I get the hex file from an Arduino without the .ino code
I have a CNC router table that came into my local makerspace. The board looks like it has some standard parts, but also has some parts I don't recognize. At the heart of it is an Arduino Uno. I would like to get the code from the UNO, as a back up. I will have to do testing on this board, but I don't want to overwrite something I don't have a back up of.
is there a way to get the firmware off of the arduino, without having the ino files that generated it?
(This is a standard function on many other platforms such as PIC, I just don't know how to do it in Arudino. I am assuming the functionality also exists.)

cool story bro, show me.

the hex file is the code. your MCU runs. if I had the hex file, I wouldnt need the source code, I could upload it to the MCU. I can do that with avrdude, or whatever, Im sure arduno code can do it too.

here is some talk about it https://electronics.stackexchange.com/questions/61079/is-it-possible-to-extract-code-from-an-arduino-board

lol nice. Here is some talk about it, no solution, and a link to a 404d page. I think I almost have it figured out one my own, though. ... I think I can get avrdude to do it.

yes, avrdude is the program ... there should be command line help that may include an example

Cool I got it using avrdude.
$ avrdude -c arduino -P /dev/ttyUSB0 -b 9600 -p m328p -U  flash:r:CNCArdunio.hex:i
> -c the platform (basically)
> -P the port where your harware is.
> -b the baudrate.
> -p the chip architecture.
> -U momory type flash  :r option to read to file  :i option to format into Intel HEX.

caveats.Upon closer inspection this is either a very early model UNO, or a cheap clone. It comes up at /dev/ttyUSB0, and required that I press the reset button shortly before sending the avrdude command, else it resulted in
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I just thought of another way to do it, using an ardunio as an ISP, (in circiut programmer? wut?) but Im not sure it would work right using this board, and my other authentic Ardunio boards. and it wouldnt give you a file, you would simply make a clone.

You might also need to read the mcu's eeprom using the same command, but with eeprom:r:eeprom.eep:i (I believe).


text:
Why are some letters reserved?
I wrote a function that takes characters and noticed that the Arduino Compiler treated some characters like system-reserved, and other like functions, and a few just like characters. Lowercase doesn't seem to be effected.
I'm just wondering why.

What is your code supposed to mean?

Are you referring to the different colors of the letters? The syntax highlighter is made to highlight correct C code. Giving it invalid code will produce invalid highlighting. I wouldn't try to read too much into it.

Oh ok. I may have read into it too much

@EdgarBonet its a segment,  you give it forward(a||b) and motor a or b moves forward, or reverse, or brakes, or halts all, etc. It also was working(need more testing) I was just curious about the syntax highlighting which I noticed while I was writing it.

Please copy and paste your code, not a picture of it.  For help see Markdown help. You can format code by selecting the code and pressing Ctrl+K to have your browser do this for you.

The Arduino IDE does keyword coloration according to a very crude system. It simply scans for all the keywords.txt files included with:

Arduino IDE
Libraries bundled with the Arduino IDE
Libraries you have installed to the libraries subfolder of your sketchbook
Libraries bundled with the hardware package of the currently selected board - Hardware package of the currently selected board (recent IDE versions only)

There are several types of keyword identifiers that determine which color is used. The reason those letters are colored in your IDE is because some library you have installed just happens to have added them to its keywords.txt file.
The Arduino IDE makes no attempt to determine whether you have included those libraries and so coloration doesn't necessarily mean they are "reserved". If you have not included the library that defines a specific keyword then the coloration of that keyword is meaningless.
For more information on keywords.txt see:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords

In WString.h is a define:
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

In other words, the letter F is already a macro.
I don't know what your code:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

is supposed to do. I suppose you are just testing the syntax highlighting?
The syntax highlighting is designed to try to "help" you by colouring words in a pre-supplied file in a different way. It doesn't in any way affect how the compilation works. And, judging by what you posted, it can't always be relied upon. Personally, I ignore it.

I was just showing the letters that do syntax highlighting.


text:
Arduino Micro blue light dimms and turns off when I plug in my circuit
I have a PING Ultrasonic Sensor, Adafruit Absolute Orientation Sensor, and a Continuous rotation servo. All pins are connected to an Arduino Micro. However because the micro only has one 5V output, I used a rail from a breadboard. I connected the + & - leads from all the devices to the rail and then plugged in two leads connecting 5V and GND from the Micro to the rail. My goal was two send power from the Arduino Micro down the rail to all three devices.
I plugged in the Micro, and instead of seeing green lights on the sensor (powered on), the blue light on the Micro turned off and the servo twitched. I have no idea why. Do I need external power for the 5V?

Sounds to me like a short or other over-current situation.

This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.

do you have any recommendations for the power supply? one that i can connect to a breadbooard.

would a 9v battery work?

Personally, I prefer a wall adapter. Any 5V supply that can handle the rated peak load current (plus some for padding) for your servo. I did a quick search on Amazon and I have something like this supply.I also bought some connectors like this.

I'm definitely not doing these comment hyperlinks right but I'm not sure why..so just ignore that!

but how would I connect the battery to the breadboard

Do you mean the power supply? The connector that I linked in the previous comment fits on the end of the power supply cable and will allow you to screw a pair of wires in the end. You can plug these into a breadboard.

I realized the problem I had. I switched ground and 5v by accident in the tangle of wires. Lol


text:
Bit mask first 2 bits of 16 bits for accelerometer
The datasheet for the accelerometer states that:

Here is the data output from the accelerometer:

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.
I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:
int bresult=0b0011111111111111&result;
Serial.print(bresult,BIN);

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?
The variable result is of data type "long"
According to an answer, I tried:
int bresult= result<<2;
Serial.print(bresult,BIN);

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger?
The image below shows result then bresult.

That's odd, as 0b0011111111111111&result; works as expected on my Arduino. I just tested it as I didn't know about the 0b... notation (I only knew B...)

Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So
int bresult= result<<2;

Since <<2 is the same as *4 the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by 0.025 (or divide by 40), you end up having to multiply by 0.00625 (or divide by 160).

I tried to do this: int bresult= result<<2;
Serial.print(bresult,BIN);
However i still get 15 bits

Here is a screenshot : http://i.imgur.com/Ck35p4V.png

However, I am left with two zeros at the end of the value, making my value bigger. Is it possible to remove these two zeros? Here is a screenshot of result and bresult: http://prntscr.com/45j01c

Please re-read my answer, as already told you that would happen. Two extra 0s at the end means the result is 4 times too big.

For the arduino, long is 32 bits, int is 16 and char is 8.
Save the result in an int not a long. Then Gerben's method int bresult = (result << 2)/4 should work. This is because << 2 moves everything left two bits, but / 4 move every thing right two bits with new bytes the same as the sign bit. So you get a 16 bit signed variable with the correct number. If you have it as a long you would have to do
int bresult = (result << 18)/(2^18).
BTW Serial.print(bresult,BIN); is always going to give you up to 16 bits. There is no 14 bit type.

However, I am left with two zeros at the end of the value, making my value bigger. Is it possible to remove these two zeros? Here is a screenshot of result and bresult: http://prntscr.com/45j01c

As geo said, printing a result as binary will always show 16 bits. You will ALWAYS see 16 binary digits, no matter what. What are you trying to do with the output? If you need 14 bits of 1 and zero characters written to the serial output, you might need to write a custom function for that. It would be trivial to do.

@Hamoudy in the screen shot you haven't done the /4 yet.


text:
Unrecognizable Message From PROGMEM char*
I'm using a PROGMEM char* to store a massive array. When I try to print a certain part of the array, the message comes out mangled. How do I fix this?
The output should be "Poliwag", but it comes out as "arow".
#include <TrueRandom.h>
#include <EEPROM.h>
#define numPokemon 151
PROGMEM char* nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
"Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
"Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
"Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
"Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
"Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
"Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
"Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
"Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
"Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
"Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
"Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"
};
int a = 0;
int b = 0;
int value;
String pokemonName = "Missingno";
int currentID = TrueRandom.random(1,numPokemon+1);
// a = CurrentID
void setup(){
  Serial.begin(9600);
  if (EEPROM.read(a)!=0){
    currentID = EEPROM.read(a);
    Serial.print("The Stored ID is ");
    Serial.println(EEPROM.read(a));
    Serial.println("Stored = true");
  }else{
    value = EEPROM.read(a);
    Serial.println(value);
    EEPROM.write(a,currentID);
    value = EEPROM.read(a);
    Serial.println(value);
    Serial.println("Stored = false");
  }
  pokemonName = nameArray[currentID];
  Serial.println(pokemonName);
}
void loop(){

}

The way you've written in, the pointer is stored in flash, but the strings are stored in SRAM. Read the appropriate documentation (also found in the Arduino reference) more closely, and do as it says.
char nmPokemon0[] PROGMEM = "MISSINGNO";
char nmPokemon1[] PROGMEM = "Bulbasaur";
 ...

PGM_P nameArray[] PROGMEM =
{
  nmPokemon0, nmPokemon1, ...
};

And don't forget to copy the string to SRAM as shown further down before outputting it, since Serial.println() can't work directly with flash.

http://arduino.cc/en/Reference/PROGMEM has all of this info.


text:
Library for DIY Keyboard
I'm planning on making my own Bluetooth mechanical keyboard using the Adafruit Feather 32u4 Bluetooth LE. Something that I haven't really figured out is the programming side of things. I was wondering if there is an easy to use library for this.
I know of the KeyPad library but I'm not sure how to handle modifier keys like Shift and CTRL with it. Any idea can help!
Edit: Like said before the project I'm working on is a Bluetooth mechanical keyboard. So this means there will be 85 (at least for my design) switches in a matrix.
In an ideal world the library I'm looking for can do the following: I specify the keys and their position in a matrix and what the modifier keys are. It can generate the appropriate ASCII character when the matching key(s) are pressed and return it or something, so that I can send it over Bluetooth in another piece of code.
In a less ideal world I use the KeyPad library but I don't really know how to take care of modifier keys like shift when doing that.
Have a nice day!

What exactly the library should do? Your whole project?

@ThomasS. My project is a Bluetooth Mechanical Keyboard. I'm sorry for the fuzzy explanation, I updated the question. I hope its a bit better!

What is the problem of accessing a matrix, checking for keys (pressed and typed) and converting to the appropriate character/byte sequence? I don't see how a library would help here much because of the massive configuration. The only tiny problem you need to solve is that pressing multiple keys should be allowed by the circuit (e.g. using diodes in the rows or columns or, if you want to be perfect, for each key).

That's how I'm going to do it now. I just remembered coming a cross a library for making an USB keyboard that handled everything by itself. I thought I would need to handle lower- and uppercase letters in the code but it turns out you don't need to do that, you send a MODIFIERKEY_SHIFT command.

I do not have experience with the Bluetooth version of it, but at least with "normal" Arduinos, I found out that only the UNO could produce the correct sequences to enter BIOS configuration mode. This is due to the fact that the BIOS has very specific expectations. The UNO employs a secondary AVR chip to emulate the USB keyboard and it happens to be compliant with the BIOS expectations. Other Arduinos (nano, due, etc.) that rely on a sw library are not compliant. So you might want to check if you can enter BIOS config mode, before ditching other keyboards.

@IgorStoppa I'm currently using a Mac so I don't even have a BIOS to enter haha :) a very useful tip for other people though!

If you want to make it work anywhere near the what a keyboard does, you'll certainly want to make it a bluetooth HID keyboard. Also, you'll probably not want to multiplex the keys in a way that you can't handel specific patterns: www.microsoft.com/appliedsciences/antighostingexplained.mspx

For shift (making an a into an A), simply program in some ands. Pseudo-code:
if shift AND a:
    return A
elif shift AND b:
    return B

and so on and so forth.

Nope. Look at the ASCII table, you can use shift to decrease the ASCII value with 22, so you don't have to program it for every single combo

https://github.com/tmk/tmk_keyboard is what you want.
Search in Adafruit's site for how to incorporate Bluefruit.


text:
Detecting a 2.8ms pulse using a Arduino Uno
I am working on a project for knowing the position of a DC motor which has a hall sensor built into it. I am a newbie into programming using the Arduino Uno R3. After some forum search and self checks, I cannot pass this hurdle. I hope I can frame the questions properly here.
My Problem: The DC motor hall sensor sends out 2 high pulse of 11.3V - 13V with a duration of 2.8ms for each revolution. My Arduino interrupt pin doesn't read the high pulse as it gives me "0" count after motor spin (I run 50 loops and results remain the same).

On my breadboard, I use a voltage divider to reduce hall-effect ouput from max 13V to 5V so that the Arduino pin 2 can read rising voltage when it jumps to 5V (low should be 2.5V).
Couple of things I noted during the motor spin -
a) The millis() function returns 79-81ms per sketch run
b) The same hall sensor output if connected to analog pin reads 580,590,590,1001, 1012, 580, 580.. etc. I cannot gauge position of the motor by using these values as they are inconsistent on the way up Vs. way down.
I have attached analog readings while going up and down in snap shot below:

2 questions I have:

Why is the pin 2 not detecting a high pulse? will it not be able to read 2.8ms durations because of motor speed (9.5 rev/s or 570rpm)?
Is it possible to gauge anything from Analog read function? Am I missing something?

Thanks in advance for all responses.. Any questions regarding the circuit, I will be more than happy to post them.

"(low should be 2.5V)" Have you read the datasheet yet?

Please post all your code. I don't see where pulses is defined. Copy/paste it into your question, don't take a screenshot of it. You can format it by selecting it and pressing Ctrl+K.

First, better to see whole source and schematics.
"Why is the pin 2 not detecting"
Check:
1. Hall sensor connected to Pin 2

pulses variable declared as volatile.
Check if internal pull up resistor setup consistent with hall sensor connection.
Check that Hall sensor's lowest signal voltage is below 0.3 VCC (you said 5V, so it should drop below 1.5V), BTW 580 - the lowest analog value you showed means 2.83V
Check you are not using nointerrupt();

"Is it possible to gauge anything from Analog read function? Am "
Yes.
Analog read takes about 0.1 ms in default setup, so should make at least 1000 reads per second to catch peak.
So,
Easiest way is to choose some value like 600, when analog read is above mark it as Rising when it drops below mark is Falling.
More complicated ways will include some training and hysteresis to improve detection.
Also I suggest to use voltage limiter instead of voltage divider. This gives better detection.

1,2, 5 is checked. I will check the rest.

Best way is to test where the problem is to replace Hall sensor with button.

if with button arduino don't increase pulses variable, then problem is inside arduino (sketch code, port setup or internal schema) otherwise it is outside.
Anyway, I agreed with both Nicks, it will be helpful to provide whole sketch code.

@ all:  Lab is closed for thanksgiving. Will surely respond on the code and other items by Monday

All,
My Arduino is not reading interrupts across the interrupt pin:
I am getting a high of 1.456V and a low 1.07V through the interrupt pin 2... But the pulses counter still remain 0....
Any idea why?
  volatile unsigned int pulses=0; //pulse counter
  volatile int8_t steps=0;
  int timeu=0;
  int flag=2;

  void count()
  {
    pulses++;
  }

  void setup()
  {
    // initialize serial communication:
    Serial.begin(9600);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    pinMode(13,OUTPUT);
    pinMode(2,INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(2),count,RISING);

  }

  void stopmotor()
  {
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
    steps=0;
  }
  void motorCCW()
  {
    analogWrite(11,255);
    digitalWrite(12,HIGH);
    digitalWrite(13,LOW);
    steps=-1;
  }
  void motorCW()
  {
    analogWrite(11,255);
    digitalWrite(12,LOW);
    digitalWrite(13,HIGH);
    steps=1;
  }

  void loop()
  {

    if (timeu<=1000)//First time - Going up
    {
        sei();
        motorCW(); //moving up
        flag=8;
        timeu++;
      }
    else if (timeu==1000)
      {
          flag=10;
          stopmotor();
          cli();
          //Serial.print("Completed time cycle of 50");

      }

  if (flag==10)
  {
    Serial.print("pulses = ");
    Serial.print(pulses);
    Serial.println();

  }

  }

The interrupt is triggered by a rising edge of a digital input pin, where 0V is LOW and 5V is HIGH. The threshold voltage is going to be somewhere around 2.5V. It's not intended to look for a rising analog signal, but rather a full-off transition to a full-on state. If you wish to convert your Hall Effect sensor's output to a digital LOW/HIGH signal, you may need to use a comparator (OpAmps are okay at this.)

yes, Jose is right, according atmel specs, for 5V supply, LOW switched to HIGH when voltage grow above 3.5V and HIGH switched to LOW when voltage drops below 1.5V

I think problem is either Hall sensor connection wrong or your voltage dividers interfere each other.

As I understand, you Hall sensor's output is 0V near magnet and 13V other time (or vise-versa)
Check this answer to see how protect you digital pin from overvoltage.

The output across hall sensor is as follows:  for low pulse: 7.7V to 8.8V, for high pulse: 11.3V to 13.3V. My understanding from Andrey's feedback was i need to get the high below 1.5V.  My voltage divider is working good as i had changed resistors to match the required voltage. But in conclusion, i think its better to go with Jose's recommendation of a comparator to do the job.

Yes, I agree, for this voltage range better to use comparator.
Do you have datasheet for Motor and sensor?

All,
Here is the code:
int flag = 1;
int speedo = 255;
          int counter =0; //counts the number of revolutions
          int timeu=0;
          int timed=0;
          int Voltmeasure=0;
          int times=0;
          volatile unsigned int pulses=0; //pulse counter
          bool upcount=false;
          bool downcount=false;
          unsigned int timeold=0;
          int difference=0;

          void count()
          {
            if(upcount==true)
              pulses++;
              else if (downcount==true)
               pulses--;
          }

          void setup()
          {
            // initialize serial communication:
            Serial.begin(9600);
            pinMode(11,OUTPUT);
            pinMode(12,OUTPUT);
            pinMode(13,OUTPUT);
            pinMode(2, INPUT);
            pinMode(3, INPUT);
            attachInterrupt(digitalPinToInterrupt(2),count, RISING);
          }
          void stopmotor()
          {
            digitalWrite(12,HIGH);
            digitalWrite(13,HIGH);
          }
          void motorCCW()
          {
            analogWrite(11,speedo);
            digitalWrite(12,HIGH);
            digitalWrite(13,LOW);
          }
          void motorCW()
          {
            analogWrite(11,speedo);
            digitalWrite(12,LOW);
            digitalWrite(13,HIGH);
          }

          void loop()
          {
              if(flag==1)
              {
                delay(2000); //wait for 2 seconds to start motor
                flag=2;
              }

            //first run motor moves down
                if (counter<16 && flag==2)
                {
                  motorCW(); //moving up

                  //Reading Hall-sensor pulses- using analog signal
                  Voltmeasure = analogRead(A3);
                  Serial.print("CW Voltmeasure = ");
                  Serial.print(Voltmeasure);
                  Serial.println();

                  //Reading Hall-sensor pulses - using interuppt signal
                  upcount=true;

                  //counting the number of high pulse
                  if (Voltmeasure>700 && times==0)
                  {
                    counter++; times=1;
                  }
                  else if (Voltmeasure<610)
                    times=0;

                  //timer for number of loops
                  timeu++;
                  Voltmeasure=0;

                  if (timeu==70||counter==16) //move by 70 cycles or until counter is 16
                  {
                    stopmotor();
                    upcount=false;
                    timeu=0;
                    times=0;
                    Serial.print("High-point is reached - Travel complete");
                    Serial.println();
                    delay(2000); //delay by 2 seconds
                    flag=3;
                  }
                }

                if (counter>0 && flag==3)
                {
                  delay(2000); //pause before next run
                  motorCCW();

                  //Reading Hall-sensor pulses - using analog signal
                  Voltmeasure = analogRead(A3);
                  Serial.print("CCW Voltmeasure = ");
                  Serial.print(Voltmeasure);
                  Serial.println();

                  //Reading Hall-sensor pulses - using interuppt signal
                  downcount=true;

                 //counting the number of high pulse
                  if (Voltmeasure>700)
                  {
                    counter--; times=1;
                  }
                  else if (Voltmeasure<610)
                    times=0;
                  timed++;
                  Voltmeasure=0;

                  if (timed==70||counter==0) //move by 70 cycles or until counter is 0
                  {
                    stopmotor();
                    downcount=false;
                    timed=0;
                    times=0;
                    Serial.print("Lowest point is reached - Travel complete");
                    Serial.println();
                    flag=3;//stop motor
                  }
                 }

          //  difference=millis()-timeold;
          //  timeold = millis();
          //
          //  //Printing information after line complete
          //  Serial.print("time for one sketch = ");
          //  Serial.print(difference);
          //  Serial.println();

            Serial.print("Counter = ");
            Serial.print(counter);
            Serial.println();

            Serial.print("pulses = ");
            Serial.print(pulses);
            Serial.println();

          }

General block diagram

Motor with Hall sensor, Ve is 13V, Ue is 13.5V:

I print the counter (Analog pin) and pulses (interrupt pin) with running this program code.
The Analog pin reads:
CW Voltmeasure = 574
CW Voltmeasure = 588
CW Voltmeasure = 1000
CW Voltmeasure = 999
CW Voltmeasure = 998
CW Voltmeasure = 1002
CW Voltmeasure = 1002
CW Voltmeasure = 589
CW Voltmeasure = 588
CW Voltmeasure = 590
CW Voltmeasure = 588
CW Voltmeasure = 1000......by this time motor spins 6.5 rev (based on time elapsed) but counter is only @ 3 (3 highs)
Pulses read 0.......
This is where i am at. Not able to understand Analog readings dont match the number of revs with the highs & why interupt pin reads 0......

Any help guys? Any questions?

Serial printing take some time. According you speed, 1 symbol takes about 1 ms, so sending "CW Voltmeasure = " by serial can take up to 16 ms (when serial buffer full) which is enough to miss one pulse.

What 5.01 voltmeter shows when sensor switched? According logs this should be about 2.8 V

And this is not enough to trigger interrupt.

Andrey, are you asking to switch the connections betw hall sensor & 5.01V points?

What more is required for interrupt pin?

I asked to mesure voltage on 5V divider, when Hall should be low

Also, I am printing CW voltmeasures only for explaining the problem, i am commenting them when running otherwise.

Understood. Did you any tests with button?

it measures 2.82 V at low

It should be below 1.5V to trigger interrupt on pin 2

Not yet. But i am not sure how that will help.

oh ok.. I will bring it down using another voltage divider to 1.5V for measuring interrupts. Thanks!

missed voliatile on upcount/downcount will cause ISR not working.
Also I siggest:

replace upcount/downcount by volatile int8_t step = 0;

void count() { pulses += step; }

move step = 1 and step = -1 inside motorCW/motorCCW

volatile int8_t steps=0;
void count()
{
pulses+=steps;
}
void setup()
{
// initialize serial communication:
Serial.begin(9600);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(2, INPUT);
attachInterrupt(0,count, RISING);
}
void stopmotor()
{
digitalWrite(12,LOW);
digitalWrite(13,LOW);
}
void motorCCW()
{
analogWrite(11,speedo);
digitalWrite(12,HIGH);
digitalWrite(13,LOW);
steps=-1;
}
void motorCW()
{
analogWrite(11,speedo);
digitalWrite(12,LOW);
digitalWrite(13,HIGH);
steps=1;
}

About button. After you place button in parallel with resistor between Pin 2 and GND you will be able to emulate Hall sensor like it is properly connected.

I added to motorCW() and motorCCW() and also changed the count function as you said. Am i correct?

yes, looks like correct.
don't forget to put step = 0 to stopMotor.

Sounds good.. yea i added to stop motor also. I will run this and provide feedback

Andrey, still no pulses reading. I am getting a high of 1.456V and a low 1.07V through the voltage divider... pulses remain 0....

I tried modifying the voltages to interrupt pins
Now interrupt pin voltages read:
High:1.456V
Low: 1.07V
Note: The arduino is running at 12V external source.
My "pulses" counter still reads 0 for interrupts. Any idea why?

All,
I didnt need the voltage comparator in the end, the code was running slower and wasnt picking up all the hall sensor signals that the motor was giving due to loop time. i changed the ifs to else ifs and then i was able to get a faster loop time.
Thanks all for the help.
The device is working as intended..


text:
Arduino Pro Micro bricked?
I have a Pro Micro board at which tried to upload a sketch with sparkfun's Pro Micro 3.3v processor selected.
After the upload completed successfully the board did not run again and is not even detected from the arduino ide anymore.
When I uploaded sketches with the leonardo 5.5v board selected everything went well and I had no problem. Now I can not burn the bootloader because of the arduino ide not detecting the board.
What can i do?

Nothing special, it was the sd example for listing the micro sd files that the ide has

I think that the 3.3v selected version is what caused the problem but I do not know what to do

if the sketch fails, USB is not handled. so you must activate the bootloader by activating reset twice. led should blink fast until it is active

Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.
Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.
I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board

and you know that I copied the comment from our chat about the not soldered board where you could not reset the board https://chat.stackexchange.com/transcript/message/47422785#47422785

@Juraj damn you are everywhere :P Soldering the pins was my problem indeed, I bought a soldering iron and some alloy, and now everything works just fine!

score! THanks for this, probably in the manual I did not read.

After bricking a few units I finally sat down and read the manual for my SparkFun Qwiic Pro Micro - USB-C (ATmega32U4). I also figured out the cause.
The cause of my unit bricking was bad code. Compiled and profiled fine, but crashed the unit when uploaded.  As a result the port became unavailable and seemingly gone.  In my particular case one brick was via and unsupported command in my source. The second brick was abuse of memory. Sketches would upload, then the unit dies and the no connection message pops up.
The solution for this unit was use of the reset switch with some key timing, and a trusted script to recapture the device.  This page was all I needed to read, classif #RTFM syndrome.
The following is a layman version of events for those less fortunate having not endured decades of software brain melt.
Recovery in a Nutshell
The USB port/comm when working will/can flip between the "normal" mode and the bootloader mode.  Bootloader is a mode where the devices is exposed and can receive code and special commands.
If something, like the code, is causing the device to crash, such as I had, then the desired USB/serial port is not available.
The Reset Switch
The reset switch may also be some pins to be shorted.  The manual talks about high/low and resistance.  Generally I have found you just short the damn thing, milage may vary. I used the button.
Per the instructions you can double tab the button and then I seem to trail off and not really absorb the rest. Eventually I got the pattern.
The Pattern
If you double click the reset button the device goes into boot loader for 8 seconds.
Find a short "hello world" sketch and have it ready.
Double tap the reset button and immediately upload the sketch.

That may not work...

When uploading a sketch the beginning of the upload is the compile step.  This must complete before there is anything to ship to the device.
I had to click upload and then double tap and get the timing right.  Eventually I would use the shortcut (CMD/CRTL + U).  The sketch takes and the device is back to normal.
Hope this helps someone - I needed the dummy version.