CASE stepper IR remote and Arduino - arduino

This is my code and i want to control stepper with IR remote. My code work fine but i want to know how can continu my action while a hold button on remote. The HEX code is different when i hold button and i don't know to recall my last function.
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) // have we received an IR signal?
{
switch (results.value)
Here, i start switch with my HEX code fron IR remote
{
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
}
}
Use function for calling action
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}enter code here
Thank

Try this.
This will remember your last keypress.
If the current keypress is a "hold", it will run the same function as the last keypress
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
// last keypress value
unsigned long prev_result_value = 0;
// this key press value
unsigned long current_result_value;
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) { // have we received an IR signal?
current_result_value = results.value; // store the result
if (!prev_result_value)
prev_results_value = current_result_value; // first time through only.
if (results.value == HOLD_CODE) // is this a hold code?
current_results_value = rev_results_value; // make the current result the same as the last keypress.
//switch (results.value) {
switch (current_results_value) {
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
prev_results_value = current_results_value;
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
prev_results_value = current_results_value;
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
prev_results_value = current_results_value;
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
Serial.println(current_results_value, HEX);
Serial.println(prev_results_value, HEX);
}
}
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}

Related

why my arduino doesnt recognize the characters?

I have a problem with my Bluetooth module on my Arduino, I am trying to do a door that opens with a button in an application in the phone but when I press the button in the app the door doesn't move.
#include <SoftwareSerial.h>
#include <Servo.h>
int mover;
int mover2;
Servo servoMotor1;
Servo servoMotor2;
char rxChar;
SoftwareSerial BTserial(10, 11);
void setup(){
Serial.begin(9600);
Serial.println("Bluetooth test program");
pinMode (4,INPUT);//Fin de carrera 1
pinMode (2,INPUT);//Fin de carrera 2
mover=90; //0 Abrir 180 Cerrar 60-120 Velocidades
mover2=150;//motor Cerradura
servoMotor1.attach(8);//Motor Pin8
servoMotor2.attach(9);//Motor Pin9
BTserial.begin(9600);
BTserial.println("Bluetooth test program");
}
void loop() {
int lectura;
int lectura2;
servoMotor1.write(mover);
servoMotor2.write(mover2);
lectura=digitalRead(4);//fin de carrera
lectura2=digitalRead(2);//fin de carrera
if (Serial.available())
{
BTserial.write(Serial.read());
}
if (BTserial.available())
{
Serial.write(BTserial.read());
char rxChar = BTserial.read();
}
if(rxChar=='a'){
Serial.print("60 Grados");
mover=60;
}
if(rxChar=='b'){
Serial.print("120 Grados");
mover=120;
}
if (lectura==LOW and mover==120){
mover=90;//motor frena
mover2=30;//Motor Cerradura Cerrado
}
if (lectura2==LOW and mover==60){
mover=90;//motor frena
}
}
when I press the button the console returns "⸮"
This line is wrong: char rxChar = BTserial.read(); because you are declaring a local rxChar and assigning the read character to it. But, because it is local (inside { } ) its value will be lost. And because you also have a global rxChar (line 7: char rxChar;) that is unassigned, you will be using that value everywhere else.
Also, as mentioned you are reading from BTSerial twice.
You can fix the problem by simply removing "char" in the line mentioned, so rxChar will refer to the global declaration, and
perform only one read: rxChar = BTserial.read(); Serial.write(rxChar);

UniversalTelegramBot doesn't work with ESP32 but it doesn't show an error. I think it's a libraries version compatibility issue,could someone help me?

I'm developing a program in Arduino Ide (v. 1.8.13) which takes brightness values and send them to ESP32 Web Server. Also, I want to add the posibility of seeing the data via Telegram. At the moment I just want to send '/start' to the Telegram bot and Arduino program answer with a welcome message. However, the bot doesn't receive my messages. I read this is a versions issue between ArduinoJson, Universal Telegram Bot, Arduino Ide and ESP32 Core version. Could someone tell me what versions work fine in ESP32? I'm getting crazy.
I add my actual code.
These are the versions I'm using: Arduino Ide:1.8.13, Arduino Json:6.18, Universal Telegram Bot:1.3.0, Wifi Client Secure:1.0, ESP32:1.04.
Thanks in advance :)
// Import required libraries
#include <WiFi.h>
#include <Wire.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>
const char* ssid_STA = "XXXXXX";
const char* password_STA = "XXXXXX";
IPAddress ip(192,168,1,44);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
#define BOTtoken "XXXXXX"
#define CHAT_ID "XXXXXXX"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
time_t fecha;
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
void configureSensor(void)
{
/* You can also manually set the gain or enable auto-gain support */
// tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */
// tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */
tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */
/* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but slowest conversions */
/* Update these values depending on what you've set above! */
Serial.println("------------------------------------");
Serial.print ("Gain: "); Serial.println("Auto");
Serial.print ("Timing: "); Serial.println("13 ms");
Serial.println("------------------------------------");
}
String readLuz() {
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
Serial.print(event.light); Serial.println(" lux");
return String(event.light);
}
void Informacion(){
Serial.println("voy a enviar");
sensors_event_t event;
tsl.getEvent(&event);
//bot.sendMessage(chat_ID, "La luminosidad en tu jardín es de " ,"");
Serial.println("enviado");
}
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
Serial.println(chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
//COger texto
String text = bot.messages[i].text;
Serial.println(text);
//Coger nombre
String from_name = bot.messages[i].from_name;
//if (text == "/get_info") {
//}
if (text == "/start") {
String welcome = "Bienvenida "+from_name+"\n";
welcome += "Properties.\n\n";
welcome += "/get_info : Obtener información actual del jardín\n";
bot.sendMessage(chat_id, welcome, "");
}
}
}
/**************************************************************************/
/*
Arduino setup function (automatically called at startup)
*/
/**************************************************************************/
void setup(void)
{
Serial.begin(115200);
// client.setInsecure();
/* Initialise the sensor */
//use tsl.begin() to default to Wire,
//tsl.begin(&Wire2) directs api to use Wire2, etc.
if(!tsl.begin())
{
/* There was a problem detecting the TSL2561 ... check your connections */
Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
while(1);
}
/* Display some basic information on this sensor and Setup the sensor gain and integration time */
//displaySensorDetails();
configureSensor();
///EJEMPLO SREVER
// Initialize SPIFFS
if(!SPIFFS.begin()){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
;
// Connect to Wi-Fi
//WiFi.softAP(ssid_AP, password_AP);
WiFi.mode(WIFI_STA);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid_STA, password_STA);
while (WiFi.status() != WL_CONNECTED) {
delay(3000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println("IP");
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html");
});
server.on("/luz", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readLuz().c_str());
});
// Start server
server.begin();
/*
//ALARMS
//Coger la hora real al reiniciar
//fecha = now();
//Serial.print(hour(fecha)); Serial.print(minute(fecha)); Serial.print(second(fecha)); Serial.print(day(fecha)); Serial.print(month(fecha)); Serial.println(year(fecha));
//setTime(hour(fecha), minute(fecha),second(fecha), day(fecha), month(fecha),year(fecha));
setTime(12, 42, 00, 16, 6, 21);
// Crear las alarmas y configurar las funciones correspondientes a cada una
Alarm.alarmRepeat(8, 0, 0, Informacion); // Evento a las 14:00 diario
Alarm.alarmRepeat(12,43, 0, Informacion); // Evento a las 14:05 diario
Alarm.alarmRepeat(21, 0, 0, Informacion); // Evento a las 14:10 diario
*/
}
/**************************************************************************/
/*
Arduino loop function, called once 'setup' is complete (your own code
should go here)
*/
/**************************************************************************/
void loop(void){
if (millis() > lastTimeBotRan + botRequestDelay) {
Serial.println("loop");
Serial.println(bot.last_message_received);
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan= millis();
}
// Mostrar el reloj en el monitor serial
//digitalClockDisplay();
// Esperar 1 segundo y procesar las Alarmas mientras tanto...
//Alarm.delay(1000);
}
/*
void digitalClockDisplay() {
Serial.print(hour());
printDigits(minute());
//printDigits(second());
Serial.println();
}
void printDigits(int digits) {
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
*/
I suppose you are missing the statement
// Add root certificate for api.telegram.org
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);

Why won't my Arduino Uno run my door locking code?

Sorry for the messy code, but I was wondering if anyone knows why it can't be run on my Arduino Uno? It's for a locking door controlled by RFID and IR remote respectively, and it stopped working for some reason when I edited the code for the void ir() section.
my code:
#include <MFRC522.h>
#include "Stepper.h"
#include "IRremote.h"
#define SS_PIN 10
#define RST_PIN 9
#define ACCESS_DELAY 2000
#define DENIED_DELAY 1000
MFRC522 mfrc522(SS_PIN, RST_PIN);
#define STEPS 32 // Number of steps per revolution of Internal shaft
Stepper small_stepper(STEPS, 2, 4, 3, 5);
int Steps2Take; // 2048 = 1 Revolution
int receiver = 8; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
bool locked = true;
int steps = 500;
// Create MFRC522 instance.
/*----- Variables, Pins -----*/
/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4
void setup()
{
irrecv.enableIRIn(); // Start the receiver
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Put your card to the reader...");
Serial.println();
}
void rfid()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
if (content.substring(1) == "B9 67 D6 6E") //change here the UID of the card/cards that you want to give access
{
Serial.println("Authorized access");
Serial.println();
delay(500);
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
delay(3000);
Steps2Take = -steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
}
else {
Serial.println(" Access denied");
delay(3000);
}
}
void ir()
{ if (irrecv.decode(&results)) // have we received an IR signal?
{
switch(results.value)
{
case 0xFFA857: //VOL - pressed
if (locked == true){
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
locked = false;
}
case 0xFF629D: //VOL + pressed
if (locked == false){
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = -steps; // Rotate 500 ACW
small_stepper.step(Steps2Take); //Do the steps
locked = true;
}
}
}
}
}
void loop()
{
ir();
rfid();
}
My error:
/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T//ccQ6deD3.ltrans0.ltrans.o: In function main':
/private/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T/AppTranslocation/F6976C18-1AF6-4EB1-A8BD-1B9FBC53FC03/d/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/main.cpp:46: undefined reference toloop'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Stepper.h"
Used: /Users/Ulitimac/Documents/Arduino/libraries/Stepper
Not used: /private/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T/AppTranslocation/F6976C18-1AF6-4EB1-A8BD-1B9FBC53FC03/d/Arduino.app/Contents/Java/libraries/Stepper
exit status 1
Error compiling for board Arduino/Genuino Uno.
Thanks in advance!

Sending IR signal from Arduino to F&D speakers

I am using below code to send an IR signal to my speaker but they don't respond.
#include <IRremote.h>
IRsend irsend;
const int buttonPin = 8; // the number of the pushbutton pin
//const int ledPin = 3;
int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
// pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(7,HIGH);
irsend.sendNEC(0x1FE08F7,32);
}else{
digitalWrite(7,LOW);
}
}
IR Reciever on my other Arduino receives signal but also they vary sometime it shows UNKNOWN and sometime NEC. I am using below code:
#include <IRremote.h>
const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
irrecv.blink13(true);
}
void loop() {
if (irrecv.decode(&results)) {
if (results.decode_type == NEC) {
Serial.print("NEC: ");
} else if (results.decode_type == SONY) {
Serial.print("SONY: ");
} else if (results.decode_type == RC5) {
Serial.print("RC5: ");
} else if (results.decode_type == RC6) {
Serial.print("RC6: ");
} else if (results.decode_type == UNKNOWN) {
Serial.print("UNKNOWN: ");
}
Serial.println(results.value, HEX);
Serial.println(results.value);
irrecv.resume(); // Receive the next value
}
}
The NEC code that I recieved is correct but on that code speaker does not respond. I double checked the HEX code with the remote that came along with speaker but nothing seem to work.
I think that you could have problem with the HEX literal.
From Arduino API:
By default, an integer constant is treated as an int with the attendant limitations in values. To specify an integer constant with another data type, follow it with:
a 'u' or 'U' to force the constant into an unsigned data format. Example: 33u
a 'l' or 'L' to force the constant into a long data format. Example: 100000L
a 'ul' or 'UL' to force the constant into an unsigned long constant. Example: 32767ul
And from GitHub:
void sendNEC (unsigned long data, int nbits) ;
So, try:
irsend.sendNEC(0x01FE08F7UL,32);

arduino+Esp8266 + apk (TCP server-client)

someone know how i can do a correct comunication with esp8266 and apk (tcp server<->tcp client)
Here is the problem:
I send values and esp8266 dont read it well sometime;
arduino bauidio:115200
esp8266 baudio:115200
apk: send msg like 5;del;45 (speed,state,servo_position)
this is my car code (tcp server):
#include <SoftwareSerial.h>
#include <Servo.h>
#define M_ATRAS 4
#define M_ADELANTE 5
#define M_VELOCIDAD 6
Servo servo; // Crea un Objeto servo
SoftwareSerial ESP8266(3,2); //1)RX-> Azul, 2)TX->Amarillo
String mar;
int vel;
int rot;
void setup()
{
Serial.begin(9600);
ESP8266.begin(115200);
Serial.println("Iniciando...");
comandoESP("AT+RST"); // reset module
comandoESP("AT+CWMODE=3"); // configure as access point
//comandoESP("AT+CWSAP=\"ESP\",\"1234567890\",3,3"); //SSID,PASSWORD,CHANNEL,PASSWORD-ENCRYPATION(0=NO PASSWORD) //0 is encryption type like 0 = Open, 2 =WPA_PSK, 3 = WPA2_PSK, 4 = WPA_WPA2_PSK
comandoESP("AT+CWJAP=\"tfh\",\"fggrtfdfgdtg\"");
comandoESP("AT+CIPMUX=1"); // configure for multiple connections
comandoESP("AT+CIPSERVER=1,400"); // turn on server on port x
Serial.println("Servidor TCP ON...");
pinMode(M_VELOCIDAD, OUTPUT);
pinMode(M_ATRAS,OUTPUT);
pinMode(M_ADELANTE,OUTPUT);
velocidad(0);
servo.attach(7); // Selecionamos el pinde control para el servo Rango: 0<->155
Serial.println("Posicion delservo: "+String(servo.read()));
}
void loop()
{
if(ESP8266.available())
{
if(ESP8266.findUntil("+IPD,","."))
{
vel=ESP8266.readStringUntil(';').toInt();
mar=ESP8266.readStringUntil(';');
rot=ESP8266.readStringUntil(';').toInt();
velocidad( vel);
marcha(mar);
rotacion(rot);
Serial.println(String(vel)+"-"+mar+"-"+String(rot));
}
}
}
void marcha(String tipo){
if(tipo == "del")
{
//Serial.println("Adelante?");
digitalWrite(M_ATRAS,LOW);
digitalWrite(M_ADELANTE,HIGH);
}
else if(tipo == "tra")
{
//Serial.println("Atras?");
digitalWrite(M_ATRAS,HIGH);
digitalWrite(M_ADELANTE,LOW);
}
}
void velocidad(int v){
//Serial.println("Velocidad: "+String(v));
analogWrite(M_VELOCIDAD, v);
}
void rotacion(int r){
int rot =map(r,-10, 10, 125, 0); //mapeamos los valores que puede tener el acelerometro a los valores que puede tener el servo
//Serial.println("Acelerometro: "+String(r)+" Servo: "+String(rot));
servo.write(rot);
}
void comandoESP(String cmd)
{
ESP8266.println(cmd);
if(ESP8266.available())
Serial.println(ESP8266.readStringUntil(14));
delay(1000*3); //3seg
}
Instead of writing your own AT Commands, use a library and use Virtual Serial.
WeeESP8266 is a nice library. See my post on how to put all together.

Resources