How to change bits in C?

I am trying to write a function in C that will shift individual bits of a byte based on a clock signal. So far I have come up with this ...

void ShiftOutByte (char Data)
{
    int Mask = 1;
    int Bit = 0;
    while(Bit < 8)
    {
        while(ClkPin == LOW);
        DataPin = Data && Mask;
        Mask = Mask * 2;
        Bit++;
    }
}

where DataPin represents the port that I want to transfer data, and ClkPin is the output of the clock port.

I want the device to shift 8 bits, starting with the low byte of the byte. For some reason, my output is constantly high. I am sure that the port pins are configured correctly, so this is a logical problem.

+3
source share
3 answers

Your solution is almost there, but there are several problems:

  • , , , , , , ( , ). , . , , - , , .
  • (& &) (&), ,
  • , , DataPin 0 1. , . , (1, 2, 4, 8,...) .

, , - :

void ShiftOutByte (unsigned char Data)
{
    int Bit;
    for(Bit=0; Bit < 8; ++Bit)
    {
        while(ClkPin == HIGH);
        while(ClkPin == LOW);
        DataPin = Data & 1;
        Data >>= 1;
    }
}

. for while ... Bit++.

+3

&, not & &. && , .

+5

, , . && 1, . Data , .

This may mask a more subtle problem. I don’t know what your target architecture is, but if DataPinit is actually a one-bit broadcast register, then you probably need to be careful not to try to assign values ​​other than 0 or 1 to it. One way to achieve this is to write DataPin = !!(Data & Mask);. Another is moving data in the other direction and using a fixed mask 1.

+1
source

Source: https://habr.com/ru/post/1763862/


All Articles