ADS1115与MSP430的使用
时间:10-02
整理:3721RD
点击:
ADS1115是超小型的,宽电压16位AD转换器,通过一个I2c接口与MCU相连,官方给的电路连接图如下
驱动程序如下
#include<msp430g2553.h> #include "ads1115.h" void delay() { uint i; for(i=0;i<20000;i++); } void wait() { uchar i=3; while(i--); _NOP(); } void start() { S_SDA; //数据线拉高 wait(); S_SCL; //时钟为高 wait(); C_SDA; //数据线拉低,表起始信号 wait(); C_SCL; //时钟为低,允许数据改变 wait(); } void stop() { C_SCL; wait(); C_SDA; wait(); S_SCL; wait(); S_SDA; //在SCL为高器期间,数据线上升,表停止 } void ack() //应答 { C_SDA; wait(); S_SCL; wait(); C_SCL; wait(); S_SDA; } uchar check_ack() { uchar ack; S_SDA; wait(); S_SCL; wait(); ack=SDA & 0x80; C_SCL; _NOP(); if(ack) return 1; //无应答 else return 0; //有应答 } void write_byte(uchar byte) { uchar i; C_SCL; for(i=0;i<8;i++) { if(byte & 0x80) S_SDA; else C_SDA; //送数据 wait(); S_SCL; //拉高控制线 wait(); C_SCL; //拉低时钟线,允许数据改变 byte <<= 1; //准备下一位 } } uchar read_byte(void) { uchar byte=0,i; P1DIR &= ~BIT7; wait(); for(i=0;i<8;i++) { S_SCL; wait(); byte <<= 1; if(SDA & 0X80) byte |= 0x01; C_SCL; wait(); } return byte; } void write_word(uchar addr,uint word) { uchar byte=0x90; //0b10010000 start(); write_byte(byte); //写地址 byte = check_ack(); write_byte(addr); //指定寄存器 byte = check_ack(); write_byte(word>>8); //写高字节 byte = check_ack(); write_byte(word); //写低字节 byte = check_ack(); stop(); } uint read_word(uchar addr) { uint word; uchar byte=0x90; //0b10010000 start(); write_byte(byte); //写地址 byte = check_ack(); write_byte(addr); //指定寄存器 byte = check_ack(); stop(); wait(); start(); byte=0x91; //0b10010001 write_byte(byte); //写地址,操作为读 byte = check_ack(); word = read_byte(); //读高字节 ack(); word <<= 8; byte = read_byte(); //读低字节 ack(); word += byte; stop(); return word; } void main(void) { uint value; uint tmp; float u; WDTCTL=WDTPW+WDTHOLD; P1DIR |= BIT1; P1OUT &= ~BIT7; stop(); while(1) { write_word(0x01,0xc383); //0b1100 0011 1000 0011 delay(); value = read_word(0x00); //读取值 tmp = value & 0x7fff; u = 4.096 * tmp / 32768; if(value>0x7fff) u = 0.0; u *= 1000; } }
ADS1115的时序要求比较严格,针对不同的MCU移植时需要注意时间