STM8S103F3P6製作電子秤
#include <stm8s.h>#define CLK_FREQ 16000000UL // 定義系統時鐘頻率
void main(void)
{
// 初始化系統時鐘
CLK_DeInit();
CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1); // 16MHz
// 初始化GPIO
GPIO_Init(GPIOA, GPIO_PIN_1, GPIO_MODE_IN_FL_NO_IT); // 負載細胞接口+
GPIO_Init(GPIOA, GPIO_PIN_2, GPIO_MODE_IN_FL_NO_IT); // 負載細胞接口-
GPIO_Init(GPIOD, GPIO_PIN_4, GPIO_MODE_IN_PU_IT); // 按鈕接口
GPIO_Init(GPIOD, GPIO_PIN_5, GPIO_MODE_OUT_PP_LOW_FAST); // LED顯示燈
// 初始化I2C
I2C_DeInit();
I2C_Init(100000, 0x02, I2C_DUTYCYCLE_2, I2C_ACK_CURR,
I2C_ADDMODE_7BIT, CLK_FREQ); // I2C頻率100KHz
// 初始化計時器
TIM4_DeInit();
TIM4_TimeBaseInit(TIM4_PRESCALER_128, 125); // 溢出頻率1kHz
// 啟用中斷
enableInterrupts();
while(1)
{
// 讀取負載細胞數據
uint16_t weight = getWeight();
// 顯示數據
displayWeight(weight);
}
}
uint16_t getWeight()
{
uint16_t weight = 0;
uint16_t adcVal = 0;
// 讀取ADC數據
ADC1_DeInit();
ADC1_Init(ADC1_CONVERSIONMODE_SINGLE, ADC1_CHANNEL_3,
ADC1_PRESSEL_FCPU_D8, ADC1_EXTTRIG_TIM, DISABLE,
ADC1_ALIGN_RIGHT, ADC1_SCHMITTTRIG_CHANNEL3, DISABLE);
ADC1_Cmd(ENABLE);
ADC1_StartConversion();
while(ADC1_GetFlagStatus(ADC1_FLAG_EOC) == RESET);
adcVal = ADC1_GetConversionValue();
// 轉換數據到重量值
weight = (adcVal
return weight;
}
void displayWeight(uint16_t weight)
{
// 將數字轉換為字元
char weightStr;
sprintf(weightStr, "%05d", weight);
// 顯示數字
uint8_t i = 0;
for(i = 0; i < 5; i++)
{
sendDigit(weightStr);
}
}
void sendDigit(char digit)
{
// 顯示器地址
const uint8_t addr = 0x3F;
// 字元數字表
const uint8_t numTable = {0x3F, 0x06, 0x5B, 0x4F, 0x66,
0x6D, 0x7D, 0x07, 0x7F, 0x6F};
// 轉換字元為數字
uint8_t num = 0;
if(digit >= '0' && digit <= '9')
{
num = numTable;
}
// 發送數字到顯示器
I2C_GenerateSTART(ENABLE);
while(!I2C_CheckEvent(I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(addr << 1, I2C_DIRECTION_TX);
while(!I2C_CheckEvent(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(num);
while(!I2C_CheckEvent(I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTOP(ENABLE);
}
頁:
[1]