Little driver for the MCP3421 18bits ADC

Place your projects here
Post Reply
User avatar
cicciocb
Site Admin
Posts: 2195
Joined: Mon Feb 03, 2020 1:15 pm
Location: Toulouse
Has thanked: 470 times
Been thanked: 1461 times
Contact:

Little driver for the MCP3421 18bits ADC

Post by cicciocb »

Hi all,

Here you can find a very simple library for the ADC 18bits MCP3421.
This chip has a programmable resolution going from 12 to 18 bits coupled with a PGA (Programmable Gain Amplifier) with a gain of 1, 2, 4 or 8.
The chip has an input range of +-2.048V (+-2048mV) differential (it can measure positive and negative voltages).
Increasing the gain will increase the sensitivity but will reduce the scale (at gain=8 the scale will be 2048/8 = +-256mV).

The code contains two subroutines (SUBs): one that configure the chip (resolution and gain) and the other that read the value of the input signal.

In the code is shown how convert the value directly in millivolts, taking into account the resolution and the gain.

I hope it will be useful to someone.

Code: [Local Link Removed for Guests]

'ANNEX32 RDS MCP3421 library
SDA = 47
SCL = 21
I2C.SETUP SDA, SCL

' Set the resoluation and the gain
nb_bits = 18
gain = 1
mcp3421_config nb_bits, gain

v = 0
while 1
  mcp3421_read v, nb_bits 
  'computes conversion to volts
  ' gain=1 @ 12 bits-> 1mv
  ' gain=1 @ 18bits -> 0.015625mv (1/64)
  scale =  1 / (2^(nb_bits - 12))
  mVolts = v * scale / gain
  wlog mVolts; " mV"
  pause 1000
wend
end

'read the value from the chip MPC3421
'nb_bits can be 12, 14, 16 or 18
'value returns the reading
sub mcp3421_read(value, nb_bits)
  dim v(4)
  i2c.reqfrom &h68, 3
  for i = 1 to 3
    v(i) = i2c.read
   next i
  select case nb_bits
    case 12 
      value = (v(1) and &hf) << 8 or v(2)
      if (value > 2048) then value = value - 4096
    case 14
      value = (v(1) and &h3f) << 8 or v(2)
      if (value > 8192) then value = value - 16384
    case 16
      value = v(1) << 8 or v(2)
      if (value > 32768) then value = value - 65536
    case 18
      value = (v(1) and &h3) << 16 or (v(2) << 8) or v(3)
      if (value > 131072) then value = value - 262144
    case else
      value = 0
  end select
  'wlog v(1), v(2), v(3)
end sub

'configure the chip MPC3421
'nb_bits can be 12, 14, 16 or 18
'gain can be 1, 2, 4 or 8
sub mcp3421_config(nb_bits, gain)
  local rate, pga 
  select case nb_bits
    case 12 : rate = 0
    case 14 : rate = 1
    case 16 : rate = 2
    case 18 : rate = 3
    case else : rate = 0
  end select
  select case gain
    case 1 : pga = 0
    case 2 : pga = 1
    case 4 : pga = 2
    case 8 : pga = 3
    case else : pga = 0
  end select  
  i2c.begin &h68
  i2c.write (rate <<2) or pga or &h10 ' continuous mode
  i2c.end  
end sub
Post Reply