A library for the MCP3221 12BIT I2C ADC. (2.7 - 5.0v)
Dependents: MCP3221_TEST ADC2DAC
MCP3221.cpp
- Committer:
- DaveStyles
- Date:
- 2012-10-31
- Revision:
- 0:db4e3d0374fe
File content as of revision 0:db4e3d0374fe:
#include "MCP3221.h" //Create instance MCP3221::MCP3221(PinName sda, PinName scl, float supplyVoltage) : i2c(sda, scl), _supplyVoltage(supplyVoltage) { } //destroy instance MCP3221::~MCP3221() { } float MCP3221::read() { //You cannot write to an MCP3221, it has no writable registers. //MCP3221 also requires an ACKnowledge between each byte sent, before it will send the next byte. So we need to be a bit manual with how we talk to it. //It also needs an (NOT) ACKnowledge after the second byte or it will keep sending bytes (continuous sampling) // //From the datasheet. // //I2C.START //Send 8 bit device/ part address to open conversation. (See .h file for part explanation) //read a byte (with ACK) //read a byte (with NAK) //I2C.STOP // char data[2]; i2c.start(); int acknowledged = i2c.write(MCP3221_CONVERSE); //send a byte to start the conversation. It should be acknowledged. _data[0] = i2c.read(1); //read a byte. acknowledge when we have it. _data[1] = i2c.read(0); //read the second byte. (n)acknowledge when we have it to stop the flow. i2c.stop(); //convert to 12 bit. short res; int _12_bit_var; // 2 bytes char _4_bit_MSnibble = _data[0]; // 1 byte, example 0000 1000 char _8_bit_LSByte = _data[1]; // 1 byte, example 1111 0000 _12_bit_var = ((0x0F & _4_bit_MSnibble) << 8) | _8_bit_LSByte; //example 100011110000 res=_12_bit_var; return (_supplyVoltage/4096) * res; }