I could not make IRsend from the IRremote library to work - arduino

Hello i am using an arduino mkr1000 so send and IR signal using the IRremote library for mkr1000 IRremote library. I am having problems with IRsend.
First i used the IRdump example to get the data from my remote button. When i finished this i tried the IRsend example but it seems to be not working.
I temporarily replaced with a ordinary LED to show if it is really blinking, but it is not. I have tested the both the ordinary LED and IR LED that they worked.
I also think that i have wired the LED correctly according to the example
PIN 3 -> LED -> Resistor -> Ground
My circuit was further confirmed correct when i upload a sketch that makes it blink.
Basically i am trying to send a NEC 32bit signal, 0x2FD807F
but i guess they were not able to finish the library of send for mkr1000???
in this post a comment was made with a code but did not really have any detail on how to use it.
here is where i am currently at
int IR_S = 3;
void setup()
{
pinMode(IR_S,OUTPUT);
}
void loop() {
IR_Sendcode(0x2FD807F);
delay(1000);
}
void IR_Send38KHZ(int x,int bit) //Generate 38KHZ IR pulse
{
for(int i=0;i<x;i++)//15=386US
{
if(bit==1)
{
digitalWrite(IR_S,1);
delayMicroseconds(9);
digitalWrite(IR_S,0);
delayMicroseconds(9);
}
else
{
digitalWrite(IR_S,0);
delayMicroseconds(20);
}
}
}
void IR_Sendcode(uint8_t data) // Send the data
{
for(int i=0;i<8;i++)
{
if((data&0x01)==0x01)
{
IR_Send38KHZ(23,1);
IR_Send38KHZ(64,0);
}
else
{
IR_Send38KHZ(23,1);
IR_Send38KHZ(21,0);
}
data=data>>1;
}
}

I while i was waiting for replies i created my own code. I have finished and tested it. It should theoretically work on any arduino.
/*
This is a code for NEC Infrared Transmission Protocol Transmitter
NEC specifications are
~ Carrier Frequency is 38kHz
* Logical '0' – a 562.5µs pulse burst followed by a 562.5µs space, with a total transmit time of 1.125ms
* Logical '1' – a 562.5µs pulse burst followed by a 1.6875ms space, with a total transmit time of 2.25ms
- a 9ms leading pulse burst (16 times the pulse burst length used for a logical data bit)
- a 4.5ms space
- the 8-bit address for the receiving device
- the 8-bit logical inverse of the address
- the 8-bit command
- the 8-bit logical inverse of the command
- a final 562.5µs pulse burst to signify the end of message transmission.
Example,
If the code recieved from the data dump from the IRremote library is 0x2FD807F
-0x02 is address
-0xFD is the inverse address
-0x80 is the command
-0x7F is the inverse command
THIS PROGRAM IS A BLOCKING PROGRAM
*/
#define IR 3
#define CarrierFreqInterval 11
void setup() {
pinMode(IR, OUTPUT);
digitalWrite(IR, LOW);
}
void loop() {
// unsigned long start = micros();
transmit(0x02FD807F);
// unsigned long ends = micros();
// unsigned long delta = ends - start;
// Serial.println(delta);
delay(500);
}
void transmit(uint32_t data) {
//Function for transmiting the data
uint32_t bitcount = 0x80000000;
// 9ms pulse burst
for (int i = 0; i < 355; i++) {
digitalWrite(IR, HIGH);
delayMicroseconds(CarrierFreqInterval);
digitalWrite(IR, LOW);
delayMicroseconds(CarrierFreqInterval);
}
// 4.5ms space
delayMicroseconds(4500);
//8bit address,adress inverse,command,command inverse
while ( bitcount != 0b0) {
if ((data & bitcount) == bitcount) {
pulseHIGH();
}
else {
pulseLOW();
}
bitcount = bitcount >> 1;
}
//final pulse burst
for (int i = 0; i < 21; i++) {
digitalWrite(IR, HIGH);
delayMicroseconds(CarrierFreqInterval);
digitalWrite(IR, LOW);
delayMicroseconds(CarrierFreqInterval);
}
}
void pulseHIGH() {
// Pulse 38KHz good for a LOGIC '1'
for (int i = 0; i < 21; i++) {
digitalWrite(IR, HIGH);
delayMicroseconds(CarrierFreqInterval);
digitalWrite(IR, LOW);
delayMicroseconds(CarrierFreqInterval);
}
delay(1);
delayMicroseconds(687.5);
}
void pulseLOW() {
// Pulse 38KHz good for a LOGIC '0'
for (int i = 0; i < 21; i++) {
digitalWrite(IR, HIGH);
delayMicroseconds(CarrierFreqInterval);
digitalWrite(IR, LOW);
delayMicroseconds(CarrierFreqInterval);
}
delayMicroseconds(562.5);
}

Related

Arduino send bad signal to interrupt pin

I have connected coin hopper and coin acceptor to one arduino uno, coin acceptor connected to pin 2, coin hopper to pin 3 - sensor and pin 7 - relay. When coin hopper switch relay, it is executing coininterrupt
for coin hopper I am using this script link
coin acceptor script: link
I need this 2 scripts working on 1 arduino
my code:
#define SENSOR 3
#define RELAY 7
#define ACCEPTOR 2
volatile boolean insert = false;
int pulse=0,count;
char sen;
int temp=0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR,INPUT_PULLUP);
pinMode(RELAY,OUTPUT);
sen=digitalRead(SENSOR);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(ACCEPTOR), coinInterrupt, RISING);
}
void loop()
{
if (insert) {
insert = false;
Serial.println("coin");
delay(1000);
}
if(Serial.available())
{
timer=millis();
// temp is amount to dispense send to arduino
temp=Serial.parseInt();
if(temp>0){
digitalWrite(RELAY,LOW);}
}
sen=(sen<<1)|digitalRead(SENSOR);
// if hopper sensor read drop coin
if(sen==1)
{
timer=millis();
pulse++;
sen&=0x03;
Serial.println("out 1");
//if dispensed coins equal with coins to dispense stop engine
if(pulse==temp)
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
// if amount dispensed is not equal with amount to dispense and engine running, stop
if((digitalRead(RELAY)==LOW)&(millis()-timer>2000))
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
void coinInterrupt() {
insert = true;
}
I was trying to change pins (arduino uno support interrupts on pin 2 and 3 only) but problem still appears so I guess there is issue in the code
your sketch does not run in this state :
first fix errors :
declare insert as volatile
remove cpulse (not used anywhere)
change 'if()' to (I suppose) 'if (insert) ....'
remove stuff with 'sen' var : simply use if(digitalRead(SENSOR)) or if(!digitalRead(SENSOR))
except if you need to store relay state.
use logical operators like || or && unless you really need bitwise operations
example of result sketch :
#define SENSOR 3
#define RELAY 7
volatile boolean insert = false;
byte amountToDispense = 0;
int pulse = 0;
int temp = 0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR, INPUT_PULLUP);
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(2), coinInterrupt, RISING);
}
void loop()
{
if (insert ) {
insert = false;
Serial.println("coin");
delay(1000);
}
if (Serial.available())
{
timer = millis();
temp = Serial.parseInt();
if (temp > 0) {
//amountToDispense = Serial.read() - 48;
digitalWrite(RELAY, LOW);
}
}
if (digitalRead(SENSOR))
{
timer = millis();
pulse++;
Serial.println("out 1");
if (pulse >= temp)
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
if (!digitalRead(RELAY) && (millis() - timer > 2000))
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
void coinInterrupt() {
insert = true;
}
What is this supposed to do?
sen=(sen<<1)|digitalRead(SENSOR);
You init sen with digitalRead(SENSOR);
Assuming that pin is LOW when you start the sketch and turns HIGH, sen will become 1.
Next you do sen &= 0x03 so sen is still 1.
Again sen=(sen<<1)|digitalRead(SENSOR); , sen will either be 2 or 3.
Next loop run sen=(sen<<1)|digitalRead(SENSOR); sen is now 4 or 6. and so on...
I don't have time to think about what you want to achieve but this is definitely a problem as you'll only enter if (sen == 1) once and never again.
If this is not sufficient you should probably improve your post as it is unclear what arduino sends bad signal to interrup pin is supposed to mean. That doesn't make sense. Explain the expected behaviour of your program and how it behaves instead. add more comments so it becomes clear what you intend to do with each block of code so we don't have to interpret

ESP32 handle webserver and neopixels (with delay) in two cores

I'm searching the answer for a while but haven't found how to fix this problem. I have a lot of neopixel animations (currently 50 of them), these are written with delays which keeps the animations simple and readable. disadvantage is the delays as you all know. 50 animations to rewrite is a hell of a job so I want to avoid this. What I did is bought an ESP32 with two cores, so I thought I could run the animations on one core and the webserver on one core. previously I wanted to do I with an interrupt on a ESP8266 but I red and tested that I was not possible to do communication things or run a webserver in an interrupt for example. Is it possible to do that with two cores on an ESP32 or am I running in to the same problem as earlier? current output of the program: My webserver starts and the neopixel animation is showed when pushing the button, however my webserver continuously restarts over and over again. Any help appreciated, thanks in advance!
ps: In the worst case scenario I have to rewrite my animations, anyone an idea how to replace 3 for loops in to non blocking code?
code running on ESP32:
TaskHandle_t Task1;
TaskHandle_t Task2;
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUM_LEDS 24
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);
void colorWipe(byte red, byte green, byte blue, int SpeedDelay) {
for(uint16_t i=0; i<NUM_LEDS; i++) {
setPixel(i, red, green, blue);
showStrip();
delay(SpeedDelay);
}
}
// *** REPLACE TO HERE ***
void showStrip() {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.show();
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
FastLED.show();
#endif
}
void setPixel(int Pixel, byte red, byte green, byte blue) {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.setPixelColor(Pixel, strip.Color(red, green, blue));
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
leds[Pixel].r = red;
leds[Pixel].g = green;
leds[Pixel].b = blue;
#endif
}
void setAll(byte red, byte green, byte blue) {
for(int i = 0; i < NUM_LEDS; i++ ) {
setPixel(i, red, green, blue);
}
showStrip();
}
#include <WiFi.h>
const char* WIFI_NAME= "xxxxxxxxxx";
const char* WIFI_PASSWORD = "xxxxxxxxxx";
WiFiServer server(80);
String header;
// Auxiliary variables to store the current output state
String output5State = "off";
String output4State = "off";
// Assign output variables to GPIO pins
const int output5 = 2;
const int output4 = 4;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
String ledState = "off";
void setup() {
//create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0
xTaskCreatePinnedToCore(
Task1code, /* Task function. */
"Task1", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task1, /* Task handle to keep track of created task */
0); /* pin task to core 0 */
delay(500);
//create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1
xTaskCreatePinnedToCore(
Task2code, /* Task function. */
"Task2", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task2, /* Task handle to keep track of created task */
1); /* pin task to core 1 */
delay(500);
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output5, OUTPUT);
pinMode(output4, OUTPUT);
// Set outputs to LOW
digitalWrite(output5, LOW);
digitalWrite(output4, LOW);
}
//Task1code: blinks an LED every 1000 ms
void Task1code( void * pvParameters ){
Serial.print("Task1 running on core ");
Serial.println(xPortGetCoreID());
strip.begin();
strip.show(); // Initialize all pixels to 'off'
for(;;){
/*
digitalWrite(output5, HIGH);
delay(1000);
digitalWrite(output5, LOW);
delay(1000);*/
//Serial.print("state:" + ledState);
if(ledState == "on") {
//digitalWrite(output4, HIGH);
colorWipe(0x00,0xff,0x00, 50);
colorWipe(0x00,0x00,0x00, 50);
} else {
strip.clear();
strip.show();
}
}
}
//Task2code: blinks an LED every 700 ms
void Task2code( void * pvParameters ){
Serial.print("Connecting to ");
Serial.println(WIFI_NAME);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print("Trying to connect to Wifi Network");
}
Serial.println("");
Serial.println("Successfully connected to WiFi network");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
for(;;){
WiFiClient client = server.available();
if (client) {
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
currentTime = millis();
previousTime = currentTime;
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /5/on") >= 0) {
Serial.println("GPIO 5 on");
output5State = "on";
//digitalWrite(output5, HIGH);
} else if (header.indexOf("GET /5/off") >= 0) {
Serial.println("GPIO 5 off");
output5State = "off";
//digitalWrite(output5, LOW);
} else if (header.indexOf("GET /4/on") >= 0) {
Serial.println("GPIO 4 on");
output4State = "on";
ledState = "on";
//digitalWrite(output4, HIGH);
} else if (header.indexOf("GET /4/off") >= 0) {
Serial.println("GPIO 4 off");
output4State = "off";
ledState = "off";
//digitalWrite(output4, LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #77878A;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP8266 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 5
client.println("<p>GPIO 5 - State " + output5State + "</p>");
// If the output5State is off, it displays the ON button
if (output5State=="off") {
client.println("<p><button class=\"button\">ON</button></p>");
} else {
client.println("<p><button class=\"button button2\">OFF</button></p>");
}
// Display current state, and ON/OFF buttons for GPIO 4
client.println("<p>GPIO 4 - State " + output4State + "</p>");
// If the output4State is off, it displays the ON button
if (output4State=="off") {
client.println("<p><button class=\"button\">ON</button></p>");
} else {
client.println("<p><button class=\"button button2\">OFF</button></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
}
void loop(){
}
animation with three for loops:
void theaterChaseRainbow(int SpeedDelay) { /* for wheel watch higher in the code */
byte *c;
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
for (int q=0; q < 3; q++) {
for (int i=0; i < NUM_LEDS; i=i+3) {
c = Wheels( (i+j) % 255);
setPixel(i+q, *c, *(c+1), *(c+2)); //turn every third pixel on
}
showStrip();
delay(SpeedDelay);
for (int i=0; i < NUM_LEDS; i=i+3) {
setPixel(i+q, 0,0,0); //turn every third pixel off
}
}
}
}
You're 95% of the way there. ESP32 runs FreeRTOS with preemptive multi-threading. Your code is quite reasonably divided into two threads (Task1 and Task2) which run on different cores. In fact, the number of cores doesn't really matter much as long as you're not running out of CPU cycles or violating the real-time deadlines of your animations. You could probably run both tasks concurrently on a single core without the ESP32 breaking a sweat.
As for the HTTP server restarting - that's the intended behaviour of your code, is it not? The (rather horribly indented) function Task2code runs a never-ending loop which starts the HTTP server, serves a page and the stops. Is this loop really necessary?

vw_get_message return false when running motors

I am using Arduino for the first time, my project consists of RF transmitter connected with arduino UNO and a RF receiver connected to Arduino Mega.
I'm try to send data from transmitter and print it on receiver serial using VirtualWire library and every thing is okey for this receiver code:
#include <VirtualWire.h>
int x=9;
int y=8;
int z=10;
int r=7;
void setup()
{
Serial.begin(9600);
pinMode(x,OUTPUT);
pinMode(y,OUTPUT);
pinMode(z,OUTPUT);
pinMode(r,OUTPUT);
vw_setup(2000);
vw_rx_start();
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
// Message with a good checksum received, print it.
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.println();
}
}
Then i add some if statments to run 2 motors (connected to x,y,z,r pins) based on recrived values :
#include <VirtualWire.h>
int x=9;
int y=8;
int z=10;
int r=7;
void setup()
{
Serial.begin(9600);
pinMode(x,OUTPUT);
pinMode(y,OUTPUT);
pinMode(z,OUTPUT);
pinMode(r,OUTPUT);
vw_setup(2000);
vw_rx_start();
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
// Message with a good checksum received, print it.
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
if (buf[i]==0x77)//Stop motors
{
digitalWrite(x,LOW);
digitalWrite(y,LOW);
digitalWrite(z,LOW);
digitalWrite(r,LOW);
}
else
{
if(buf[i]==0x80)//2 motors clockwise
{
digitalWrite(x,LOW);
digitalWrite(y,HIGH);
digitalWrite(z,HIGH);
digitalWrite(r,LOW);
}
if (buf[i]==0x90)//counter clockwise
{
digitalWrite(x,HIGH);
digitalWrite(y,LOW);
digitalWrite(z,LOW);
digitalWrite(r,HIGH);
}
}
}
Now the problem is that when motors is stop working and I am sending the values that will run it either with or counterclockwise the motor works in the right direction but then does not respond to any data sent.
In short, when the motor stops working and I send data, the receiver receives the values and runs the motor violin is required, but then for example if the motor was working clockwise and sent the order which is running counterclockwise or even stop work, it does not respond and continues to move It was.
I noticed that this bacause when motors runs this function returns false
vw_get_message(buf, &buflen)
But i don't no why!
In VirtualWire library every time you send a new character or a set of characters your buffer will be overwritten. So the problem in this program is with your for loop checking. It will work fine if you just use the following
For example if you are sending characters like 'A', 'B' etc then
if (vw_get_message(buf, &buflen))
{
if(buf[0]=='A')
{
//move forward
}
if(buf[0]=='B')
{
//move backward
}
.... and so on
Hope this helps

arduino interrupts with servo motor

currently am working on project to open a door with access code using arduino UNO and a servo motor. Normal operation requires entering access code using keypad which is working fine. Another option requires pressing a button that causes an interrupt to rotate the servo motor. My problem is my interrupt only works once and never works again. Plus how do i put the for-loop to rotate the servo motor inside the interrupt function with a delay. I know that is not possible but am calling another function that has the delayMicroseconds but all this is not working. Below is my implementation please help
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
Servo servo;
const int openButtonPin = 2;
void setup() {
// put your setup code here, to run once:
servo.attach(5);
pinMode(openButtonPin, INPUT); //Pin 2 is input
attachInterrupt(0, enforceOpenAccess, HIGH); // PIN 2
}
void(* resetFunc)(void) = 0;
void loop()
{
//My other keypad implementations go here
}
void myDelay(int x) // function to cause delay in the interrupt
{
for(int i = 0; i<x; i++)
{
delayMicroseconds(1000);
}
}
void enforceOpenAccess() // ISR
{
for(int k =0; k<=180; k+=2)
{
servo.write(k); //rotate the servo
myDelay(30); //delay the rotation of the servo
}
}
The code above is run on arduino UNO being simulated in proteus and the interrupt button is a push button. Please if there is other ways of implementing that but with the same behaviour as I have described above help out. Thanks a lot
There are a couple of problems in the slice of code you posted. Just for completeness, you should post the loop function, since we can't guess what you wrote inside.
Just one comment: did you put a pullup? Otherwise use INPUT_PULLUP instead of INPUT for the button pinmode.
The main one is that you attached the interrupt for the HIGH mode, which will trigger the interrupt any time the pin is up, not on the rising edge. And please use the macro digitalPinToInterrupt to map to the correct pin:
attachInterrupt(digitalPinToInterrupt(openButtonPin), enforceOpenAccess, RISING);
Then.. Let's improve the code. You really should use the interrupts only when strictly necessary when you have to respond IMMEDIATELY (= less than a couple of milliseconds) to an input. Here you don't have to, so it's MUCH better to check for the button in the loop (more on turning the motor following)
uint8_t lastState;
void setup()
{
...
lastState = LOW;
}
void loop()
{
uint8_t currentState = digitalRead(openButtonPin);
if ((currentState != lastState) && (currentState == HIGH))
{
// Start turning the motor
}
lastState = currentState;
...
}
This will enable you to properly debounce the button too:
#include <Bounce2.h>
Bounce debouncer = Bounce();
void setup()
{
...
pinMode(openButtonPin, INPUT); //Pin 2 is input
debouncer.attach(openButtonPin);
debouncer.interval(5); // interval in ms
}
void loop()
{
debouncer.update();
if (debouncer.rose())
{
// Start turning the motor
}
...
}
If, on the other way, you REALLY want to use the interrupts (because waiting for a couple of milliseconds is too much for you), you should do something like this:
#include <Bounce2.h>
Bounce debouncer = Bounce();
void setup()
{
...
pinMode(openButtonPin, INPUT);
attachInterrupt(digitalPinToInterrupt(openButtonPin), enforceOpenAccess, RISING);
}
void loop()
{
...
}
void enforceOpenAccess() // ISR
{
// Start turning the motor
}
It looks like your code? No, because now we'll speak about turning the motor
You should NOT use delays to make steps, because otherwise you will wait for 30ms * 180 steps = 5.4s before being able to do anything else.
You can, however, make a sort of reduced state machine. You want your servo to move from 0 to 180 in steps of 1. So let's code the "don't move" state with any value greater than 180, and consequently we can do something like this in the loop:
unsigned long lastServoTime;
uint8_t servoPosition = 255;
const int timeBetweenSteps_in_ms = 30;
void loop()
{
...
if (servoPosition <= 180)
{ // servo should move
if ((millis() - lastServoTime) >= timeBetweenSteps_in_ms)
{
lastServoTime += timeBetweenSteps_in_ms;
servoPosition++;
if (servoPosition <= 180)
servo.write(servoPosition);
}
}
}
Then, using any of the previous examples, instead of // Start turning the motor write
lastServoTime = millis();
servoPosition = 0;
servo.write(servoPosition);
This way you won't block the main loop even when the button is pressed
This is what is in my loop()
char key = keypad.getKey();
if(key)
{
if(j < 10)
{
studentNumber[j] = key;
//holdMaskedNumber[j] = '*';
lcd.setCursor(0,2);
lcd.print(String(studentNumber));
if(j == 9)
{
studentNumber[9] = '\0';
//holdMaskedNumber[9] = 0;
lcd.clear();
//String number = String(studentNumber);
//lcd.print(number);
//delay(1000);
//lcd.clear();
lcd.print("Access Code");
}
j++;
}
else
{
if(i < 5)
{
accessCode[i] = key;
holdMaskedCode[i] = '*';
lcd.setCursor(1,2);
lcd.print(String(holdMaskedCode));
if(i == 4)
{
holdMaskedCode[5] = '\0';
accessCode[5] = '\0';
//lcd.clear();
//lcd.setCursor(0,0);
//accessCodeString = String(accessCode);
//lcd.print(accessCodeString);
//delay(1000);
lcd.clear();
for(int i =0; i<6; i++)
{
lcd.print("Please wait.");
delay(500);
lcd.clear();
lcd.print("Please wait..");
delay(500);
lcd.clear();
lcd.print("Please wait...");
delay(500);
lcd.clear();
}
digitalWrite(4, HIGH);
lcd.print("Access Granted");
for(int k =0; k<=180; k+=2)
{
servo.write(k);
delay(30);
}
resetFunc();
}
i++;
}
}
}

Send over infrared on Arduino

I need to transmit an infrared signal using the Arduino to run a Samsung TV.
I tried the following code:
// Lucas Eckels
// Http://lucaseckels.com
// IR remote control emitter for NEC protocol remote, as described at
// Http://www.sbprojects.com/knowledge/ir/nec.htm
// Tested on a Samsung LCD TV.
#include <util/delay.h>
#define IR_PIN 13
// With CONTINOUS defined, the first command is repeated continuously until
// You reset the Arduino. Otherwise, it sends the code once, then waits for
// Another command.
#define CONTINUOUS
// Times are in microseconds
#define ON_START_TIME 4500
#define OFF_START_TIME 4500
#define ON_TIME 580
#define OFF_TIME_ONE 1670
#define OFF_TIME_ZERO 540
#define DEVICE_1 7
#define DEVICE_2 7
void setup() {
pinMode (IR_PIN, OUTPUT);
digitalWrite(IR_PIN, LOW);
Serial.begin(9600);
delay(1000);
Serial.write("Starting up..\n");
}
byte command = 0;
int commandCount = 0;
bool commandReady = false;
void loop() {
if (commandReady) {
Serial.print("Writing command");
Serial.print(command, DEC);
Serial.print("\n");
writeStart();
// Writing device code
writeByte(DEVICE_1);
writeByte(DEVICE_2);
// Writing command code
writeByte(command);
writeByte(~command);
writeEnd();
delay(100);
#ifndef CONTINUOUS
commandReady = false;
command = 0;
commandCount = 0;
#endif
return;
}
if (Serial.available () > 0) {
// Read in a 3-digit decimal command code.
byte incoming = Serial.read();
if (incoming <= '9 ' || incoming >= '0') {
command *= 10;
command += incoming - '0 ';
++commandCount;
}
if (commandCount == 3) {
commandReady = true;
}
}
}
void writeStart() {
modulate(ON_START_TIME);
delayMicroseconds(OFF_START_TIME);
}
void writeEnd() {
modulate(ON_TIME);
}
void writeByte(byte val) {
// Starting with the LSB, write out the
for (int i = 0x01; i & 0xFF; i <<= 1) {
modulate(ON_TIME);
if (val & i) {
delayMicroseconds (OFF_TIME_ONE);
} else {
delayMicroseconds (OFF_TIME_ZERO);
}
}
}
void modulate(int time) {
int count = time / 26;
byte portb = PORTB;
byte portbHigh = portb | 0x20; // Pin 13 is controlled by 0x20 on PORTB.
byte portbLow = portb & ~0x20;
for (int i = 0; i <= count; i++) {
// The ideal version of this loop would be:
// DigitalWrite(IR_PIN, HIGH);
// DelayMicroseconds(13);
// DigitalWrite(IR_PIN, LOW);
// DelayMicroseconds(13);
// But I had a hard time getting the timing to work right. This approach was found
// Through experimentation.
PORTB = portbHigh;
_delay_loop_1(64);
PORTB = portbLow;
_delay_loop_1(64);
}
PORTB = portb;
}
The code compiles but is not working for me.
I wrote this to control an LG TV and Sony Amplifier. You would just need to save your own raw codes to the header file and off you go:
https://github.com/gotnull/SiriProxy-TV-Control/blob/master/arduino-remote/Remote/Remote.pde
// This procedure sends a 38KHz pulse to the IRledPin
// for a certain # of microseconds. We'll use this whenever we need to send codes
void pulseIR(long microsecs) {
// we'll count down from the number of microseconds we are told to wait
cli(); // this turns off any background interrupts
while (microsecs > 0) {
// 38 kHz is about 13 microseconds high and 13 microseconds low
digitalWrite(IRledPin, HIGH); // this takes about 3 microseconds to happen
delayMicroseconds(10); // hang out for 10 microseconds
digitalWrite(IRledPin, LOW); // this also takes about 3 microseconds
delayMicroseconds(10); // hang out for 10 microseconds
// so 26 microseconds altogether
microsecs -= 26;
}
sei(); // this turns them back on
}
I'd also recommend taking a read through Ladyada's wonderful tutorial:
Sensor tutorials - IR remote receiver/decoder tutorial
DelayMicroseconds is fairly accurate, and will be precise enough for your task. However you are right in staying away from DigitalWrite. It takes about 50 times as many clock-cycles to complete compared to direct port assignment (PORTB=... ) which takes exactly one. You will only be able to time a 38MHz pulse that way. I don't know what your _delay_loop_1 does, but everything else seems okay. (aside from the "i + +" but that's a cut'n'paste typo I guess)
Have you checked that it actually lights up? a phone or cheap digicam will actually show you the IR on the screen.

Resources