C 程序错误预期数字常量前的分号

C program error expected semicolon before numeric constant

我正在尝试为 avr 和超时编译 C 程序我遇到了一个奇怪的编译错误。该程序使用 Ateml studio 为 atmega8 微控制器编写

expected ';' before numeric constant

这是我的程序

/*
 * LDR_ADC_ATM8.c
 *
 * Created: 11/16/2015 9:25:39 AM
 *  Author: Semira
 */ 


#include <avr/io.h>
#include <util/delay.h>

// Standard Input/Output functions
#include <stdio.h>
//////////////////////////////////
//Programmer Setting
#define relay PORTB.1
#define ON 1
#define OFF 0
////////////////////////////////
//User Setting
#define Dark 800
#define Light 600
/////////////////////////////////
#define ADC_VREF_TYPE 0x00
// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{

    ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
    // Delay needed ADC input voltage
    delay_us(10);
    // Start the AD conversion
    ADCSRA|=0x40;
    // Wait for the AD conversion to complete
    while ((ADCSRA & 0x10)==0);
    ADCSRA|=0x10;
    return ADCW;
}
// Declare your global variables here
unsigned int adc=0;
int main(void)
{
    // Declare your local variables here
    // Input/Output Ports initialization
    // Port B initialization
    // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=Out
    // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=0

    PORTB=0x00;
    DDRB=0x02;
    // USART initialization
    // Communication Parameters: 8 Data, 1 Stop, No Parity
    // USART Receiver: On
    // USART Transmitter: On
    // USART Mode: Asynchronous
    // USART Baud Rate: 9600
    UCSRA=0x00;
    UCSRB=0x18;
    UCSRC=0x86;
    UBRRH=0x00;
    UBRRL=0x33;
    // ADC initialization
    // ADC Clock frequency: 62.500 kHz
    // ADC Voltage Reference: AREF pin
    ADMUX=ADC_VREF_TYPE & 0xff;
    ADCSRA=0x87;
    delay_ms(1000);
    while (1)
    {
        // Place your code here
        adc=read_adc(5);
        delay_ms(100);
        delay_ms(500);
        if(adc>Dark)// if darkness
        {
            delay_ms(10);
            relay=ON;
        }
        if(adc<Light)// if day light
        {
            delay_ms(10);
            relay=OFF;

        }
    }

}   

我该如何解决这个错误?

PORTB=0x00;
DDRB=0x02;
etc

这些需要类型。如:

uint8_t PORTB=0x00;
uint8_t DDRB=0x02;

或适合您应用的任何内容。

Atmel Studio 使用 AVRGCC,因此 PORTB.1 不是有效语法。要切换端口上的特定位:

PORTB |= (1 << PB1);   // set bit 1 on PORTB
PORTB &= ~(1 << PB1);  // clear bit 1 on PORTB

您可以使用作为 avr-libc 定义并执行左移的 _BV 宏。

#DEFINE _BV(bit) (1 << bit)

所以你也可以这样写

PORTB |= _BV(PB1);

为了简化事情,您可以定义辅助宏,这很常见:

#define SETBIT(reg, bit) reg |= 1 << bit
#define CLRBIT(reg, bit) reg &= ~(1 << bit)

就个人而言,我可能会写一个函数:

void SetRelay(bool on) {
    if (on) {
        PORTB |= (1 << PB1);
    } else {
        PORTB &= ~(1 << PB1);
    }
}