Send limited SMS (SIM800L) Arduino [closed] - arduino

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 days ago.
This post was edited and submitted for review 8 days ago.
Improve this question
Hi, I'm new to the forum and would like some help.
I have a personal project where, "when changing the state of an on/off switch, only 2 SMS messages are sent (I am using the SIM800L) to a certain number, without repeating these messages and when the state of the switch changes, send others 2 SMS to this same number. The port where the key is, will be monitored to verify the change of state, so I want to limit the amount of SMS so as not to keep sending several messages while the key remains in the current state". I use a ESP32 WROOM board and one SIM800L board.
I already configured loops, instances but the logic doesn't work.
Here's of the code I'm working on; i don't know the language C very well and maybe conain errors.
Thanks for the help.
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG Serial
//====================================================================
// Configura os numeros de telefone que receberão a notificação padrão.
#define SMS_CONTATO_1 "+55XXXXXXXXXXX" //Anton
#define SMS_CONTATO_2 "+55XXXXXXXXXXX" //Anton1
#define SMS_CONTATO_3 "+55XXXXXXXXXXX" //Anton2
#define SMS_CONTATO_4 "+55XXXXXXXXXXX" //Anton3
//#define SMS_CONTATO_5 "+55XXXXXXXXXXX" //Substitua o XXXXXXXXXXXX pelo número que receberá a notificação
//====================================================================
// Credenciais de acesso a rede GPRS - Deixe vazio caso não precise de usuário e senha para conectar à rede GPRS
const char apn[] = "xxxxxxxxxx"; //Substitua xxxxxxxx pelo nome/endereço da operadora
const char user[] = "xxx"; //Se não houver user, deixar em branco
const char pass[] = "xxx"; //Se não houver pass, deixar em branco
//====================================================================
// Pino que receberá estado da rede de entrada (falha ou normalização)
const int PinFalha = 15;
//====================================================================
int LED_BUILTIN = 2; //Define ledPin interno no Pino 2
int MonitorLed = 4; //Define pino de monitoramento no Pino 4
//====================================================================
boolean botaoAtual = false; //Estado atual do botao conectado ao PinFalha (15)
boolean botaoAnt = false; //Estado anterior do botao conectado ao PinFalha (15)
//====================================================================
// Inclusão da biblioteca com os comandos para funcionamento do Modem SIM800L
#include <TinyGsmClient.h>
//====================================================================
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(Serial, Serial2);
TinyGsm modem(debugger);
#else
TinyGsm modem(Serial2);
#endif
//====================================================================
// Variáveis usadas para contar o tempo sem travar a função loop millis de referencia
long int millisRefCon, millisUserResp;
// Flag que indica a contagem de tempo (usadas pela função 'timeout')
bool flagCon = false, flagUserResp = false;
//====================================================================
String sendAT(String command)
{
String response = "";
Serial2.println(command);
// Aguardamos até que haja resposta do SIM800L
while(!Serial2.available());
response = Serial2.readString();
return response;
}
//====================================================================
void setup() {
Serial.begin(9600);
Serial2.begin(9600);
pinMode(PinFalha, INPUT);
//====================================================================
pinMode(LED_BUILTIN , OUTPUT);//Define ledPin (pino 10) como saída
pinMode(MonitorLed, OUTPUT);
//====================================================================
delay(3000);
// Atribui para as variáveis de contagem de tempo o tempo atual antes de entrar no loop
millisRefCon = millisUserResp = millis();
setupGSM(); //Inicializa o Modem SIM800L
Serial.println("||GPRS: Conectado||"); //Mensagem de confirmação de conexao
}
//====================================================================
void setupGSM() {
// A reinicialização levará algum tempo; basta aguardar por volta de 10 segundos
DBG("Inicializando modem...");
if (!modem.restart()) {
delay(10000);
return;
}
// Retorna com informações do Modem
String modemInfo = modem.getModemInfo();
DBG("||Modem:", modemInfo);
//====================================================================
bool res;
// Retorna a identificação do cartão SIM.
String ccid = modem.getSimCCID();
DBG("CCID:", ccid);
// Retorna com IMEI do Modem
String imei = modem.getIMEI();
DBG("IMEI:", imei);
//====================================================================
// Retorna a qualidade/intensidade do Sinal do Modem
// (10-14:OK | 15-19:BOM | 20-30 : Excelente
int csq = modem.getSignalQuality();
DBG("Qualidade de sinal:", csq);
// Retorna com o nível da bateria em %
int battLevel = modem.getBattPercent();
DBG("Nivel de bateria:", battLevel);
// Retorna com a voltagem da bateria/alimentação (Modem precisa de 3,7V a 4,1V)
float battVoltage = modem.getBattVoltage() / 1000.0F;
DBG("Voltagem de bateria:", battVoltage);
}
//====================================================================
// Função que compara se o tempo foi atingido, sem que 'congele' a execução do loop
bool timeout(const int DELAY, long *previousMillis, bool *flag)
{
if(*flag)
{
*previousMillis = millis();
*flag = false;
}
if((*previousMillis + DELAY) < millis())
{
*flag = true;
return true;
}
return false;
}
//====================================================================
void loop() {
while (botaoAtual==1) botaoAtual = digitalRead(PinFalha); //espera botao mudar de estado
if (botaoAtual && !botaoAnt == HIGH) { //Se estadoButton for igual a HIGH ou 1
digitalWrite(LED_BUILTIN , HIGH); //Define ledPin como HIGH, ligando o LED
digitalWrite(MonitorLed, HIGH); //Define Led sinalizador para HIGH, ligando o LED
smsNormal(); //Chama função "smsNormal" para enviar mensagem padrão para os numeros habilitados
}
else
while (botaoAtual==0) botaoAtual = digitalRead(PinFalha); //espera botao mudar de estado
{
digitalWrite(LED_BUILTIN, LOW); //Se estadoButton for igual a LOW, apaga Led
digitalWrite(MonitorLed, LOW); //Define Led sinalizador para LOW, desligando o LED
smsFalha(); //Chama função "smsFalha" para enviar mensagem padrão para os numeros habilitados
}
}
//====================================================================
//Função de envio de SMS em caso de retorno de energia ao estado normal
void smsFalha(){
bool res;
res = modem.sendSMS(SMS_CONTATO_1, String("***FALHA DE ENERGIA - MAQ.2***"));
DBG("SMS:", res ? "OK" : "fail");
res = modem.sendSMS_UTF16(SMS_CONTATO_1, u".:::Energy:::..", 21);
DBG("UTF16 SMS:", res ? "OK" : "fail");
res = modem.sendSMS(SMS_CONTATO_2, String("***FALHA DE ENERGIA - MAQ.2***"));
DBG("SMS:", res ? "OK" : "fail");
res = modem.sendSMS_UTF16(SMS_CONTATO_2, u".:::Energy:::..", 21);
DBG("UTF16 SMS:", res ? "OK" : "fail");
}
//Função de envio de SMS em caso de falha de energia
void smsNormal(){
bool res;
res = modem.sendSMS(SMS_CONTATO_1, String(".::RETORNO DE ENERGIA - MAQ.2::."));
DBG("SMS:", res ? "OK" : "fail");
res = modem.sendSMS_UTF16(SMS_CONTATO_1, u".:::Energy:::..", 21);
DBG("UTF16 SMS:", res ? "OK" : "fail");
res = modem.sendSMS(SMS_CONTATO_2, String(".:RETORNO DE ENERGIA - MAQ.2:."));
DBG("SMS:", res ? "OK" : "fail");
res = modem.sendSMS_UTF16(SMS_CONTATO_2, u".:::Energy:::..", 21);
DBG("UTF16 SMS:", res ? "OK" : "fail");
}
//====================================================================

Related

Press twice or more to turn off, once to turn on

I'm trying to make this sensor in ESP32, and I can't figure out what am I missing or if I did something wrong, I think I could use a relay module to make it easier, but the task implies that I only use basic code like if, while, etc. The thing is that I need to press twice in a short amount of time (1 or 2 seconds) while it is on to turn it off, and if it is off, just press once and it will turn on. I can't figure out how to make the sensor to stop, since it keeps giving signals.
It should work like: when someone goes closer than 30cm to the sensor, the red LED blink, if not the green LED is always on. I need to put in a button that turns off and on this device.
I tried to create a parameter that tells if it is on or off, but I can't make it work, I can not figure out why tho.
`#include <Arduino.h>
#define trigger 27
#define echo 14
#define ledrojo 4
#define ledverde 5
#define BOTON 13
float distancia = 0;
unsigned long ta = 0;
unsigned long tiempo_capturado_inicio = 0;
unsigned long tiempo_pulsado = 0;
int pulsos = 0;
int estadosistema = 0;
byte aux_boton = 0;
byte aux_inicio = 0;
void setup()
{
Serial.begin(9600);
// El numero serial para la comunicacion serial
pinMode(BOTON, INPUT_PULLUP);
estadosistema = 0;
}
void loop()
{
if (!digitalRead(BOTON)) // Cuando se presione el boton
{
while (!digitalRead(BOTON))
{
} // Mientras mantengo el boton presionado, no pasara nada
aux_inicio = 1; // Con esto enciendo el temporizador
aux_boton = 1; // Con esto comienza el contador
if (estadosistema = 1) // Si el sistema esta encendido sucedera:
{
if (aux_inicio = 1)
{
if (millis() - tiempo_pulsado >= 4000) // Tiempo maximo para dar el segundo pulso es 1 segundo
{
aux_inicio = 0; // Apagar el temporizador
aux_boton = 0; // Apagar el contador
}
if (!digitalRead(BOTON))
{
aux_boton = 1; // Mantener el contador encendido
}
if (aux_boton = 1 && !digitalRead(BOTON)) // Conteo de pulsos
{
pulsos += 1;
aux_boton = 0;
}
}
if (aux_inicio = 0) // Cuando el temporizador termina, se contea los pulsos
{
if (pulsos >= 1) // Si se pulso una segunda vez o mas, el sistema se apagara
{
estadosistema = 0;
pulsos = 0;
aux_boton = 0;
aux_inicio = 0;
Serial.print("Se ha apagado el sistema de alarma");
}
else
{ // Si solo se presiono una vez, el sistema seguira encendido
Serial.print("El sistema de alarma sigue encedido");
}
}
}
if (estadosistema = 0) // Si el sistema esta apagado sucedera:
{
estadosistema = 1; // Se enciende el sistema
delay(1000);
aux_boton = 0;
aux_inicio = 0;
Serial.print("El sistema de alarma se ha encendido");
}
}
if (estadosistema = 0) // Mientras el sistema esta apagado
{
distancia = 1000000000000000;
digitalWrite(trigger,LOW);
digitalWrite(echo,LOW);
}
if (estadosistema = 1)
{
pinMode(echo, INPUT);
// Esto es para recibir la informacion del echo del sensor ultrasonico
pinMode(trigger, OUTPUT);
// Esto es lo que provocara una señal en el sistema serial
pinMode(ledrojo, OUTPUT);
// Este es el led rojo que se usara cuando haya peligro
pinMode(ledverde, OUTPUT);
// Este es el led verde que se usara cuando no haya peligro
digitalWrite(trigger, HIGH); // Prendemos el trigger
delayMicroseconds(10);
digitalWrite(trigger, LOW); // Apagamos el trigger
ta = pulseIn(echo, HIGH); // Tiempo que demora en llegar la señal al Echo
ta = ta / 2;
distancia = ta / 29; // Distancia hasta el obstaculo
if (distancia <= 30)
{
digitalWrite(ledrojo, HIGH); // Prendemos el LED rojo
digitalWrite(ledverde, LOW); // Apagamos el LED verde
Serial.print("¡PELIGRO, RETROCEDA!"); // Mensaje de que una persona esta en la zona de peligro
delay(5);
Serial.print("");
digitalWrite(ledrojo, LOW); // Hacemos que parpadee a 100Hz
delay(5);
}
else
{
digitalWrite(ledverde, HIGH);
digitalWrite(ledrojo, LOW);
}
}
}
`
use easyButtton library (look at https://github.com/evert-arias/EasyButton)
try this sketch (may need some fix - not tested)
#include <EasyButton.h>
//syntax EasyButton button(BUTTON_PIN, debounce, pullup, invert);
EasyButton button(BOTON, 10, true, false);
boolean sensor_on;
#define trigger 27
#define echo 14
#define ledrojo 4
#define ledverde 5
#define BOTON 13
void setup()
{
Serial.begin(9600);
// El numero serial para la comunicacion serial
pinMode(BOTON, INPUT_PULLUP);
button.begin();
button.onPressed(buttonPressed); //single press
button.onSequence(2, 500, sequenceEllapsed); //2 press in 500mS - change value if needed
if (button.supportsInterrupt())
{
button.enableInterrupt(buttonISR);
wifi.sendNow("Button will be used through interrupts");
}
}
void loop() {
//button.read(); //remove comment if button don't work by interrupt
if(sensor_on) { //1 press
if(get_distance() < 30) {
blink_red_led(); //red led blink
digitalWrite(ledverde, LOW); //green led off
} else {
digitalWrite(ledverde, HIGH);//green led on
digitalWrite(ledrojo,LOW); //red led off
}
} else { //no measure and set all leds off
digitalWrite(ledverde, LOW);
digitalWrite(ledrojo,LOW);
}
}
ICACHE_RAM_ATTR void buttonISR() {
button.read();
}
void buttonPressed() {
sensor_on=true;
}
void sequenceEllapsed() {
sensor_on=false;
}
unsigned long get_distance() {
digitalWrite(trigger, HIGH); // Prendemos el trigger
delayMicroseconds(10);
digitalWrite(trigger, LOW); // Apagamos el trigger
unsigned long ta = pulseIn(echo, HIGH); // Tiempo que demora en llegar la señal al Echo
ta = ta / 2;
return(ta / 29); // Distancia hasta el obstaculo
}
void blink_red_led() {
digitalWrite(ledverde, LOW);
digitalWrite(ledrojo, !digitalRead(ledrojo);
delay(200);
}

How can I get Ak8963 Address from MPU9250

I try to read the value Who I Am from AK8963 in MPU9250, if I read the values of the accelerometer and the gyroscope in other skecth I have not problems, but When I try to configure the magnetometer first I need to know if there is connection in i2c bus but, If I run i2c Scan always find 0x68-- MPU9250 address but never AK8963 Addres 0X0C, I have already configured Bypass from Int_cpf.. register Address 0x37 with 0x02 here my code always return 255 from value Who I Am from AK8963.
Here my code
#include <Wire.h>
const uint8_t AK8963 = 0X0C;//
const uint8_t WIA = 0X00;
const uint8_t MPU9250 = 0x68;
const uint8_t ACCEL_XOUT_H = 0X3B;//direccion del registro donde se aloja el valor de lectura
acelerometro
const uint8_t SMPLRT_DIV = 0X19;//registro divisor de frecuencia
//la frecuencia de muestreo del sensor es igual a la frecuencia del giroscopio divido
//el valor dado en el registro SMPLRT_DIV + 1
//Frecuencia de muestreo giroscopio output rate/(1+SMPLRT_DIV) = 8KHZ/8 = 1KHZ
const uint8_t CONFIG = 0x1A;//Registro de configuracion de tasas de muestro y filtro acelerometro y giroscopio
const uint8_t USER_CTRL = 0x6A;
const uint8_t SIGNAL_PATH_RESET = 0X68;
const uint8_t FIFO_EN = 0X23;
const uint8_t INT_ENABLE = 0X38;
const uint8_t PWR_MGMT_1 = 0x6B;
const uint8_t PWR_MGMT_2 = 0x6C;
const uint8_t ACCEL_CONFIG = 0X1C;//registro configuracion acelerometro
const uint8_t INT_PIN_CFG = 0X37;
void MPU9260_CONFIG()
{
delay(150);//espero 100 milisegundos
I2CWRITER(MPU9250 , SMPLRT_DIV, 0X07);//Envio el numero 7 al registro
I2CWRITER(MPU9250 , CONFIG, 0X00);//Giroscopio con frecuencia de muestreo de 8KHZ
I2CWRITER(MPU9250 , FIFO_EN, 0X00);
I2CWRITER(MPU9250 , ACCEL_CONFIG , 0x00);
I2CWRITER(MPU9250 , INT_ENABLE, 0X01);
I2CWRITER(MPU9250 , SIGNAL_PATH_RESET, 0x00);
I2CWRITER(MPU9250 , USER_CTRL , 0X00);
I2CWRITER(MPU9250 , PWR_MGMT_1, 0x01);
I2CWRITER(MPU9250 , PWR_MGMT_2, 0x00);
I2CWRITER(MPU9250 , INT_PIN_CFG, 0x02);
}
void I2CWRITER(uint8_t deviceAddress, uint8_t regAdress, uint8_t dato)
{
Wire.beginTransmission(deviceAddress);
Wire.write(regAdress);
Wire.write(dato);
Wire.endTransmission();
}
void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
MPU9250_CONFIG();
}
void loop() {
Wire.beginTransmission(AK8963);
Wire.write(WIA);
Wire.requestFrom(AK8963, 1);
byte c = Wire.read(); // receive a byte as character
Serial.println(c);
delay(500);// print the character
}

When i run my arduino code i get error: 'RightForward' was not declared in this scope. Does anybody know how to solve this?

Hello I am making a robot and the robot is being controlled by serialdata. Somehow i get this error: "RightForward" was not declared in this scope and i don't really know the solution can anyone help? I understand that it can't find RightForward in the code but how can i make it find it.
This is my arduino code:
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <SoftwareSerial.h>
#include <Servo.h>
// put your setup code here, to run once
Servo servo01;
Servo servo02;
Servo servo03;
Servo servo04;
//De code voor de Stepper Motoren
// hier worden de motoren gedefinieerd en de pinnen die ze zullen gebruiken
SoftwareSerial Bluetooth(37, 38);
AccelStepper LeftFrontWheel(1, 40, 41); // links voor wiel
AccelStepper RightFrontWheel(1, 46, 47); // rechts voor wiel
#define led 14
int wheelSpeed = 1500;
const int lfw[50], rfw[50]; // Arrays op posities van de wielen op te slagen
//Geen constanten voor deze volgende 2 rijen ze moeten kunnen worden aangepast
int servo1Pos, servo2Pos, servo3Pos, servo4Pos; // huidige positie
int servo1PPos, servo2PPos, servo3PPos, servo4PPos; // vorige positie
const int servo01SP[50], servo02SP[50], servo03SP[50], servo04SP[50];// om posities op te slagen
const int speedDelay = 20;
const int index = 0;
//hier moet geen constante deze waarde moet kunnen worden aagepast.
int SerialData;
int m = 0;
void setup() {
// de snelheid voor de steppermotoren
LeftFrontWheel.setMaxSpeed(3000);
RightFrontWheel.setMaxSpeed(3000);
//code voor servomotoren (Arm)
//De 4 Servomotoren worden hier gedefinieerd
Serial.begin(9600);
pinMode(led, OUTPUT);
servo01.attach(5);
servo02.attach(6);
servo03.attach(7);
servo04.attach(8);
Bluetooth.begin(38400); // de standaard waarde voor onze bleutooth module
Bluetooth.setTimeout(5);
delay(20);
Serial.begin(38400);
// De arm wordt gezet op zijn eigenlijke basispositie
servo1PPos = 90;
servo01.write(servo1PPos);
servo2PPos = 100;
servo02.write(servo2PPos);
servo3PPos = 120;
servo03.write(servo3PPos);
servo4PPos = 95;
servo04.write(servo4PPos);
}
void loop()
{
//korte uitleg wat er hier gebeurt: wanneer er op een knop in de app wordt geklikt dan geeft deze een nummer
//door. Dat nummer krijgt een commando deze commando's worden hieronder toegewezen.
if (Serial.available() > 0) {
SerialData = Serial.read();
//stoppen van de robot
//switch voor de wielen
switch (SerialData) {
case 0:
m == 0;
break;
//wanneer het getal 1 wordt doorgegeven dan is het commando rightforward. dus gaat de robot naar links.
case 1:
m == 1;
break;
// bij het getal 2 wordt links vooruit gedaan wat ervoor zorgt dat de robot naar rechts gaat
case 2:
m == 2;
break;
// bij het getal 3 wordt de robot achteruit gereden.
case 3:
m == 3;
break;
//Bij het getal 4 wordt de robot voorruit gereden
case 4:
m == 4;
break;
// Servo motor 01 Arm
//omhoog
case 8:
m == 8;
break;
//omlaag
case 9:
m == 9;
break;
//omhoog
// Servo motor 02 Arm
case 10:
m == 10;
break;
//omlaag
case 11:
m == 11;
break;
//Servo motor 03 Arm
//omhoog
case 12:
m == 12;
break;
//omlaag
case 13:
m == 13;
break;
//Servor motor 04 Arm
//omhoog
case 14:
m == 14;
break;
//omloag
case 15:
m == 15;
break;
// knop op de laatste positie te saven
case 16:
m == 16;
break;
}
/* //if (dataIn == 0) {
// m = 0;
//}
//wanneer het getal 1 wordt doorgegeven dan is het commando rightforward. dus gaat de robot naar links.
//if (dataIn == 1)
//{
// m == 1;
//}
// bij het getal 2 wordt links vooruit gedaan wat ervoor zorgt dat de robot naar rechts gaat
// if(dataIn == 2)
//{
//m == 2;
//}
// bij het getal 3 wordt de robot achteruit gereden.
//if (dataIn == 3)
//{
// m == 3;
//}
//Bij het getal 4 wordt de robot voorruit gereden
//if (dataIn == 4)
//{
// m == 4
//}
//}
//Test nummer
//if (dataIn == 5)
//{
// m == 5
//}
//Test nummer
//if (dataIn == 6)
//{
// m == 6
//}
//Test nummer
//if (dataIn == 7)
//{
//m == 7
//}
// Servo motor 01 Arm
//omhoog
// if (dataIn == 8)
//{
// m == 8
//}
//omlaag
//if (dataIn == 9)
//{
// m == 9
//}
//Servo motor 02 arm
//omhoog
//Servo motor 03 arm
//omhoog
//if (dataIn == 12)
{
m == 12
}
//omlaag
if (dataIn == 13)
{
m == 13
}
// knop save positie arm
if (dataIn == 14)
{
m == 14
}*/
if (SerialData != NULL) {
// commando wordt gedeclareerd.
if(m == 1)
{
RightForward();
}
if(m == 2 )
{
LeftForward();
}
if (m == 3)
{
Backward();
}
if (m == 4)
{
Forward();
}
if(m == 0){
StopMoving();
}
}
}
void stopMoving
{
LeftFrontWheel.setspeed(0);
RightFrontWheel.setspeed(0);
}
// als het wiel rightforward rijd dan gaat de robot naar links.
void RightForward
{
LeftFrontWheel.setspeed(0);
RightFrontWheel.setspeed(wheelspeed);
}
// als het wiel leftforward rijd dan gaat de robot rechts
void LeftForward
{
LeftFrontWheel.setspeed(wheelspeed);
RightFrontWheel.setspeed(0);
}
//als de wielen backwards rijden dan rijd de robot naar achter
void Backward
{
LeftFrontWheel.setspeed(-wheelspeed);
RightFrontWheel.setspeed(-wheelspeed);
}
//als de wielen forward rijden dan rijd de naar voren
void Forward
{
LeftFrontWheel.setspeed(wheelspeed);
RightFrontWheel.setspeed(wheelspeed);
}
// de wheelsnelheid wordt hier gedeclareerd
//Arm bewegen
// Motor 01
// beweeg motor 01 omhoog
while (m == 8)
{
if (Serial.available()> 0)
{
m = Serial.read();
}
servo01.write(servo1PPos);
servo1PPos++;
delay(speedDelay);
}
// beweeg motor 01 omlaag
while (m == 9)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo01=write(servoPPos);
servo1PPos--;
delay(speedDelay);
}
//Motor 02
//Beweeg motor 02 omhoog
while (m == 10)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo02.write(servo2PPos);
servo2PPos++;
delay(speedDelay);
}
//Beweeg motor 02 omlaag
while (m == 11)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo02.write(servo2PPos);
servo2PPos--;
delay(speedDelay);
}
//Motor 3
//Beweeg motor 3 omhoog
While ( m == 12)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo03.write(servo3PPos);
servo3PPos++;
delay(speedDelay);
}
//Beweeg motor 3 omlaag
While (m == 13)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo03.write(servo3PPos);
servo3PPos--;
delay(speedDelay);
}
//Motor 4
//Beweeg motor 4 omhoog
While ( m == 14)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo04.write(servo4PPos);
servo4PPos++;
delay(speedDelay);
}
//Beweeg motor 3 omlaag
While (m == 15)
{
if (Serial.available()>0)
{
m = Serial.read();
}
servo04.write(servo4PPos);
servo4PPos--;
delay(speedDelay);
}
// Als arm snelheid veranderd
if (SerialData > 101 & SerialData < 250)
{
// motor snelheid aanpassen
speedDelay = SerialData /10;
}
//stand van de robot opslaan
if (m == 16)
{
if (index == 0) {
LeftFrontWheel.setCurrentPosition(0);
RightFrontWheel.setCurrentPosition(0);
}
lfw[index] = LeftFrontWheel.currentPosition();
rfw[index] = RightFrontWheel.currentPosition();
servo01SP[index] = servo1PPos; // bewaar positie in deze array
servo02SP[index] = servo2PPos;
servo03SP[index] = servo3PPos;
servo04SP[index] = servo4PPos;
index++; // verhoog lijst index
m = 0
}
}
}```
A function declaration or definition also need a list of parameters, or an empty pair or brackets, if there are none.
//als de wielen forward rijden dan rijd de naar voren
void Forward ()
{
LeftFrontWheel.setspeed(wheelspeed);
RightFrontWheel.setspeed(wheelspeed);
}
Functions should not be defined inside other functions.
For others, it's more fun reading complete but small code. Reduce your code to a minimal sketch, still exposing your problem
BTW: Your question is not about Arduino or robot, but about C / C++.

how to make to joysticks work at once on Arduino

I'm making my own controller using Arduino, and I am using 2 joysticks. the first joystick is to move around and the second is to look around. So when I use the first joystick that makes me walk around and then I would like to look around at the same time, but then it won't allow me to do both things at the same time.
I sat both of my joystick" controllers" into a void loop, and I think that's the reason why it doesn't work.
this is the first view i got:
#include <Mouse.h>
#include <Keyboard.h>
int Button1 = 7; // øverste knap
int Button2 = 9; // højre knap
int Button3 = 8; // venstre knap
int Button4 = 10; // nederste knap
//joystick
int horzPin = A1; // For x pin
int vertPin = A2; // For y pin
int selPin = 2; // For knap pin
int vertZero, horzZero; // Gemmer den indledende værdi for hver akse, normalt omkring 512
int vertValue, horzValue; // Gemmer den nuværende værdi af akserne.
int mouseClickFlag = 0; // For musens knap Sprint
int MushorzPin = A3; // For x pin
int MusvertPin = A4; // For y pin
int MusselPin = 3; // For knap pin
int MusvertZero, MushorzZero; // Gemmer den indledende værdi for hver akse, normalt omkring 512
int MusvertValue, MushorzValue; // Gemmer den nuværende værdi af akserne.
const int sensitivity = 200; // Jo højere sensitivity der er jo langsommere er musen. Skulle være omkring 300
int MusmouseClickFlag = 0; // For musens knap
void setup() {
Serial.begin(9600);
pinMode(Button1,INPUT);
joyMovSetup();
joystickMouseSetup();
}
void loop() {
btnHIGH();
btnLOW();
joyStickMouseEngine();
joyMovEngine();
}
this is for the mouse:
bool isPressed = false;
void joystickMouseSetup() {
pinMode(MushorzPin, INPUT); // Sætter pinsene til input
pinMode(MusvertPin, INPUT);
pinMode(MusselPin, INPUT); // sætter knappen pin til input
digitalWrite(MusselPin, HIGH); // Sætter knap pin til høj fordi den ikke er trykket
delay(1000); // Lille kort pause for at få tingene til at fungere
MusvertZero = analogRead(MusvertPin); // Får start positionernes input
MushorzZero = analogRead(MushorzPin); // Joystikket skulle være neutralt når dette forekommer
}
void joyStickMouseEngine() {
MusvertValue = analogRead(MusvertPin) - MusvertZero; // Læser y aksens position
MushorzValue = analogRead(MushorzPin) - MushorzZero; // Læser x aksens position
if (MusvertValue != 0)
Mouse.move(0, MusvertValue/sensitivity, 0); // Rykker musen på y aksen
if (MushorzValue != 0)
Mouse.move(MushorzValue/sensitivity, 0, 0); // Rykker musen på x aksen
if ((digitalRead(MusselPin) == LOW)) // Hvis joystick knappen er trykket
{
if (isPressed == true) {
// Slukker knappen
Keyboard.begin();
Keyboard.release(KEY_LEFT_SHIFT); // Slipper shift
delay(300);
isPressed = false;
return;
} if (isPressed == false) {
Keyboard.begin();
Keyboard.press(KEY_LEFT_SHIFT); // Slipper shift
delay(300);
isPressed = true;
return;
}
}
}
this is to move the player:
void joyMovSetup() {
pinMode(horzPin, INPUT); // Sætter pinsene til input
pinMode(vertPin, INPUT);
pinMode(selPin, INPUT); // sætter knappen pin til input
digitalWrite(selPin, HIGH); // Sætter knap pin til høj fordi den ikke er trykket
delay(1000); // Lille kort pause for at få tingene til at fungere
vertZero = analogRead(vertPin); // Får start positionernes input
horzZero = analogRead(horzPin); // Joystikket skulle være neutralt når dette forekommer
}
void joyMovEngine() {
int sensorValueX = analogRead(horzPin);
int sensorValueY = analogRead(vertPin);
if (sensorValueY < 20){
Keyboard.press('w');
delay(20);
Keyboard.release('w');
}
else if(sensorValueX < 20){
Keyboard.press('a');
delay(20);
Keyboard.release('a');
}
else if(sensorValueY > 1000){
Keyboard.press('s');
delay(20);
Keyboard.release('s');
}
else if(sensorValueX > 1000){
Keyboard.press('d');
delay(20);
Keyboard.release('d');
}
if ((digitalRead(selPin) == 0) && (!mouseClickFlag)) // Hvis joystick knappen er trykket
{
mouseClickFlag = 1;
Keyboard.begin();
Keyboard.press(KEY_LEFT_CTRL); // Trykker på shift
}
if ((digitalRead(selPin))&&(mouseClickFlag)) // Hvis joystick knappen ikke er trykket
{
mouseClickFlag = 0;
Keyboard.begin();
Keyboard.release(KEY_LEFT_CTRL); // Slipper shift
}
}
You can try using interrupts. To do this tap the joystick's analog outputs and connect them to interrupt enabled pins on your Arduino. Then set the interrupts to work either when it detects a rising input or a falling input.
You can also try FreeRTOS which will enable you read two joysticks at a time.

Got NaN answer from DHT22

I am trying to read temperature and humidity from a DHT22, here is the code:
#include "fsm_config.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define DHTPIN D4 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
const int buttonPin = D5; // definicao do pino utilizado pelo botao
const int ledPin = D7; // definicao do pino utilizado pelo led
const char* ssid = "augusto-Aspire-E5-571"; // id da rede
const char* password = "sLPCwZqX"; // senha da rede
const char* mqtt_server = "things.ubidots.com"; // server
int buttonState = LOW; // armazena a leitura atual do botao
int lastButtonState = LOW; // armazena a leitura anterior do botao
unsigned long lastDebounceTime = 0; // armazena a ultima vez que a leitura da entrada variou
unsigned long debounceDelay = 50; // tempo utilizado para implementar o debounce
float umidade; //Stores humidity value
float temperatura; //Stores temperature value
String hum = "{\"value\":";
String temp = "{\"value\":";
char humChar[50];
char tempChar[50];
WiFiClient espClient;
PubSubClient client(espClient);
int lastMsg = 1000;
int now;
char msg[60];
char msg1[60];
int send_data() {
dht.begin();
umidade = dht.readHumidity();
temperatura = dht.readTemperature();
//Print temp and humidity values to serial monitor
Serial.print("Humidity: ");
Serial.print(umidade);
Serial.print(" %, Temp: ");
Serial.print(temperatura);
Serial.println(" Celsius");
temp.concat(temperatura);
temp.concat("}");
hum.concat(umidade);
hum.concat("}");
temp.toCharArray(tempChar, 50);
hum.toCharArray(humChar, 50);
String hum = "{\"value\":";
String temp = "{\"value\":";
client.publish("/v1.6/devices/wemos/umidade", humChar);
client.publish("/v1.6/devices/wemos/temp", humChar);
delay(10000); //Delay 2 sec.
return true;
}
But I only got "NaN" as answer, what should happened? I've looked for some other questions here but none was useful for me.
Here the link for the image of the connections:
NaN stands for "Not a Number". Sometimes the sensor fails to read and gives you a nan value. You can't do anything against it, but in the DHT.h library is a function called isnan(). So you can make a backup variable were you store the last value that was correct. Then you can check if your sensor reads nan and if he does you can print out the backup variable:
float temperature;
float bTemperature;
temperature = dht.readTemperature();
if(!isnan(temperature)){
bTemperature = temperature;
Serial.println(temperature);
}
else{
Serial.println(bTemperature);
}

Resources