How can I get Ak8963 Address from MPU9250 - arduino

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
}

Related

Send limited SMS (SIM800L) Arduino [closed]

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");
}
//====================================================================

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);
}

74HC595 Shift register with Arduino

I am using shift register with Arduino to increase my Output pins. Here I want to edit each serial bit individualy and store it. In Short I want to control each pin of register as we use Arduino I/O pins. I try to do it with the following programe but it is not working.
#include<ShiftOutX.h>
#include<ShiftPinNo.h>
// Define Connections to 74HC595
// ST_CP pin 12
const int latchPin = 10;
// SH_CP pin 11
const int clockPin = 11;
// DS pin 14
const int dataPin = 12;
String S1 = "1";
String S2 = "0";
String S3 = "0";
String S4 = "0";
String S5 = "0";
String S6 = "0";
String S7 = "0";
String S8 = "0";
String S9 = "0";
String S10 = "1";
String S11 = "0";
String S12 = "0";
String S13 = "0";
String S14 = "0";
String S15 = "0";
String S16 = "0";
String S17 = "0";
String S18 = "0";
String S19 = "0";
String S20 = "1";
String S21 = "0";
String S22 = "0";
String S23 = "0";
String S24 = "0";
String S25 = "0";
String SB = "b";
String S = "0";
shiftOutX reg(latchPin, dataPin, clockPin, LSBFIRST, 3);
void setup ()
{
// Setup pins as Outputs
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(latchPin, HIGH);
String one =S+SB+ S1+ S2+ S3+ S4+ S5+ S6+ S7+ S8+ S9+ S10+ S11+ S12+ S13+ S14+ S15+ S16+ S17+ S18+ S19+ S20+ S21+ S22+ S23+ S24+ S25;
Serial.println(one);
char buf[27];
one.toCharArray(buf,one.length());
Serial.println(buf);
shiftOut_24(dataPin, clockPin, LSBFIRST, buf);
digitalWrite(latchPin, LOW);
digitalWrite(latchPin, HIGH);
delay(1000);
}
"0b1000000001000000000100000
0b100000000100000000010000"
I get the above out put on serial screen but output of the register is different. Please give me some solution.
I understand you want to chain 3 shift registers
byte data[3] = {0b01000000, 0b00100000, 0b00100000 };
void shiftOut24(byte* data) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin,MSBFIRST,data[2]);
shiftOut(dataPin, clockPin,MSBFIRST,data[1]);
shiftOut(dataPin, clockPin,MSBFIRST,data[0]);
digitalWrite(latchPin, 1);
}
void debugPrint24(byte* data) {
// TODO print more nicely
// leading zeros by adding bit 24 currently
long out = 1L<<24;
out |= (long)data[0] | (long)data[1] << 8 | (long)data[2] << 16;
Serial.println(out,BIN);
}
byte pos = 0; // 0 .. 23 for test data
void loop() {
debugPrint24(data);
shiftOut24(data);
// adding test data for fun
byte b = pos / 8;
if (b > 2) b = pos = data[0] = data[1] = data[2] = 0;
data[b] |= 1 << (pos++ & 7); // set another bit for next round
delay(1000);
}
Just some demo code to set single bits.
I got a code from the net and I think it could work well. It is easy to use and I was able to control each pin individualy. Below is the code:
// Arduino-Pin verbunden mit SH_CP des 74HC595
int shiftPin = 11;
// Arduino-Pin verbunden mit ST_CP des 74HC595
int storePin = 10;
// Arduino-Pin verbunden mit DS des 74HC595
int dataPin = 12;
// Dieses Muster soll ausgegeben werden
int muster[24] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
void Send_Data(){
// storePin sicherheitshalber auf LOW
digitalWrite(storePin, LOW);
for (int i=0; i<24; i++) {
// Zuerst immer alle 3 Pins auf LOW
// Aktion passiert bei Wechsel von LOW auf HIGH
digitalWrite(shiftPin, LOW);
// Jetzt den Wert der aktuellen Stelle ans Datenpin DS anlegen
digitalWrite(dataPin, muster[i]);
// Dann ShiftPin SHCP von LOW auf HIGH, damit wird der Wert
// am Datenpin ins Register geschoben.
digitalWrite(shiftPin, HIGH);
}
// Wenn alle 8 Stellen im Register sind, jetzt das StorePin STCP
// von LOW auf HIGH, damit wird Registerinhalt an Ausgabepins
// kopiert und der Zustand an den LEDs sichtbar
digitalWrite(storePin, HIGH);
}
void setup() {
// Pins 8,9,10 auf Ausgabe
pinMode(storePin, OUTPUT);
pinMode(shiftPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop () {
muster[0] = 1;
Send_Data();
delay(1000);
muster[15] = 1;
Send_Data();
delay(1000);
muster[23] = 1;
Send_Data();
delay(1000);
muster[0] = 0;
Send_Data();
delay(1000);
muster[15] = 0;
Send_Data();
delay(1000);
muster[23] = 0;
Send_Data();
delay(1000);
}
Please keep me updating if any one come across more easy way to do it.

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