Go Down

Topic: [SOLVED] Bit Bangin' (Read 111 times) previous topic - next topic

outsider

Nov 11, 2018, 02:11 am Last Edit: Today at 07:26 am by outsider
Is there a simpler / cleaner way to do line 31?  :smiley-confuse:
I want to preserve the upper nybble of PORTB and insert ONLY the LOWER nybble of hSteps[].
Code: [Select]
   PORTB = (hSteps[cntr & 0x7] & 0x0F) | (PORTB & 0xF0);

Code: [Select]

/* pin 8 to pin 1 on ULN2003, pin 16 to pink,   coilA
       9 to pin 2,                15    yellow, coilC
      10 to pin 3,                14    orange, coilB
      11 to pin 4,                13    blue,   coilD

   Type a number in top of serial monitor for steps to go,
    -2 billion (CCW) to 2 billion (CW) & press [ENTER].
*/
uint32_t tStart, tEnd = 916UL;
const byte fSteps [8] = {0x01, 0x02, 0x04, 0x08, 0x01, 0x02, 0x04, 0x08};
const byte hSteps [8] = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};
byte cntr = 0;
long stg; // steps to go

void setup()
{
  Serial.begin(9600);
  DDRB = 0x0F; // set pins 8,9,10,11 to OUTPUT
}
void loop()
{
  if (Serial.available() > 0)
    {
      stg =  Serial.parseInt();
      Serial.println(stg);
    }
  if (stg != 0)                  
  {
    tStart = micros();
    while(micros() - tStart < tEnd);
    PORTB = (hSteps[cntr & 0x7] & 0x0F) | (PORTB & 0xF0);
      // sets direction, adds to or subtracts from stg
      // depending on direction
    stg < 0 ? cntr-- : cntr++;
    stg < 0 ? stg++ : stg--;
  }
}

 TNX All.

DKWatson

PORTB = (hSteps[cntr & 0x7] & 0x0F) | (PORTB & 0xF0);
You don't need the last bit if you just change the assignment
PORTB |= (hSteps[cntr & 0x7] & 0x0F);
Live as if you were to die tomorrow. Learn as if you were to live forever. - Mahatma Gandhi

MorganS

But that's incapable of setting any bits to 0 in the region that is being modified. I think the original code is about as clear and simple as you can get.
"The problem is in the code you didn't post."

DKWatson

Right you are. How about,

PORTB &= 0xF0 | (hSteps[cntr & 0x7] & 0x0F);

It's just a shuffle, but maybe better for the photographers?
Live as if you were to die tomorrow. Learn as if you were to live forever. - Mahatma Gandhi

westfw

Quote
Code: [Select]
   PORTB = (hSteps[cntr & 0x7] & 0x0F) | (PORTB & 0xF0);
I don't think that the "& 0x0F" does anything - all your hsteps values already have the high bits clear...

Go Up