I am building a Sumo robot, I am using 3 HCRSO4 ultrasonic sensors and e TRC5000 change color detectors, all this over an Arduino Mega with Two IBT_2 H bridges. I have probles with this code because I don´t know what is not working. Can sombedody give me a hand?
`
#include <BTS7960.h>
#define L_EN 48
#define R_EN 49
#define L_PWM 3
#define R_PWM 4
#define LineaR 41
#define LineaL 27
#define LineaB 32
int ledr=25;
int leda=26;
int Estado=0;
int SLineaR; //sensor de linea delantero derecho
int SLineaL; //sensor de linea delantero izquierdo
int SLineaB; //sensor de linea trasero
#define L_EN_R 50
#define R_EN_R 51
#define L_PWM_R 5
#define R_PWM_R 6
BTS7960 motor1(L_EN, R_EN, L_PWM, R_PWM); //motor izquierdo
BTS7960 motor2(L_EN_R, R_EN_R, L_PWM_R, R_PWM_R); //motor derecho
#include <EasyUltrasonic.h>
int TRIGPIN_F=8;
int ECHOPIN_F=9;
EasyUltrasonic ultrasonic_F; //ultrasonico frontal
int TRIGPIN_L=10;
int ECHOPIN_L=11;
EasyUltrasonic ultrasonic_L; //ultrasonico izquierdo
int TRIGPIN_R=12;
int ECHOPIN_R=13;
EasyUltrasonic ultrasonic_R; //ultrasonico derecho
void setup() {
pinMode(ledr,OUTPUT);
pinMode(leda,OUTPUT);
//ARRANQUE MOTOR
Serial.begin(9600);
motor1.begin();
motor1.enable();
motor2.begin();
motor2.enable();
//ARRANQUE ULTRASÓNICOS
ultrasonic_F.attach(TRIGPIN_F,ECHOPIN_F);
ultrasonic_L.attach(TRIGPIN_L,ECHOPIN_L);
ultrasonic_R.attach(TRIGPIN_R,ECHOPIN_R);
//ARRANQUE SENSORES DE LINEA
pinMode(LineaR, INPUT);
pinMode(LineaL, INPUT);
pinMode(LineaB, INPUT);
delay(5000);
}
void adelante(){
motor1.pwm=255;
motor1.front();
motor2.pwm=255;
motor2.back();
Serial.println("ADELANTE");
}
void izquierda(){
motor1.pwm=255;
motor1.back();
motor2.pwm=255;
motor2.back();
Serial.println("IZQUIERDA");
}
void derecha(){
motor1.pwm=255;
motor1.front();
motor2.pwm=255;
motor2.front();
Serial.println("DERECHA");
}
void reversa(){
motor1.pwm=255;
motor1.back();
motor2.pwm=255;
motor2.front();
Serial.println("REVERSA");
}
void MapeoFrontal(){
SLineaR=digitalRead(LineaR);
SLineaL=digitalRead(LineaL);
SLineaB=digitalRead(LineaB);
int distanceIN_F= ultrasonic_F.getDistanceIN();
int distanceCM_F= convertToCM(distanceIN_F);
Serial.print("DISTANCIA FRONTAL: ");
Serial.println(distanceCM_F);
if (distanceCM_F > 0 && distanceCM_F <=50 && SLineaR == Estado && SLineaL == Estado && SLineaB == Estado){
adelante();
Serial.println("ENCONTRE ALGO ADELANTE");
}
}
void MapeoIzquierda(){
SLineaR=digitalRead(LineaR);
SLineaL=digitalRead(LineaL);
SLineaB=digitalRead(LineaB);
int distanceIN_L= ultrasonic_L.getDistanceIN();
int distanceCM_L= convertToCM(distanceIN_L);
Serial.print("DISTANCIA IZQUIERDA: ");
Serial.println(distanceCM_L);
if (distanceCM_L > 0 && distanceCM_L <=50 && SLineaR == Estado && SLineaL == Estado && SLineaB == Estado){
izquierda();
Serial.println("ENCONTRE ALGO A LA IZQUIERDA");
}
}
void MapeoDerecha(){
SLineaR=digitalRead(LineaR);
SLineaL=digitalRead(LineaL);
SLineaB=digitalRead(LineaB);
int distanceIN_R= ultrasonic_R.getDistanceIN();
int distanceCM_R= convertToCM(distanceIN_R);
Serial.print("DISTANCIA DERECHA: : ");
Serial.println(distanceCM_R);
if (distanceCM_R > 0 && distanceCM_R <=50 && SLineaR == Estado && SLineaL == Estado && SLineaB == Estado){
derecha();
Serial.println("ENCONTRE ALGO A LA DERECHA");
}
}
void LineasFrente(){
SLineaR=digitalRead(LineaR);
SLineaL=digitalRead(LineaL);
if(SLineaR ==Estado || SLineaL ==Estado){
reversa();
Serial.println("LINEA BLANCA AL FRENTE");
}
}
void LineaTrasera(){
SLineaB=digitalRead(LineaB);
if(SLineaB !=Estado){
adelante();
Serial.println("LINEA BLANCA ATRÁS");
}
}
void Busqueda(){
int SLineaR=0;
int SLineaL=0;
int SLineaB=0;
SLineaR=digitalRead(LineaR);
SLineaL=digitalRead(LineaL);
SLineaB=digitalRead(LineaB);
int distanceIN_F= ultrasonic_F.getDistanceIN();
int distanceCM_F= convertToCM(distanceIN_F);
int distanceIN_L= ultrasonic_L.getDistanceIN();
int distanceCM_L= convertToCM(distanceIN_L);
int distanceIN_R= ultrasonic_R.getDistanceIN();
int distanceCM_R= convertToCM(distanceIN_R);
if(distanceCM_R>80 && distanceCM_F>80 && distanceCM_L>80 && SLineaR == Estado && SLineaL == Estado && SLineaB==Estado);
Serial.println("Buscando");
izquierda2();
delay(50);
adelante2();
delay(100);
derecha2();
delay(50);
reversa2();
delay(100);
}
void luz(){
digitalWrite(ledr,HIGH);
digitalWrite(leda,LOW);
delay(70);
digitalWrite(ledr,LOW);
digitalWrite(leda,HIGH);
delay(70);
}
void loop() {
luz();
delay(1);
Busqueda();
delay(1);
MapeoFrontal();
delay(1);
MapeoIzquierda();
delay(1);
MapeoDerecha();
delay(1);
LineasFrente();
delay(1);
LineaTrasera();
delay(1);
adelante();
delay(5000);
reversa();
delay(5000);
}
`
I have already checked the wires, everything is well conected, every sensor was tested and each of the are working perfectly.
This image show the output in the serial monitor
I am expecting that somebody finds the erros I cant see and try to fix my code or someonte that help me building a new code that workes only with the front ultrasonic sensor and the change colors detectors.
You'll need to provide a lot more detail into the problem you want the community to help you solve. We can't debug your entire program that you say "is not working" without any details about what is not working.
I suggest you start with the first function you believe is not working properly and provide a minimally reproducible example.
Related
I am trying to measurer distance with ultrasonic sensor, for each 10 centimeters a wav file is playing from micro SD. the ultrasonic sensor is working fine alone. but when connected with micro SD and by using tmrpcm library to play sound at some range the measurement is giving wrong distances.
this is my code.
#include "SD.h"
#include "TMRpcm.h"
#include "SPI.h"
const int EchoM = 6;
const int TriggerM = 5;
float distanceM;
unsigned long durationM;
const int SD_ChipSelectPin = 4;
TMRpcm tmrpcm;
void setup()
{
tmrpcm.speakerPin = 9;
Serial.begin(9600);
pinMode(TriggerM, OUTPUT);
digitalWrite(TriggerM, LOW);
pinMode(EchoM, INPUT);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}
tmrpcm.setVolume(5);
}
void loop() {
digitalWrite(TriggerM, HIGH);
delayMicroseconds (50);
digitalWrite(TriggerM, LOW);
durationM = pulseIn(EchoM, HIGH);
distanceM = durationM / 58.0;
if (distanceM >= 1 && distanceM <= 9 ) {
Serial.println(distanceM, 1);
delay(900);
m5();
delay(800);
}
if (distanceM >= 10 && distanceM <= 19 ) {
Serial.println(distanceM, 1);
delay(900);
m15();
delay(800);
}
if (distanceM >= 20 && distanceM <= 29 ) {
Serial.println(distanceM, 1);
delay(900);
m25();
delay(800);
}
if (distanceM >= 30 && distanceM <= 39 ) {
Serial.println(distanceM, 1);
delay(900);
m35();
delay(800);
}
if (distanceM >= 40 && distanceM <= 49 ) {
Serial.println(distanceM, 1);
delay(900);
m45();
delay(800);
}
}
const int vdelay = 400;
void m5() {
tmrpcm.play("m5.wav");
delay (vdelay);
}
void m15() {
tmrpcm.play("m15.wav");
delay (vdelay);
}
void m25() {
tmrpcm.play("m25.wav");
delay (vdelay);
}
void m35() {
tmrpcm.play("m35.wav");
delay (vdelay);
}
void m45() {
tmrpcm.play("m45.wav");
delay (vdelay);
}
I found a solution. the problem was the pulseIn is not accurate when there are multiple libraries. so, I used NewPing library instead and it worked just as I wanted.
I am using the ESP8266 Wi-Fi shield to connect Arduino to the cayenne server. However once connect the chip to the access point it will heat up and sometimes will lagging. After that, it shows some message but the Cayenne server didn't connect to the Arduino. Every widget can not be operated (No response when clicking a button, temperature value unchanged, etc.). Can anyone solve this issue? It is important for my course work. I am using Arduino Uno and ESP8266 ESP-01 chip. We have tried different styles of code to upload data to cayenne server but they didn't work(Below include 3 versions)
Finale 1 Version(Cayenne out) :
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
Serial.print(myRTC.dayofmonth);
Serial.print('/');
Serial.print(myRTC.month);
Serial.print('/');
Serial.print(myRTC.year);
Serial.print('/');
Serial.print(' ');
Serial.print(myRTC.hours);
Serial.print(':');
Serial.print(myRTC.minutes);
Serial.print(':');
Serial.print(myRTC.seconds);
Serial.print('\n');
Serial.print(PowerInDay);
Serial.print(' ');
Serial.print(PowerInMonth);
Serial.print('\n');
}
CAYENNE_OUT(temp_sensor)
{
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
}
CAYENNE_OUT(Power_sensor)
{
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
}
CAYENNE_OUT(DayPower) {
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
}
CAYENNE_OUT(MonthPower) {
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Finale 2 Version(Cayenne out_Default):
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
Serial.print(myRTC.dayofmonth);
Serial.print('/');
Serial.print(myRTC.month);
Serial.print('/');
Serial.print(myRTC.year);
Serial.print('/');
Serial.print(' ');
Serial.print(myRTC.hours);
Serial.print(':');
Serial.print(myRTC.minutes);
Serial.print(':');
Serial.print(myRTC.seconds);
Serial.print('\n');
Serial.print(PowerInDay);
Serial.print(' ');
Serial.print(PowerInMonth);
Serial.print('\n');
}
CAYENNE_OUT_DEFAULT()
{
//Temp sensor-----------------------------------------
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
//Temp sensor-----------------------------------------
//Power sensor-------------------------------------------------
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
//Power sensor-------------------------------------------------
//Power Day-------------------------------------------------
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
//Power Month-------------------------------------------------
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Finale 3 Version(Send data with time difference):
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
int lastMillis = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
// Serial.print(myRTC.dayofmonth);
// Serial.print('/');
// Serial.print(myRTC.month);
// Serial.print('/');
// Serial.print(myRTC.year);
// Serial.print('/');
// Serial.print(' ');
// Serial.print(myRTC.hours);
// Serial.print(':');
// Serial.print(myRTC.minutes);
// Serial.print(':');
// Serial.print(myRTC.seconds);
// Serial.print('\n');
// Serial.print(PowerInDay);
// Serial.print(' ');
// Serial.print(PowerInMonth);
// Serial.print('\n');
if(millis() - lastMillis > 10000 && millis() - lastMillis < 20000 ) {//Send data between 10 - 20 seconds
//Temp sensor-----------------------------------------
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
//Temp sensor-----------------------------------------
}
if(millis() - lastMillis > 20000 && millis() - lastMillis < 30000 ) {//Send data between 20 - 30 seconds
//Power sensor-------------------------------------------------
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
//Power sensor-------------------------------------------------
}
if(millis() - lastMillis > 30000 && millis() - lastMillis < 40000 ) {//Send data between 30 - 40 seconds
//Power Day-------------------------------------------------
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
}
if(millis() - lastMillis > 40000 && millis() - lastMillis < 50000 ) {//Send data between 40 - 50 seconds
//Power Month-------------------------------------------------
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
lastMillis = millis();
}
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Serial monitor message:
AT
ATE0
AT+CIPMUX=1
AT+CWMODE?
AT+CWJAP="TP-LINK_MWNg","mwngpass"
[5618] Connected to WiFi
[5619] Connecting to mqtt.mydevices.com:1883
AT+CIPSTART=1,"TCP","mqtt.mydevices.com",1883
[15636] Network connect failed
AT+CIPSTART=1,"TCP","mqtt.mydevices.com",1883
AT+CIPSEND=1,40
MQIsdp
9c6b2/things/743674368676328742somenumbersAT+CIPSEND=1,16
e7f5ba423/cmd/+
AT+CIPSEND=1,40
AT+CIPSEND=1,40
AT+CIPSEND=1,40
AT+CIPSEND=1,40
1i Zv1/743674368676328742somenumbersAT+CIPSEND=1,40
6b2/things/743674368676328742somenumbersAT+CIPSEND=1,27
f5ba423/data/4temp,c=28.125sensor = 0 output = 0.000
Power =0.000
AT+CIPSEND=1,40
1g
If your module is getting warm its probably a hardwareissue.I guess you use 5V for the esp module which is bad as it only needs 3.3V. It might survive 5V for a short time(moment) but don't stretch your luck. So you have to convert 5V ro 3.3V level shifter. You can not use the Arduino 3.3V output pin because it can not provide the power needed by the ESP (up to 250mA) vs. max 50mA on the Arduino (UNO) 3.3V pin.
The schematic shortly explained:
The ESP's VCC pin is powered by the 3.3V output pin of the voltage regulator (AMS1117 in the grphic).
The 10uF capacitor is connected to the output pins to stabilize the regulator.
The CH_PD pin must also be connected to 3.3V.
The GND pin is obviously connected to ground.
The ESP's TXD pin can be connected directly to the RX pin of Arduino (emulated on pin 6).
The ESP's RXD pin is connected to the TX pin of Arduino (emulated on pin 7) through the level shifter.
The last two can be changed depending if you use hardware or software serial EDIT
As you use rtc it makes no sense to update the time every loop this will crash your connection. Either do it every x hours and make sure with if/else that nochyenne loop() is running. It makes no sense to sync time every x millis() the syncing of time every hourisenough foryour scenario, I would go for once a day
I've connected arduino to 4 different modules :
RTC
GPRS shield ( SARA G350 )
Wind vane
Anemometer
Everytime I launch my system the GPRS doesn't send anything unless I disconnect my anemometer.
I've tried the anemometer code on standalone and it works, I think the GPRS doesn't get enough power to send data when the anemometer is connected but how I'm not sure.
#include <SoftwareSerial.h>
#include <Wire.h>
#include <ds3231.h>
struct ts t;
String Angle;
int serial_in;
double x = 0;
double y = 0;
double a = 0;
double b = 0;
const int sensorPin = A5;
const int numReadings = 10;
int readings[numReadings];
int readIndex = 0;
int totalWind= 0;
int averageWind = 0;
int inputPin = A5;
int sensorValue = 0;
float sensorVoltage = 0;
float sensorVoltage2 = 0;
float windSpeed = 0;
float voltageConversionConstant = .004882814;
int sensorDelay = 2000;
float voltageMin = .4;
float windSpeedMin = 0;
float voltageMax = 2.0;
float windSpeedMax = 32;
SoftwareSerial mySerial(2, 3); //Tx & Rx sont connectés aux broches Arduino #7 et #8
void setup()
{
delay(15000);
Wire.begin();
DS3231_init(DS3231_INTCN);
//Commence la communication Serie
//Commence la communication Serie Arduino-Shield GPRS
mySerial.begin(9600);
delay(1000);
mySerial.println("AT"); //Handshaking
updateSerial();
mySerial.println("AT+UPSDA=2,0"); //Reset connexion
updateSerial();
delay(2000);
mySerial.println("AT+UPSD=2,1,\"sl2sfr\""); //Establissement de connexion avec l'APN
updateSerial();
delay(2000);
mySerial.println("AT+UPSDA=2,3");
updateSerial();
delay(2000);
mySerial.println("AT+UPSND=2,0");
updateSerial();
delay(2000);
}
void loop()
{
mySerial.println("AT+UPSDA=2,0"); //Reset connexion
updateSerial();
delay(2000);
mySerial.println("AT+UPSD=2,1,\"sl2sfr\""); //Establissement de connexion avec l'APN
updateSerial();
delay(2000);
mySerial.println("AT+UPSDA=2,3");
updateSerial();
delay(2000);
mySerial.println("AT+UPSND=2,0");
updateSerial();
delay(2000);
String Equipement = "STAINS";
mySerial.println("AT+UHTTP=0");
updateSerial();
delay(2000);
mySerial.println("AT+UHTTP=2,1,\"www.projetwmr.site\""); // Parametrage URL d'acces
updateSerial();
delay(2000);
String command = "AT+UHTTPC=2,5,\"/add.php\",\"post.ffs\",\"vite="; // Commande d'envoi des donnes via POST sur PHP
anemometre(); // Recuperation des données ANALOGIQUES
// convertion valeurs en String - Chaîne de caractères
command += String(windSpeed);
// or convertion précise
// command += String(Windspeed, 2);
command += "&equipement=";
command += String(Equipement);
DS3231_get(&t);
String heure = String(t.hour);
heure += ":";
heure += String(t.min);
heure += ":";
heure += String(t.sec);
String Date = String(t.year);
Date += "-";
Date += String(t.mon);
Date += "-";
Date += String(t.mday);
command += "&time=";
command += String(heure);
command += "&date=";
command += String(Date);
command += "&dire=";
girouette();
command += String(Angle);
command += "\",0"; //Fin de la commande PHP POST
mySerial.println(command);
updateSerial();
delay(45000);
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
}
while(mySerial.available())
{
Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
}
}
void girouette()
{
int sensorValue = analogRead(A1);
if (sensorValue >= 89 && sensorValue<=95 )
{ Angle="0°"; }
if (sensorValue >=60 && sensorValue<=70 )
{ Angle="22.5°"; }
if (sensorValue >=180 && sensorValue<=190 )
{ Angle="45°"; }
if (sensorValue >= 124 && sensorValue<=130 )
{ Angle="67.5°"; }
if (sensorValue >= 285 && sensorValue<=292 )
{ Angle="90°"; }
if (sensorValue >=240 && sensorValue<=250 )
{ Angle="115.5°"; }
if (sensorValue >= 630 && sensorValue<=640 )
{ Angle="135°"; }
if (sensorValue >= 600 && sensorValue<=610 )
{ Angle="157.5°"; }
if (sensorValue >=940 && sensorValue<=952 )
{ Angle="180°"; }
if (sensorValue >=825 && sensorValue<= 840 )
{ Angle="202.5°"; }
if (sensorValue >= 880 && sensorValue<= 898 )
{ Angle="225°"; }
if (sensorValue >= 700 && sensorValue<= 712 )
{ Angle="247.5°"; }
if (sensorValue >= 785 && sensorValue<= 795 )
{ Angle="270°"; }
if (sensorValue >= 405 && sensorValue<= 415)
{ Angle="292.5°"; }
if (sensorValue >= 460 && sensorValue<= 470 )
{ Angle="315°"; }
if (sensorValue >= 78 && sensorValue<=87 )
{ Angle="337.5°"; }
if (sensorValue >= 1000 && sensorValue<=50 )
{ Angle="Error"; }
delay(100);
}
void anemometre()
{
sensorValue = analogRead(A5);
totalWind = totalWind - readings[readIndex];
readings[readIndex] = sensorValue;
totalWind = totalWind + readings[readIndex];
readIndex = readIndex + 1;
sensorVoltage2 = sensorValue * voltageConversionConstant;
if (readIndex >= numReadings) {
readIndex = 0;
averageWind = totalWind / numReadings;
sensorVoltage = averageWind * voltageConversionConstant;
if (sensorVoltage <= voltageMin) {
windSpeed = 0;
} else {
windSpeed = ((sensorVoltage - voltageMin) * windSpeedMax / (voltageMax - voltageMin))*1.55;
}
}
x = windSpeed;
if (x >= y) {
y = x;
} else {
y = y;
}
a = sensorVoltage;
if (a >= b) {
b = a;
} else {
b = b;
}
}
If you don't have a reason to use it, you should avoid SoftwareSerial, it is known to be quite inefficient and it's most likely leading to issues with the other libraries you're loading.
Always use hardware serial ports if you have them available. See here for alternatives.
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.
Am trying to make a smart cane for blind ppl using 2 ultrasonic sensors
to detect obstacles, and use a buzzer and a flat vibrating motor as a feedback when an obstacle is detected, where the flat motor should be ON when an obstacle
between 1m - 3m is detected, and the buzzer when it's less than 1m.
now recently i used the NewPing library which solved some of the problems but
the code doesn't do exactly what i want, instead it triggers both the buzzer and motor together when object detected, i'd appreciate it if anyone could help.
#include <NewPing.h>
const int trigPin = 8;
const int trigPin1 = 13;
const int echoPin = 9;
const int echoPin1 = 12;
const int buzzer = 5;
const int motor = 3;
NewPing sonar1(trigPin,echoPin,maxout);
NewPing sonar2(trigPin1,echoPin1,maxout);
// defines variables
long duration;
long duration1;
int distance;
int distance1;
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(motor, OUTPUT);
Serial.begin(9600);
}
void loop() {
distance = sonar1.ping_cm();
distance1 = sonar2.ping_cm();
if (distance > 100 || distance1 > 100) {
digitalWrite(buzzer,LOW);
digitalWrite(motor,HIGH);
}
else if (distance <= 100 || distance1 <= 100) {
digitalWrite(buzzer,HIGH);
digitalWrite(motor,LOW);
}
Serial.print("Distance1: ");
Serial.println(distance);
Serial.print("Distance2: ");
Serial.println(distance1);
}
this is the ultrasonic pins:
first sensor (Vcc = 5V, trig = 8, echo = 9, GND = GND)
second sensor(Vcc = 5V, trig = 13 , echo = 12 , GND = GND)
and this is the buzzer and motor pins:
buzzer = 5 , GND
motor = 3 , GND
Separate the logic for the motor and the buzzer:
if (distance >= 100 && distance <= 300) {
// Motor on
digitalWrite(motor, HIGH);
}
else {
// Motor off
digitalWrite(motor, LOW);
}
if (distance1 < 100) {
// Buzzer on
digitalWrite(buzzer, HIGH);
}
else {
// Buzzer off
digitalWrite(buzzer, LOW);
}