STM32驱动_HX711

文章目录

HX711.c

  HX711.c

#include "HX711.h"
#include "delay.h"

#define GapValue 430

u32 Weight_Maopi;
s32 Weight_Shiwu;

void HX711_InIt ( void ) {
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd ( RCC_APB2Periph_GPIOB, ENABLE );
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init ( GPIOB, &GPIO_InitStructure );
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init ( GPIOB, &GPIO_InitStructure );
}

unsigned long HX711_Read() {
    
    
    unsigned int val = 0;
    unsigned char i = 0;
    DOUT = 1;
    SCK = 0;

    while ( DIN );

    delay_us ( 1 );

    for ( i = 0; i < 24; i++ ) {
    
    
        SCK = 1;
        val = val << 1;
        delay_us ( 1 );
        SCK = 0;

        if ( DIN ) {
    
    
            val++;
        }

        delay_us ( 1 );
    }

    SCK = 1;
    val = val ^ 0x800000;
    delay_us ( 1 );
    SCK = 0;
    delay_us ( 1 );
    return val;
}

u32 Get_Maopi() {
    
    
    Weight_Maopi = HX711_Read();
    return Weight_Maopi;
}

void Get_Weight() {
    
    
    Weight_Shiwu = HX711_Read();
    Weight_Shiwu = Weight_Shiwu - Weight_Maopi;

    if ( Weight_Shiwu > 0 ) {
    
    
        Weight_Shiwu = ( unsigned short ) ( Weight_Shiwu * 1.0 / GapValue );
    } else {
    
    
        Weight_Shiwu = 0;
    }
}

HX711.h

  HX711.h

#ifndef _HX711_H
#define _HX711_H
#include "sys.h"

#define DOUT PBout(12)
#define SCK  PBout(13)
#define DIN  PBin(12)

void HX711_InIt ( void );
void Get_Weight ( void );
u32 Get_Maopi ( void );
#endif

main.c

  main.c

#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "HX711.h"

extern s32 Weight_Shiwu;

int main ( void ) {
    
    
    SystemInit();
    delay_init ( 72 );
    NVIC_Configuration();
    uart_init ( 9600 );
    HX711_InIt();
    Get_Maopi();

    while ( 1 ) {
    
    
        Get_Weight();
        printf ( "%dg\r\n", Weight_Shiwu );
        delay_ms ( 500 );
    }
}

猜你喜欢

转载自blog.csdn.net/fukangwei_lite/article/details/121043040