Samsanit
Samsanit

Reputation: 25

Using bit shift with SPI data in processing

For a research project that I'm doing for my chemistry lab we are using and ADS8320 chip (Data Sheet found here. We are using this to take in voltage readings with a potentiometer through the SPI pins on a Raspberry Pi 3. While I have been able to get data using this code from Processing.org:

import processing.io.*;
SPI adc;

void setup() {
  //printArray(SPI.list());
  adc = new SPI(SPI.list()[0]);
  adc.settings(500000, SPI.MSBFIRST, SPI.MODE0);
}

void draw() {
  // read in values over SPI from an analog-to-digital
  // converter
  // dummy write, actual values don't matter
  byte[] out = { 0, 0 };
  byte[] in = adc.transfer(out);
  // some input bit shifting according to the datasheet
  int val = ((in[0] & 0x1f) << 5) | ((in[1] & 0xf8) >> 3);
  // val is between 0 and 1023
  println(val);
}

From what I read on the data sheet I should be getting a value of 65535 when taking in the max voltage. Instead I am getting a value of 127 when taking in max voltage. I'm not by any means a good programmer having picked it up almost exactly a month ago, but I think the issue lies in the bit shift line of code:

int val = ((in[0] & 0x1f) << 5) | ((in[1] & 0xf8) >> 3);

if this is the issue how would I set it to work with my 16 bit ADS chip? Could you also explain what this bit shift actually is for, as every source I found on it just made me more confused. Any help on this would be insanely helpful! Also if I am missing any critical information please let me know, as again I am still pretty new at this.

Upvotes: 0

Views: 453

Answers (1)

user8890895
user8890895

Reputation:

That line of the code is how you read your 10 bit value from the chip. input 0 (in[0]) has the 5 most significant bits of your data and input 1 (in[1]) has the 5 least significant bits. Hence, the shift operation. Imagine your data has 10 bits, you do (0b00011111 AND Input[0]) and you shift it to left by 5. Then you do (0b11111000 AND Input[1]) and shift it to right by 3. At the end, when putting them together with OR val1 | val2, you will be left with a 10 bit value. However, if you visit the data sheet of your chip, your chip is a 16 bit ADC, which means you migh need another pins to read the extra 6 bits you are not reading. Furthermore, make sure you are connecting correct pins to in[0] and in[1] as it can revers the orientation of your bit streams.

Upvotes: 1

Related Questions