Go Down

Topic: If umbrellas or Case for buttons and sensors? (Read 1 time) previous topic - next topic

Nick Gammon

#5
May 22, 2011, 10:46 pm Last Edit: May 23, 2011, 12:44 am by Nick Gammon Reason: 1

>>>or could I do a long if like

if (digitalRead (10) == HIGH && digitalRead (11) == HIGH && etc. )

>>>or will non of this make much difference and not matter?



The "long if" saves having to repeat the action, so that would save marginal space. It might look neater as:

Code: [Select]
if (digitalRead (10) == HIGH &&
   digitalRead (11) == HIGH &&
   etc. )
 allstop ();


(edit) - see below, the && should be ||. You want to stop if any switch is pressed, not all of them.

If you are testing lots of switches it could be faster to do direct port access. This is because digital pins 10, 11, 12 are all on the same port of the processor port. So for speed (but not necessarily clarity) you could do:

Code: [Select]
if (PORTB (_BV(PIND10) | _BV(PIND11) | _BV(PIND12)) != 0)
 allstop ();


What that is doing is a single read of port B and testing if any of the bits corresponding to D10, D11, or D12 are set. So that is a single read and a single test (the compiler will optimize out or'ing together the various bits at compile time).

Asa Herring

It sounds like this is the direction that I need to go in. Thanks

Now to be specific, I have an Arduino Mega 1560 and I am actually using pins 3, 11, 12, 13 for the main stepper motor and 4, 5, 6, 7, 8, 9 for the LCD. I have arbitrarily picked 22 and 24 for the second stepper motor.

Does the PORTB range of pins start and stop somewhere? What series do you think would work best for me?
I have an Arduino Mega 2560. I also have a (pH) BNC Sensor Shield,an I2C/SPI/Onewire Shield(I beleive that it an on board clock.)and a Breakout Board Shield, all three are from Andrew Oke. Additionally, I have a Stepping Motor but could certainly buy a Servo Motor instead if it is any better for what I want to do, short term/long term. Trying to read the lable, I guess that it is: Type 57BYG. 12 V/Phase, 20ohm, 0-6A/Phase 1.8 Deg/Step, No. 04052 with a K179 Stepper Driver board attached. I can't confirm that the board is fully funtional

Nick Gammon

Yes it does. Each port handles a maximum of 8 pins, as they are 8-bit ports. Look, for something like a stepper motor controller, doing the digitalRead approach is probably absolutely fine, and then you don't need to look up which pins belong to which ports. The direct read saves a few microseconds, not a great amount.

PaulS

Code: [Select]
if (digitalRead (10) == HIGH &&
    digitalRead (11) == HIGH &&
    etc. )

I think you want || there, not &&.

Nick Gammon

Quite right. I amended the earlier post to add an addendum.

Go Up