Re: 程式是這樣要把ADC的轉換值用USART輸出可是最大值是1024正確最小值卻不是0該怎麼修改
|
||||
---|---|---|---|---|
新會員
|
使用的是PIC16F1825
發表於: 7/11 16:26
|
|||
|
程式是這樣要把ADC的轉換值用USART輸出可是最大值是1024正確最小值卻不是0該怎麼修改
|
||||
---|---|---|---|---|
新會員
|
#include "mcc_generated_files/system/system.h"
#include #include #define _XTAL_FREQ 8000000 #define BAUDRATE 9600 #define MY_UBRR ((_XTAL_FREQ / 16 / BAUDRATE) - 1) // Function to initialize UART void UART_Init() { SPBRG = MY_UBRR; TXSTAbits.TX9 = 0; // 8-bit transmission TXSTAbits.TXEN = 1; // Enable transmitter TXSTAbits.SYNC = 0; // Asynchronous mode TXSTAbits.BRGH = 1; // High-speed mode RCSTAbits.SPEN = 1; // Enable serial port RCSTAbits.CREN = 1; // Enable continuous reception } // Function to transmit a single character via UART void uart_transmit(char data) { while (!TXSTAbits.TRMT); // Wait for buffer to be empty TXREG = data; // Transmit data } // Function to transmit a string via UART void uart_transmit_string(const char* str) { while (*str != '\0') { uart_transmit(*str++); } } // Function to initialize ADC void initADC(void) { ADCON0 = 0b00001001; // Select AN2 (CHS = 00010), enable ADC (ADON = 1) ADCON1 = 0b10010000; // Right justify result, Fosc/8 as ADC clock ADCON0bits.GO_nDONE = 1; // Start A/D conversion } // Function to read ADC value unsigned int readADC(void) { ADCON0bits.GO_nDONE = 1; // Start conversion while (ADCON0bits.GO_nDONE); // Wait for conversion to complete return ((ADRESH << 8) | ADRESL); // Return 10-bit result } // Function to convert integer to string void itoa(unsigned int value, char* buffer) { sprintf(buffer, "%u", value); } // Main function int main(void) { SYSTEM_Initialize(); UART_Init(); initADC(); char adcBuffer[6]; // Buffer to hold ADC value as string while (1) { // Read ADC value unsigned int adcValue = readADC(); // Convert ADC value to string itoa(adcValue, adcBuffer); // Transmit ADC value uart_transmit_string(adcBuffer); uart_transmit('\n'); // Newline for readability uart_transmit('\r'); __delay_ms(1000); // Delay before next reading } }
發表於: 7/9 10:13
|
|||
|