Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arduino `shiftOut()` function in native c

Tags:

c

bit

arduino

I'm trying to create the equivalent of the arduino shiftOut() function in native c on my mcu.

I want to send the command int gTempCmd = 0b00000011; via a shiftOut() type function with MSBFIRST.

What would the pseudo code for this look like so I can try map it my mcu's gpio functions?

Thanks

float readTemperatureRaw()
{
  int val;

  // Command to send to the SHT1x to request Temperature
  int gTempCmd  = 0b00000011;

  sendCommandSHT(gTempCmd);
  ...
  return (val);
}


//Send Command to sensor
void sendCommandSHT(int command)
{
  int ack;

  shiftOut(dataPin, clockPin, MSBFIRST, command);
  ....
}
like image 783
pelican Avatar asked Oct 19 '22 12:10

pelican


1 Answers

Consider the following 'psuedo-c++'

The code works as follows:

  • take the highest, or lowest bit in the word by AND-ing with all zero's except the MSB or LSB, depending on the MSBFIRST flag
  • write it to the output pin
  • shift the command one step in the right direction
  • pulse the clock pin
  • repeat 8 times, for each bit in the command

It is fairly trivial to expand this to an arbitrary number of bits upto 32 by adding a parameter for the number of repetitions

void shiftOut(GPIO dataPin, GPIO clockPin, bool MSBFIRST, uint8_t command)
{
   for (int i = 0; i < 8; i++)
   {
       bool output = false;
       if (MSBFIRST)
       {
           output = command & 0b10000000;
           command = command << 1;
       }
       else
       {
           output = command & 0b00000001;
           command = command >> 1;
       }
       writePin(dataPin, output);
       writePin(clockPin, true);
       sleep(1)
       writePin(clockPin, false);
       sleep(1)
    }
}
like image 143
Pelle Avatar answered Oct 21 '22 04:10

Pelle