Hôm nay mình giới thiệu module DAC MCP4922 ứng dụng điều khiển Biến tần
Về phần cứng :

Mạch mình dùng ADUM1401 để cách ly GND chống nhiễu cho MCU
Mạch có 2 chế độ 0-5V và 0-10V
Công thức mạch khuếch đại thuật toán Ur=Uin*(1+R2/R1)
Nếu R2=R1=0R chế độ 0-5V nếu R2=R1=10K chế độ 0-10V
Chú ý điện áp cấp cho LM358 là 12VDC hoặc 24VDC
Về code có thể dùng avr và stm32F1 đều giống nhau
#define DA_SCK PORTA_0 // ??????????
#define DA_SDI PORTA_1 // ?????????
#define DA_CS PORTA_2 // ????????
#define DA_LDAC 9 // ?????????
void convert_dac(unsigned char x)
{ // do chuc nang ghi dich 8 bit vao noi tiep ra song song
// do do vong for duoi se cho dich 8 lan de du 8 chan dau ra cho vdk
int i,tam;
for(i=0;i<8;i++) // 8 lan dich de co 8 bit
{
tam=x;
tam=tam&0x80;
if(tam==0x80) DA_SDI=1;
else DA_SDI=0;
x=x<<1; // dich bit nhu sau
DA_SCK=1;
DA_SCK=0;
}
}
void update_channels( unsigned int chA, unsigned int chB )
{
// write a value to channel A
buf[0] = (0 << 7) | (buffered << 6) | (gain << 5) | (shdn << 4) | (chA >> 8);
buf[1] = (chA & 0xff);
convert_dac( buf[0]);
convert_dac( buf[1]);
DA_CS =1;
DA_CS =0;
// write a value to channel B
buf[0] = (1 << 7) | (buffered << 6) | (gain << 5) | (shdn << 4) | (chB >> 8);
buf[1] = (chB & 0xff);
convert_dac( buf[0]);
convert_dac( buf[1]);
DA_CS =1;
DA_CS =0;
// Update DAC output
}
void analogWrite(unsigned char odd, unsigned char buffered, unsigned char gain, unsigned char active, unsigned int value)
{
unsigned char configBits ;
unsigned char firstByte ;
unsigned char secondByte;
configBits = odd << 3 | buffered << 2 | gain << 1 | active;
// Compose the first byte to send to the DAC:
// the 4 control bits, and the 4 most significant bits of the value
firstByte= configBits << 4 | (value & 0xF00) >> 8;
// Second byte is the lower 8 bits of the value
secondByte = value & 0xFF;
convert_dac(firstByte);
convert_dac(secondByte);
DA_CS =1;
DA_CS =0;
}
Code STM32F4 tương tự