I'm doing a school project, and i have tested the code with arduino uno and nano (atmega328p) and it worked perfectly, but the code don't work with arduino mega2560 wich i will need to use because of memory issue, here is the code for arduino nano/uno that i used:
#define IRpin 2
#define MAXPULSE 65000
#define RESOLUTION 20
int IRledPin = 12;
bool receptor = false;
uint16_t pulses[250][2];
uint8_t currentpulse = 0;
uint8_t pulse_size = 0;
void setup()
{
pinMode(IRledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
char comando = Serial.read();
if (comando == '0')
{
receptor = false;
Serial.write('0');
//Serial.println("Do nothing...");
}
if (comando == '1')
{
receptor = false;
Serial.write('1');
//Serial.println("Now sending...");
SendChannelUpCode();
delay(50);
}
if (comando == '2')
{
receptor = true;
Serial.write('2');
//Serial.println("Now receiving...");
}
}
if (receptor == true)
{
receive();
}
}
//==============================================================
void receive(void)
{
uint16_t highpulse, lowpulse;
highpulse = lowpulse = 0;
while (IRpin_PIN & _BV(IRpin))
{
highpulse++;
delayMicroseconds(RESOLUTION);
if ((highpulse >= MAXPULSE) && (currentpulse != 0))
{
printpulses();
pulse_size = currentpulse;
currentpulse = 0;
receptor = false;
Serial.write('d');
return;
}
}
pulses[currentpulse][0] = highpulse;
while (!(IRpin_PIN & _BV(IRpin)))
{
lowpulse++;
delayMicroseconds(RESOLUTION);
if ((lowpulse >= MAXPULSE) && (currentpulse != 0))
{
printpulses();
pulse_size = currentpulse;
currentpulse = 0;
receptor = false;
Serial.write('d');
return;
}
}
pulses[currentpulse][1] = lowpulse;
currentpulse++;
}
//==============================================================
void printpulses(void)
{
Serial.println(currentpulse);
for (uint8_t i = 0; i < currentpulse; i++)
{
Serial.print("delay: ");
Serial.println(pulses[i][0] * RESOLUTION, DEC);
Serial.print("pulse: ");
Serial.println(pulses[i][1] * RESOLUTION, DEC);
}
pulse_size = currentpulse;
}
//==============================================================
void pulseIR(long microsecs)
{
cli();
while (microsecs > 0)
{
digitalWrite(IRledPin, HIGH);
delayMicroseconds(10);
digitalWrite(IRledPin, LOW);
delayMicroseconds(10);
microsecs -= 26;
}
sei();
}
//==============================================================
void SendChannelUpCode(void)
{
for (uint8_t i = 0; i < pulse_size; i++)
{
delayMicroseconds(pulses[i][0] * RESOLUTION);
pulseIR(pulses[i][1] * RESOLUTION);
}
Serial.write('d');
}
note: I'm using on pin 2 a IR sensor, VS1838, and on pin 12 an ir led. To adapt for mega i've tried to switch PIND to one of the GPIOs of the microcontroller (PINA, PING, PIND, PINE...) and i also have changed the pin on #define IRpin, but it didn't work.