как бобедить искажение данных в EEPROM?

maximooos
Offline
Зарегистрирован: 15.09.2016

Немного дополнил стандартный пример работы с IR библиотекой.
Программа принимает и декодирует сигналы ик пультов, сохраняет в оперативную память и по нажатию кнопки отправляет эту команду через ик диод.
Я хочу сделать так чтоб принятая команда сохранялась в EEPROM и была доступна после перезагрузки ардуины.
Сейчас то что у меня получилось читает данные из памяти, в мониторе порта печатает правильные данные, но отправляемая команда уже искажена и не распознается устройством назначения.
Если принять ик команду с пульта она записывается в переменную CodeValue и в указаную ячейку eeprom. В таком случае команда распознается. После перезагрузки ардуины команда чичитается из указаной ячейки в переменную CodeValue и уже не распознается.
С переменной CodeType делается все тоже самое, но с ней проблем нет.
В чем может быть моя ошибка?
Скетч сейчас выложу в следующем сообщении.

maximooos
Offline
Зарегистрирован: 15.09.2016
#include <EEPROM.h>

/*
 * IRrecord: record and play back IR signals as a minimal 
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * An IR LED must be connected to the output PWM pin 3.
 * A button must be connected to the input BUTTON_PIN; this is the
 * send button.
 * A visible LED can be connected to STATUS_PIN to provide status.
 *
 * The logic is:
 * If the button is pressed, send the IR code.
 * If an IR code is received, record it.
 *
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>
// Дополнительные функции для перевода long -> int и назад.
#define makeLong(hi, low)  (((long) hi) << 16 | (low))
#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

// адрес, по которому сохраняются команды в постоянной памяти. Используется 4 байта. Указывается начальный адрес.
int adr_1 = 0;
int adr_2 = 4;
int adr_3 = 8;

int place = adr_1;

int RECV_PIN = 11;
int BUTTON_PIN = 9;
int STATUS_PIN = 13;


IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;


byte key(){  
  int val = analogRead(0);
   if (val < 50) return 1;
    else if (val < 150) return 2;
    else if (val < 350) return 5;
    else if (val < 500) return 4;
    else if (val < 800) return 3;
    else return 0;  
}


void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(BUTTON_PIN, INPUT);
  pinMode(STATUS_PIN, OUTPUT);
}

// Storage for the recorded code
int codeType = loadFromEeprom (place = adr_1); // The type of code
unsigned long codeValue = loadFromEeprom (place = adr_2); // The code value if not raw
unsigned int rawCodes[RAWBUF]; // The durations if raw
int codeLen; // The length of the code
int toggle = 0; // The RC5/6 toggle state



// Stores the code for later playback
// Most of this code is just logging
void storeCode(decode_results *results) {
  codeType = results->decode_type;
  int count = results->rawlen;
  if (codeType == UNKNOWN) {

    codeType = SAMSUNG;
   codeValue = 3772799143; 
    
    Serial.println("Received unknown code, saving as raw");
    codeLen = results->rawlen - 1;
    // To store raw codes:
    // Drop first value (gap)
    // Convert from ticks to microseconds
    // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
    for (int i = 1; i <= codeLen; i++) {
      if (i % 2) {
        // Mark
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
        Serial.print(" m");
      } 
      else {
        // Space
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
      //  place = adr_2; //указываем ячейку для хранения codeValue
     // saveToEeproma(rawCodes, place); // сoхранем 
        
        Serial.print(" s");
        
        
        
      }
      Serial.print(rawCodes[i - 1], DEC);
    }
    Serial.println("");
    
  }
  else {
    if (codeType == NEC) {
      Serial.print("Received NEC: ");
       place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
      place = adr_3;
      
      if (results->value == REPEAT) {
        // Don't record a NEC repeat value as that's useless.
        Serial.println("repeat; ignoring.");
        return;
      }
      
    } 
    
   
    
    else if (codeType == SONY) {
      place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
      
      Serial.print("Received SONY: ");
    } 
    else if (codeType == RC5) {
      Serial.print("Received RC5: ");
       place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
    } 
    else if (codeType == RC6) {
      Serial.print("Received RC6: ");
       place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
    } 
    
     else if (codeType == JVC) {
      Serial.print("Received JVC: ");
       place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
      place = adr_3;
      
      if (results->value == REPEAT) {
        // Don't record a JVC repeat value as that's useless.
        Serial.println("repeat; ignoring.");
        return;
      }
   }
    
     else if (codeType == SAMSUNG) {
      Serial.print("Received SAMSUNG: ");
       place = adr_1; //указываем чейку для хранения значения codeType
      saveToEeproma(codeType, place); //сохранем codeType
      place = adr_2; //указываем ячейку для хранения codeValue
      saveToEeproma(codeValue, place); // сoхранем 
           
      if (results->value == REPEAT) {
        // Don't record a SAMSUNG repeat value as that's useless.
        Serial.println("repeat; ignoring.");
        return;
      }
   }
    
    else {
      Serial.print("Unexpected codeType ");
      Serial.print(codeType, DEC);
      Serial.println("");
    }
    Serial.println(results->value, HEX);
    codeValue = results->value;
    codeLen = results->bits;
  }
}

void sendCode(int repeat) {
  if (codeType == NEC) {
    if (repeat) {
      irsend.sendNEC(REPEAT, codeLen);
      Serial.println("Sent NEC repeat");
    } 
    else {
      irsend.sendNEC(codeValue, codeLen);
      Serial.print("Sent NEC ");
      Serial.println(codeValue, HEX);
    }
  } 
  
  else if (codeType == SONY) {
    irsend.sendSony(codeValue, codeLen);
    Serial.print("Sent Sony ");
    Serial.println(codeValue, HEX);
  } 
  
   else if (codeType == JVC) {
    irsend.sendJVC(codeValue, codeLen);
    Serial.print("Sent JVC ");
    Serial.println(codeValue, HEX);
  } 
  
   else if (codeType == SAMSUNG) {
    irsend.sendSAMSUNG(codeValue, codeLen);
    Serial.print("Sent SAMSUNG ");
    Serial.println(codeValue, DEC);
  } 
  else if (codeType == RC5 || codeType == RC6) {
    if (!repeat) {
      // Flip the toggle bit for a new button press
      toggle = 1 - toggle;
    }
    // Put the toggle bit into the code to send
    codeValue = codeValue & ~(1 << (codeLen - 1));
    codeValue = codeValue | (toggle << (codeLen - 1));
    if (codeType == RC5) {
      Serial.print("Sent RC5 ");
      Serial.println(codeValue, HEX);
      irsend.sendRC5(codeValue, codeLen);
    } 
    else {
      irsend.sendRC6(codeValue, codeLen);
      Serial.print("Sent RC6 ");
      Serial.println(codeValue, HEX);
    }
  } 
  else if (codeType == UNKNOWN /* i.e. raw */) {
    // Assume 38 KHz
    irsend.sendRaw(rawCodes, codeLen, 38);
    Serial.println("Sent raw");
  }
}

int lastButtonState;

void loop() {
  // If button pressed, send the code.
  int buttonState = digitalRead(BUTTON_PIN);
  if (lastButtonState == HIGH && buttonState == LOW) {
    Serial.println("Released");
    irrecv.enableIRIn(); // Re-enable receiver
  }

  if (buttonState) {
    Serial.println("Pressed, sending");
    digitalWrite(STATUS_PIN, HIGH);
    sendCode(lastButtonState == buttonState);
    digitalWrite(STATUS_PIN, LOW);
    delay(50); // Wait a bit between retransmissions
  } 
  else if (irrecv.decode(&results)) {
    digitalWrite(STATUS_PIN, HIGH);
    storeCode(&results);
    irrecv.resume(); // resume receiver
    digitalWrite(STATUS_PIN, LOW);
  }
  lastButtonState = buttonState;
}






// Процедура сохранения 4-байтного целого в постоянную память
void saveToEeproma(long value, int address) {
  int data[2];
  data[0] = highWord(value);
  data[1] = lowWord(value);
  for (int x = 0; x < 2; x++){
    EEPROM.write(place + x * 2, highByte(data[x]));
    EEPROM.write(place + x * 2 + 1, lowByte(data[x]));
  }


 
  Serial.print("Saved to Eeprom value = ");
  Serial.print(value);
  Serial.print(" address = ");
  Serial.println(address);
  
}

// Процедура чтения 4-байтного целого из постоянной памяти
long loadFromEeprom(int address) {
  byte data[4];
  for (int x = 0; x < 4; x++){
    data[x] = EEPROM.read(place + x);
  }
  int high = word(data[0], data[1]);
  int low = word(data[2], data[3]);
  long result = makeLong(high, low);
  
 

  Serial.print("Loaded from Eeprom value = ");
  Serial.println(codeType);
  //Serial.println(buttonb);
  //Serial.println(buttonc);


  return result;
}

 

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

Вы запутались в адресах. Вы пишете в одни адрес, а читаете из других.

Посмотрите на строки 64-65. 

1. Зачем это делать в глобальном пространстве?
2. Зачем такие хитрожопости с параметрами. Вы потом это place везде используете, Вы точно уверены, что знаете чему она в итоге равна?

Ну и кроме того, совсем непоянтно зачем такие сложные навороты в функциях стр. 280-317. На вскидку, там вроде нормально, но зачем столько наворпчавть там, где это делается в одну строку? Ошибок насобирать?

Убирте, хитрожпости, будье проще и всё получится.

maximooos
Offline
Зарегистрирован: 15.09.2016

А как без перемеменной place загонять адреса в алгоритм сохранения и чтения?

maximooos
Offline
Зарегистрирован: 15.09.2016

Да и в мониторе порта после чтения печатается значение эдентичное принятому с пульта. Может оно видоизменяется в процесе записи/ чтения?

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

Ответьте на вопрос (себе, мне не надо) что делает переменная place вот в этих конструкциях?

int codeType = loadFromEeprom (place = adr_1); // The type of code
unsigned long codeValue = loadFromEeprom (place = adr_2); // The code value if not raw

А про печать, так Вы же бред какой-то печатаете.

Ну, смотрите, Вы прочитали что-то там и поместили в переменную result (стока 306). А печатаете зачем-то переменную codetype. Зачем? Чуть позже, после выхода из функции, codetype получит тоже значение, что сейчас в result, но это быдет после выхода. Вы же печатаете её внутри функции.

maximooos
Offline
Зарегистрирован: 15.09.2016

Переменнач place нужна для зопоминания следующей кнопки в другие адреса. Я это убрал из кода, чтоб не нагружать чтением того кто откликнется.

maximooos
Offline
Зарегистрирован: 15.09.2016

Да и не описывать же заново процедуру чтения и записи для каждого адреса. Адрес проще хранить в переменной, которая меняется в зависимоти от того что именно мы хотим сохранить. Если знаете способ проще подскажите.

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

Блин, Вы вопрос слышите? Что она делает конкретно в тех двух строках, которы я привёл. Вы можете ответить?

Ну, а про печать Вы всё поняли, да? Вы уж что прчитали, то и печатайте. Или Вы не понимаете, что прочитали? Код сами писали?

maximooos
Offline
Зарегистрирован: 15.09.2016

Сам писал. Про печать понял. В этих двух строка в эту переменную помещается адрес по которому хранится тип кода, а затем адрес в котором хранится значение кода.

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

Ну, слава Богу.

А теперь смотрим на две функции в строках 280-317

Ответьте на вопрос, для чего у них параметр address, если внутри он никак не используется?

maximooos
Offline
Зарегистрирован: 15.09.2016

Остались мусором .проблема в них?

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

Нет, проблема в чрезмерном, ненужном усложнении программы. Строки 280-317 можно заменить на 2 (прописью "Две") строки. Все строки, начинающиеся с "place =" можно и нужно выбросить. Программа сократится вдводе и, главное, упросттится и Вы перестанете в ней путаться.

maximooos
Offline
Зарегистрирован: 15.09.2016

Подскажите мне эти две строки пожалуйста. Буду примного благодарен

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015
void saveToEeproma(long value, int address) { EEPROM.put(address, value); }
unsigned long loadFromEeprom(int address) { unsigned long r; EEPROM.get(address, r); return r; }

Как видите, никакая- place там не используется, поэтому смело её выбрасывайте и пользуйтесь параметрами.

maximooos
Offline
Зарегистрирован: 15.09.2016

А как менять значение параметра adress?

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

Просто передавать значение.

saveToEeproma(0);

или

int kaka = 4;
saveToEeproma(kaka)

maximooos
Offline
Зарегистрирован: 15.09.2016

Спасибо. Сейчас испытаю.

maximooos
Offline
Зарегистрирован: 15.09.2016

я бесконечно вам благодарен. у меня все получилось.

valera678
Offline
Зарегистрирован: 04.11.2016

maximooos,можно сюда окончательный ,исправленНый код,пожалуйста?

UPD by Yarik.Yar, 26.12.2016, 17:25 - Ещё бы капсом написали...Не используйте жирный шрифт без надобности и следите за грамматикой, господа.

maximooos
Offline
Зарегистрирован: 15.09.2016

да пожалуйста.

но проблема все таки осталась.

в мониторе порта после перезагрузки ардуины печатаются правильные значения, но телек на них не реагирует.

#include <EEPROM.h>

/*
 * IRrecord: record and play back IR signals as a minimal 
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * An IR LED must be connected to the output PWM pin 3.
 * A button must be connected to the input BUTTON_PIN; this is the
 * send button.
 * A visible LED can be connected to STATUS_PIN to provide status.
 *
 * The logic is:
 * If the button is pressed, send the IR code.
 * If an IR code is received, record it.
 *
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;
int BUTTON_PIN = 12;
int STATUS_PIN = 13;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(BUTTON_PIN, INPUT);
  pinMode(STATUS_PIN, OUTPUT);
}

// Storage for the recorded code
int codeType = loadFromEeprom (0); // The type of code

unsigned long codeValue = loadFromEeprom (4); // The code value if not raw

unsigned int rawCodes[RAWBUF]; // The durations if raw
int codeLen; // The length of the code
int toggle = 0; // The RC5/6 toggle state

// Stores the code for later playback
// Most of this code is just logging
void storeCode(decode_results *results) {
  codeType = results->decode_type;
  int count = results->rawlen;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    codeLen = results->rawlen - 1;
    // To store raw codes:
    // Drop first value (gap)
    // Convert from ticks to microseconds
    // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
    for (int i = 1; i <= codeLen; i++) {
      if (i % 2) {
        // Mark
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
        Serial.print(" m");
      } 
      else {
        // Space
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
        Serial.print(" s");
      }
      Serial.print(rawCodes[i - 1], DEC);
    }
    Serial.println("");
  }
  else {
    if (codeType == NEC) {
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);      
      Serial.print("Received NEC: ");
      if (results->value == REPEAT) {
        // Don't record a NEC repeat value as that's useless.
        Serial.println("repeat; ignoring.");
        return;
      }
    } 
    else if (codeType == SONY) {
      Serial.print("Received SONY: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
    } 
  
    else if (codeType == RC5) {
      Serial.print("Received RC5: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
    } 
    else if (codeType == RC6) {
      Serial.print("Received RC6: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
    } 
    else {
      Serial.print("Unexpected codeType ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
      Serial.print(codeType, DEC);
      Serial.println("");
    }
    Serial.println(results->value, HEX);
    codeValue = results->value;
    codeLen = results->bits;
  }
}

void sendCode(int repeat) {
  if (codeType == NEC) {
    if (repeat) {
      irsend.sendNEC(REPEAT, codeLen);
      Serial.println("Sent NEC repeat");
    } 
    else {
      irsend.sendNEC(codeValue, codeLen);
      Serial.print("Sent NEC ");
      Serial.println(codeValue, HEX);
    }
  } 
  else if (codeType == SONY) {
    irsend.sendSony(codeValue, codeLen);
    Serial.print("Sent Sony ");
    Serial.println(codeValue, HEX);
  } 
  else if (codeType == RC5 || codeType == RC6) {
    if (!repeat) {
      // Flip the toggle bit for a new button press
      toggle = 1 - toggle;
    }
    // Put the toggle bit into the code to send
    codeValue = codeValue & ~(1 << (codeLen - 1));
    codeValue = codeValue | (toggle << (codeLen - 1));
    if (codeType == RC5) {
      Serial.print("Sent RC5 ");
      Serial.println(codeValue, HEX);
      irsend.sendRC5(codeValue, codeLen);
    } 
    else {
      irsend.sendRC6(codeValue, codeLen);
      Serial.print("Sent RC6 ");
      Serial.println(codeValue, HEX);
    }
  } 
  else if (codeType == UNKNOWN /* i.e. raw */) {
    // Assume 38 KHz
    irsend.sendRaw(rawCodes, codeLen, 38);
    Serial.println("Sent raw");
  }
}

int lastButtonState;

void loop() {
  // If button pressed, send the code.
  int buttonState = digitalRead(BUTTON_PIN);
  if (lastButtonState == HIGH && buttonState == LOW) {
    Serial.println("Released");
    irrecv.enableIRIn(); // Re-enable receiver
  }

  if (buttonState) {
    Serial.println("Pressed, sending");
    Serial.println(codeType);
    Serial.println(codeValue);
    digitalWrite(STATUS_PIN, HIGH);
    sendCode(lastButtonState == buttonState);
    digitalWrite(STATUS_PIN, LOW);
    delay(50); // Wait a bit between retransmissions
  } 
  else if (irrecv.decode(&results)) {
    digitalWrite(STATUS_PIN, HIGH);
    storeCode(&results);
    irrecv.resume(); // resume receiver
    digitalWrite(STATUS_PIN, LOW);
  }
  lastButtonState = buttonState;
}

void saveToEeproma(long value, int address) { EEPROM.put(address, value); }
unsigned long loadFromEeprom(int address) { unsigned long r; EEPROM.get(address, r); return r; }

 

maximooos
Offline
Зарегистрирован: 15.09.2016

пишет Sent NEC 20DF40BF

при этом если в строке 40 написать
int codeType = NEC; 
а в строке 42
unsigned long codeValue = 551502015; что в десятиричной системе значит то же самое
 
т.е. в ручную указать то же значение, что читается из EEPROM, телевизор LG Smart tv послушно добавляет громкость..
maximooos
Offline
Зарегистрирован: 15.09.2016

все. разобрался. нужно сохранять еще и длину кода.

строка 45

вот рабочий код

#include <EEPROM.h>

/*
 * IRrecord: record and play back IR signals as a minimal 
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * An IR LED must be connected to the output PWM pin 3.
 * A button must be connected to the input BUTTON_PIN; this is the
 * send button.
 * A visible LED can be connected to STATUS_PIN to provide status.
 *
 * The logic is:
 * If the button is pressed, send the IR code.
 * If an IR code is received, record it.
 *
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;
int BUTTON_PIN = 12;
int STATUS_PIN = 13;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(BUTTON_PIN, INPUT);
  pinMode(STATUS_PIN, OUTPUT);
}

// Storage for the recorded code
int codeType = loadFromEeprom (0); // The type of code

unsigned long codeValue = loadFromEeprom (4); // The code value if not raw

unsigned int rawCodes[RAWBUF]; // The durations if raw
int codeLen = loadFromEeprom (8); // The length of the code
int toggle = 0; // The RC5/6 toggle state

// Stores the code for later playback
// Most of this code is just logging
void storeCode(decode_results *results) {
  codeType = results->decode_type;
  int count = results->rawlen;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    codeLen = results->rawlen - 1;
    // To store raw codes:
    // Drop first value (gap)
    // Convert from ticks to microseconds
    // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
    for (int i = 1; i <= codeLen; i++) {
      if (i % 2) {
        // Mark
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
        Serial.print(" m");
      } 
      else {
        // Space
        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
        Serial.print(" s");
      }
      Serial.print(rawCodes[i - 1], DEC);
    }
    Serial.println("");
  }
  else {
    if (codeType == NEC) {
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
      saveToEeproma(codeLen, 8);      
      Serial.print("Received NEC: ");
      if (results->value == REPEAT) {
        // Don't record a NEC repeat value as that's useless.
        Serial.println("repeat; ignoring.");
        return;
      }
    } 
    else if (codeType == SONY) {
      Serial.print("Received SONY: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
      saveToEeproma(codeLen, 8);
    } 
  
    else if (codeType == RC5) {
      Serial.print("Received RC5: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
    } 
    else if (codeType == RC6) {
      Serial.print("Received RC6: ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
      saveToEeproma(codeLen, 8);
    } 
    else {
      Serial.print("Unexpected codeType ");
      saveToEeproma(codeType, 0);
      saveToEeproma(codeValue, 4);
      saveToEeproma(codeLen, 8);
      Serial.print(codeType, DEC);
      Serial.println("");
    }
    Serial.println(results->value, HEX);
    codeValue = results->value;
    codeLen = results->bits;
  }
}

void sendCode(int repeat) {
  if (codeType == NEC) {
    if (repeat) {
      irsend.sendNEC(REPEAT, codeLen);
      Serial.println("Sent NEC repeat");
    } 
    else {
      irsend.sendNEC(codeValue, codeLen);
      Serial.print("Sent NEC ");
      Serial.println(codeValue, HEX);
    }
  } 
  else if (codeType == SONY) {
    irsend.sendSony(codeValue, codeLen);
    Serial.print("Sent Sony ");
    Serial.println(codeValue, HEX);
  } 
  else if (codeType == RC5 || codeType == RC6) {
    if (!repeat) {
      // Flip the toggle bit for a new button press
      toggle = 1 - toggle;
    }
    // Put the toggle bit into the code to send
    codeValue = codeValue & ~(1 << (codeLen - 1));
    codeValue = codeValue | (toggle << (codeLen - 1));
    if (codeType == RC5) {
      Serial.print("Sent RC5 ");
      Serial.println(codeValue, HEX);
      irsend.sendRC5(codeValue, codeLen);
    } 
    else {
      irsend.sendRC6(codeValue, codeLen);
      Serial.print("Sent RC6 ");
      Serial.println(codeValue, HEX);
    }
  } 
  else if (codeType == UNKNOWN /* i.e. raw */) {
    // Assume 38 KHz
    irsend.sendRaw(rawCodes, codeLen, 38);
    Serial.println("Sent raw");
  }
}

int lastButtonState;

void loop() {
  // If button pressed, send the code.
  int buttonState = digitalRead(BUTTON_PIN);
  if (lastButtonState == HIGH && buttonState == LOW) {
    Serial.println("Released");
    irrecv.enableIRIn(); // Re-enable receiver
  }

  if (buttonState) {
    Serial.println("Pressed, sending");
    Serial.println(codeType);
    Serial.println(codeValue);
    digitalWrite(STATUS_PIN, HIGH);
    sendCode(lastButtonState == buttonState);
    digitalWrite(STATUS_PIN, LOW);
    delay(50); // Wait a bit between retransmissions
  } 
  else if (irrecv.decode(&results)) {
    digitalWrite(STATUS_PIN, HIGH);
    storeCode(&results);
    irrecv.resume(); // resume receiver
    digitalWrite(STATUS_PIN, LOW);
  }
  lastButtonState = buttonState;
}

void saveToEeproma(long value, int address) { EEPROM.put(address, value); }
unsigned long loadFromEeprom(int address) { unsigned long r; EEPROM.get(address, r); return r; }

 

maximooos
Offline
Зарегистрирован: 15.09.2016

та версия кода, что я выкладывал в начале тоже работает, если добавить в ней сохранение/чтение codeLen