ошибка a function-definition is not allowed here before '{' token как исправить?

vladOS321
Offline
Зарегистрирован: 30.10.2018

Помогите пожалуйста исравить ошибки в коде

код:

void setup() {
#include "Servo.h"
  const int MaxSensors = 2;                     // Количество сенсоров .
  const int ServoPins[MaxSensors] = {7, 8};     // Пины для подключения серво
  const int RangingPins[MaxSensors] = {3, 2};   // Пины для подключения датчиков SR
  const int ReadingsPerSensor = 5;              //  Значение позиционировани.
  const int TimePerDegree = 9;                  //
  const int MinimumTurnDistance = 3;            // Защита от дребезга , минимальное значение для поворота на 1*
 
  // Variables
 
  Servo ServoList[MaxSensors];
  int sensorReadings[MaxSensors][ReadingsPerSensor];   // Удержание показаний каждого датчика
  int calculatedSenorReadings[MaxSensors];             // Определение расстояния для каждого датчика
  int latestReading = 0;                               //Текущая позиция в массиве для последнего чтения.
  int servoLocations[MaxSensors];                      //Позиционированние серво.
  int SenorClose = 500;                                // Фиксация минимального растояния - отклик .)
  int SensorFar = 14000;                               // Дальнее растояние . Отклик звуковых серсоров PING sensor. (Прохождение звуковой волны.)
  int ServoClose[MaxSensors] = {0, 160};               // Угол поворота первой сервы.
  int ServoFar[MaxSensors] = {70, 110};                // Угол поворота сервы - можно корректировать .
 
  void setup(){
    //Serial.begin(115200);                   // Для отображения данных и настройки убрать // .
    //Serial.println("Begin...");
 
    // Initialize the servo location and move them through a full range of motion so we know they work.
    for (int i = 0; i < MaxSensors; i++) {
      ServoList[i].attach(ServoPins[i]);
      delay(10);
      ServoList[i].write(ServoClose[i]);
      delay(500);
      ServoList[i].write(ServoFar[i]);
      delay(500);
      ServoList[i].detach();
    }
 
    delay(100);
 
  }
 
  void loop() {
    int i, j, oldLocation;
    unsigned long delayTime;
 
    // Loop through each range sensor
    for (i = 0; i < MaxSensors; i++) {    // Get the current sensor's range.     sensorReadings[i][latestReading] = getDistance(i);     // Figure out an averaged/smoothed readings based on this and past data.     calculatedSenorReadings[i] = calculateNewDistace(i);     // Set the servo to the correct angle.     oldLocation = servoLocations[i];     servoLocations[i] = map(calculatedSenorReadings[i], 0, 100, ServoClose[i], ServoFar[i]);     if (latestReading >= ReadingsPerSensor-1){                          // Don't do anything until we have enough data to trend.
      if (abs(servoLocations[i] - oldLocation) >= MinimumTurnDistance) { // Only try to turn it if we have somewhere to go.
        ServoList[i].attach(ServoPins[i]);
        delay(10);
        ServoList[i].write(servoLocations[i]);
        delayTime = (TimePerDegree * (abs(servoLocations[i] - oldLocation)) + 20);  // Set a delay for the next reading so motor noise doesn't interfere with senor readings.
        if (abs(delayTime) > 500) { // If it can't do it in this amount of time       // It's based on how far it has to turn to keep the delay to a minimum, response time at a maximum.
          delayTime = 500;       // we'll get it next time. Keep it responsive.
        }
        delay(delayTime);
        ServoList[i].detach();
      } else {                                          // Otherwise if the reading hasn't changed enough write the old value to
        ServoList[i].attach(ServoPins[i]);            // the servo so that it will hold in place if it's applying pressure.
        delay(10);
        ServoList[i].write(oldLocation);
        delay(50);
        ServoList[i].detach();
        servoLocations[i] = oldLocation;
      }
    }
    delay(20); // Added to fix left sensor misbehavior reported by Rob.
  }
 
  latestReading++; // Increment the reading counter so we know where we're at.
  if (latestReading >= ReadingsPerSensor) { // Make sure we don't record more readings than we have space to hold.
    latestReading = ReadingsPerSensor - 1;
    // Pop the oldest reading off the list.
    for (i = 0; i < MaxSensors; i++) {
      for (j = 0; j < ReadingsPerSensor - 1; j++) {
        sensorReadings[i][j] = sensorReadings[i][j + 1];        // function: calculateNewDistace(sensorNumber: Which sensor's data to process): Calculated distance in 0-100 range. // Apply some averaging and smoothing to the recorded distance readings // to take care of noisy data. int calculateNewDistace(int sensorNumber){   int output = SensorFar;                      // Default value is the furthest distance.   float weightingFactor = 0.5;                 // How fast the reading's importance tapers off in time. (1= no taper, 0 = divide by zero error.)   float flickerFactor = 30;                    // When the change is greater than this, ignore it unless its two in a row. (It's probably noise.)   if (latestReading >= ReadingsPerSensor-1) {  // Only do this if we have a full set of readings to sample.
      }
    }
  }
}
int total = 0;                             // Average them with a weighting.
float currentWeight = 1;                   // New readings count more than older readings.
float percentagePossible = 0;
boolean flickered = false;
for (int i = ReadingsPerSensor - 1; i >= 0 ; i--) { // Check for flicker (This reduces jitter with something right on the threshold.)
  flickered = false;
  if (i == ReadingsPerSensor - 1) {
    if ((abs(sensorReadings[sensorNumber][i]) - abs(sensorReadings[sensorNumber][i - 1]) > flickerFactor) &&
        (abs(sensorReadings[sensorNumber][i - 1]) - abs(sensorReadings[sensorNumber][i - 2]) > flickerFactor)) {
      flickered = true;
    }
  }
  if (flickered == false) {
    total += (sensorReadings[sensorNumber][i] * currentWeight);
    percentagePossible += currentWeight;
    currentWeight *= weightingFactor;
  }
}
output = total / percentagePossible;
}
return output;
}
// function: getDistance
// Take a sensor number (not pin number) and returns an int in the 0-100 range
// 0 = closest, 100= furthest.  (It's a percentage of the distance that the software
//
// Note: Function is designed to be generic so that it can be swapped out for
//       different kinds of ranging sensors.
//       This version of the function is made for Parallax PING))) sensors
//       For more info see http://arduino.cc/en/Tutorial/Ping
int getDistance(int sensorNumber) {
  long duration;   // How long it takes a sonic pulse to reflect back.
  int out;         // The value we send back from the function
 
  // Initialize the sensor and tell it to send out a ping.
  pinMode(RangingPins[sensorNumber], OUTPUT);
  digitalWrite(RangingPins[sensorNumber], LOW);
  delayMicroseconds(2);
  digitalWrite(RangingPins[sensorNumber], HIGH);
  delayMicroseconds(5);
  digitalWrite(RangingPins[sensorNumber], LOW);
 
  // Read the time in milliseconds until the value comes back.
  pinMode(RangingPins[sensorNumber], INPUT);
  duration = pulseIn(RangingPins[sensorNumber], HIGH);
 
  // Trim the data into minimums and maximums and map it to the 0-100 output range.
  duration = constrain(duration, SenorClose, SensorFar);
  out = map(duration,  SenorClose, SensorFar, 0, 100);
  return out;
}//#include
const int MaxSensors = 2;                     // Количество сенсоров .
const int ServoPins[MaxSensors] = {7, 8};     // Пины для подключения серво
const int RangingPins[MaxSensors] = {3, 2};   // Пины для подключения датчиков SR
const int ReadingsPerSensor = 5;              //  Значение позиционировани.
const int TimePerDegree = 9;                  //
const int MinimumTurnDistance = 3;            // Защита от дребезга , минимальное значение для поворота на 1*
 
// Variables
Servo ServoList[MaxSensors];
int sensorReadings[MaxSensors][ReadingsPerSensor];   // Удержание показаний каждого датчика
int calculatedSenorReadings[MaxSensors];             // Определение расстояния для каждого датчика
int latestReading = 0;                               //Текущая позиция в массиве для последнего чтения.
int servoLocations[MaxSensors];                      //Позиционированние серво.
int SenorClose = 500;                                // Фиксация минимального растояния - отклик .)
int SensorFar = 14000;                               // Дальнее растояние . Отклик звуковых серсоров PING sensor. (Прохождение звуковой волны.)
int ServoClose[MaxSensors] = {0, 160};               // Угол поворота первой сервы.
int ServoFar[MaxSensors] = {70, 110};                // Угол поворота сервы - можно корректировать .
 
void setup() {
 
  //Serial.begin(115200);                   // Для отображения данных и настройки убрать // .
  //Serial.println("Begin...");
 
  // Initialize the servo location and move them through a full range of motion so we know they work.
  for (int i = 0; i < MaxSensors; i++) {
    ServoList[i].attach(ServoPins[i]);
    delay(10);
    ServoList[i].write(ServoClose[i]);
    delay(500);
    ServoList[i].write(ServoFar[i]);
    delay(500);
    ServoList[i].detach();
  }
  delay(100);
 
}
 
void loop() {
  int i, j, oldLocation;
  unsigned long delayTime;
 
  // Loop through each range sensor
  for (i = 0; i < MaxSensors; i++) {    // Get the current sensor's range.     sensorReadings[i][latestReading] = getDistance(i);     // Figure out an averaged/smoothed readings based on this and past data.     calculatedSenorReadings[i] = calculateNewDistace(i);     // Set the servo to the correct angle.     oldLocation = servoLocations[i];     servoLocations[i] = map(calculatedSenorReadings[i], 0, 100, ServoClose[i], ServoFar[i]);     if (latestReading >= ReadingsPerSensor-1){                          // Don't do anything until we have enough data to trend.
    if (abs(servoLocations[i] - oldLocation) >= MinimumTurnDistance) { // Only try to turn it if we have somewhere to go.
      ServoList[i].attach(ServoPins[i]);
      delay(10);
      ServoList[i].write(servoLocations[i]);
      delayTime = (TimePerDegree * (abs(servoLocations[i] - oldLocation)) + 20);  // Set a delay for the next reading so motor noise doesn't interfere with senor readings.
      if (abs(delayTime) > 500) { // If it can't do it in this amount of time       // It's based on how far it has to turn to keep the delay to a minimum, response time at a maximum.
        delayTime = 500;       // we'll get it next time. Keep it responsive.
      }
      delay(delayTime);
      ServoList[i].detach();
    } else {                                          // Otherwise if the reading hasn't changed enough write the old value to
      ServoList[i].attach(ServoPins[i]);            // the servo so that it will hold in place if it's applying pressure.
      delay(10);
      ServoList[i].write(oldLocation);
      delay(50);
      ServoList[i].detach();
      servoLocations[i] = oldLocation;
    }
  }
  delay(20); // Added to fix left sensor misbehavior reported by Rob.
}
 
latestReading++; // Increment the reading counter so we know where we're at.
if (latestReading >= ReadingsPerSensor) { // Make sure we don't record more readings than we have space to hold.
  latestReading = ReadingsPerSensor - 1;
  // Pop the oldest reading off the list.
  for (i = 0; i < MaxSensors; i++) {
    for (j = 0; j < ReadingsPerSensor - 1; j++) {
      sensorReadings[i][j] = sensorReadings[i][j + 1];        // function: calculateNewDistace(sensorNumber: Which sensor's data to process): Calculated distance in 0-100 range. // Apply some averaging and smoothing to the recorded distance readings // to take care of noisy data. int calculateNewDistace(int sensorNumber){   int output = SensorFar;                      // Default value is the furthest distance.   float weightingFactor = 0.5;                 // How fast the reading's importance tapers off in time. (1= no taper, 0 = divide by zero error.)   float flickerFactor = 30;                    // When the change is greater than this, ignore it unless its two in a row. (It's probably noise.)   if (latestReading >= ReadingsPerSensor-1) {  // Only do this if we have a full set of readings to sample.
    }
  }
}
}
int total = 0;                             // Average them with a weighting.
float currentWeight = 1;                   // New readings count more than older readings.
float percentagePossible = 0;
boolean flickered = false;
for (int i = ReadingsPerSensor - 1; i >= 0 ; i--) { // Check for flicker (This reduces jitter with something right on the threshold.)
  flickered = false;
  if (i == ReadingsPerSensor - 1) {
    if ((abs(sensorReadings[sensorNumber][i]) - abs(sensorReadings[sensorNumber][i - 1]) > flickerFactor) &&
        (abs(sensorReadings[sensorNumber][i - 1]) - abs(sensorReadings[sensorNumber][i - 2]) > flickerFactor)) {
      flickered = true;
    }
  }
  if (flickered == false) {
    total += (sensorReadings[sensorNumber][i] * currentWeight);
    percentagePossible += currentWeight;
    currentWeight *= weightingFactor;
  }
}
output = total / percentagePossible;
}
return output;
}
// function: getDistance
// Take a sensor number (not pin number) and returns an int in the 0-100 range
// 0 = closest, 100= furthest.  (It's a percentage of the distance that the software
//
// Note: Function is designed to be generic so that it can be swapped out for
//       different kinds of ranging sensors.
//       This version of the function is made for Parallax PING))) sensors
//       For more info see http://arduino.cc/en/Tutorial/Ping
int getDistance(int sensorNumber) {
  long duration;   // How long it takes a sonic pulse to reflect back.
  int out;         // The value we send back from the function
 
  // Initialize the sensor and tell it to send out a ping.
  pinMode(RangingPins[sensorNumber], OUTPUT);
  digitalWrite(RangingPins[sensorNumber], LOW);
  delayMicroseconds(2);
  digitalWrite(RangingPins[sensorNumber], HIGH);
  delayMicroseconds(5);
  digitalWrite(RangingPins[sensorNumber], LOW);
 
  // Read the time in milliseconds until the value comes back.
  pinMode(RangingPins[sensorNumber], INPUT);
  duration = pulseIn(RangingPins[sensorNumber], HIGH);
 
  // Trim the data into minimums and maximums and map it to the 0-100 output range.
  duration = constrain(duration, SenorClose, SensorFar);
  out = map(duration,  SenorClose, SensorFar, 0, 100);
  return out;
}//
  ошибка:
a function-definition is not allowed here before '{' token
код скачан с интернета щас неособо разбираюсь поскольку только вникаю в програмирование ардуино
пожалуйста  помогите 
зарание благодарен
5N62V
Offline
Зарегистрирован: 25.02.2016

1) вставь код как положено

2) выкини нах первую строчку, ее там быть не должно

3) не обольщайся, тебе ёто не поможет, в ётом коде и без ётой ошибки "все прекрасно"

4) не качай всякое гавно из интернета

5) учись сам писать программы, и не надо будет а) искать где взять , и б)просить кого-то исправить

DetSimen
DetSimen аватар
Offline
Зарегистрирован: 25.01.2017

Ошибка в ХЗ какой строке, нумеров нет

DetSimen
DetSimen аватар
Offline
Зарегистрирован: 25.01.2017

И этта, помигай сначала светлодиодиком.  ТОлько сопсными ручками напиши, а не с авнопросторов качай.

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Так, главная ошибка в том и есть, что

vladOS321 пишет:

код скачан с интернета щас неособо разбираюсь 

Сначала надо её исправить, а остальное приложится.

nik182
Offline
Зарегистрирован: 04.05.2015

Ошибка в том, что скачено с интернета несколко раз и всё смешано в одну кучу. Однократное скачивание часто проходит.

forfrends
Offline
Зарегистрирован: 24.02.2015

Интересно, а что это за устройство должно быть?