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.
Related
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 need help. I have done some research and my little understanding of keypad scanning is that the ShiftIn value of Input Column should return zero (0) when a keypad button is pressed. Mine is only returning 255 (or 11111111) in BIN. All I need is to track the zero value when a key is pressed and then scan the keys matrix to display the pressed key. I will appreciate any help. I have added my code and schematic.
]1
const int kbdRows = 4;
const int kbdCols = 4;
int LatchIn = 2; //165 pin1
int ClockPin = 3; // 595 pin11 & 165 pin2
int DataIn = 4; //165 pin9
int LatchOut = 5; // 595 pin12
int DataOut = 6; //595 pin14
int led = 7;
int PinState = 0;
char keys[kbdRows][kbdCols] = {
{ '1','2','3','4' },
{ '5','6','7','8' },
{ '9','0','A','B' },
{ 'C','D','E','F' }
};
byte KeyIsDown() {
int row;
int col;
int rowBits;
int colBits;
rowBits = 0X10;
for (row = 0; row < kbdRows; row++) {
digitalWrite(ClockPin, LOW);
digitalWrite(LatchOut, LOW);
shiftOut(DataOut, ClockPin, LSBFIRST, rowBits);
digitalWrite(LatchOut, HIGH);
delay(5);
digitalWrite(ClockPin, HIGH);
digitalWrite(LatchIn, LOW);
delay(5);
digitalWrite(LatchIn, HIGH);
colBits = shiftIn(DataIn, ClockPin, LSBFIRST);
for (col = 0; col < kbdCols; col++) {
if (colBits==0) {
// not sure what condition to put here
byte keypressed = keys[kbdRows][kbdCols]; here
// I know this is the right stuff to return here
}
return colBits;
colBits = colBits >> 1;
}
rowBits = rowBits << 1;
}
}
void setup() {
pinMode(ClockPin, OUTPUT);
pinMode(DataOut, OUTPUT);
pinMode(DataIn, INPUT_PULLUP);
pinMode(LatchOut, OUTPUT);
pinMode(LatchIn, OUTPUT);
digitalWrite(LatchOut, HIGH);
digitalWrite(LatchIn, HIGH);
Serial.begin(9600);
digitalWrite(led, HIGH);
}
void loop() {
byte retColBit = KeyIsDown();
Serial.print("ColBit: ");
Serial.println(retColBit,BIN);
delay(500);
PinState = digitalRead(DataOut);
Serial.print("DataOut: ");
Serial.println(PinState,BIN);
delay(500);
}
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);
}
I am having a problem with my relay switches. I have a 5V, four relay switch for use with an Arduino. I am trying to make it so that when I push a button, one relay goes on and then, when I press it again, the same relay goes off.
This concept works with the code when using one relay. However, the problem is that my code works for one relay and one relay only. If I change the code and make multiple variables, it will not work.
FYI, I am using an Arduino UNO R3 ATmega 328
Keep in mind that this first code does work, but only for one relay. It works when I press the button to turn it on and then pressing the button again turns it off.
const int rl1 = 7;
const int rl2 = 12;
const int rl3 = 2;
const int rl4 = 8;
const int button1 = 11;
const int button2 = 10;
const int button3 = 3;
const int button4 = 4;
int rl1State = LOW;
int rl2State = LOW;
int rl3State = LOW;
int rl4State = LOW;
int buttonState = LOW;
int lastButtonState = HIGH;
int reading;
long lastDebounceTime=0;
long debounceDelay = 50;
void setup() {
Serial.begin(9600);
pinMode(rl1, OUTPUT);
pinMode(rl2, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
pinMode(button4, INPUT);
}
void loop() {
reading = digitalRead(button1);
if(reading != lastButtonState){
lastDebounceTime = millis();
lastButtonState = reading;
}
if((millis() - lastDebounceTime) > debounceDelay){
if(buttonState != lastButtonState){
buttonState = lastButtonState;
if(buttonState == HIGH){
rl1State = !rl1State;
digitalWrite(rl1, rl1State);
}
}
}
}
I tried this code for multiple relays:
const int rl1 = 7;
const int rl2 = 12;
const int rl3 = 2;
const int rl4 = 8;
const int button1 = 11;
const int button2 = 10;
const int button3 = 3;
const int button4 = 4;
int rl1State = LOW;
int rl2State = LOW;
int rl3State = LOW;
int rl4State = LOW;
//States
int buttonState1 = LOW;
int lastButtonState1 = HIGH;
int buttonState2 = LOW;
int lastButtonState2 = HIGH;
int buttonState3 = LOW;
int lastButtonState3 = HIGH;
int buttonState4 = LOW;
int lastButtonState4 = HIGH;
//Read State
int reading1;
int reading2;
int reading3;
int reading4;
long lastDebounceTime1=0;
long debounceDelay1 = 50;
long lastDebounceTime2=0;
long debounceDelay2 = 50;
long lastDebounceTime3=0;
long debounceDelay3= 50;
long lastDebounceTime4=0;
long debounceDelay4 = 50;
void setup() {
Serial.begin(9600);
pinMode(rl1, OUTPUT);
pinMode(rl2, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
pinMode(button4, INPUT);
}
void loop() {
reading1 = digitalRead(button1);
reading2 = digitalRead(button2);
reading3 = digitalRead(button3);
reading4 = digitalRead(button4);
//Relay 1
if(reading1 != lastButtonState1){
lastDebounceTime1 = millis();
lastButtonState1 = reading1;
}
if(reading1 != lastButtonState1){
lastDebounceTime1 = millis();
lastButtonState1 = reading1;
}
if((millis() - lastDebounceTime1) > debounceDelay1){
if(buttonState1 != lastButtonState1){
buttonState1 = lastButtonState1;
if(buttonState1 == HIGH){
rl1State = !rl1State;
digitalWrite(rl1, rl1State);
}
}
}
//Relay 2
if(reading2 != lastButtonState2){
lastDebounceTime2 = millis();
lastButtonState2 = reading2;
}
if((millis() - lastDebounceTime2) > debounceDelay2){
if(buttonState2 != lastButtonState2){
buttonState2 = lastButtonState2;
if(buttonState2 == HIGH){
rl2State = !rl2State;
digitalWrite(rl2, rl2State);
}
}
}
}
I also tried to re-make all the variables for each button and relay, but it still does not work.
On another note, one of my relays does not work when put to any pin (when all the pins are connected) but it works only when one of the pins are disconnected. It's really weird. I tested the relay and it's fine and I changed the Arduino but still have the same issue.
AH! This will work here is the code and the schematics for all of you that have this problem (saw on the internet a lot do have this problem), as well THANK YOU ALL for you help in solving this matter! ENJOY!
Circuit (Please note the relay cluster I am using was not available on Fritzing)
Code:
//Buttons
int button1 = 7;
int button2 = 6;
int button3 = 4;
int button4 = 2;
//Relays
int rl1 = 13;
int rl2 = 12;
int rl3 = 11;
int rl4 = 8;
//States for Relay and Button (1)
int state1 = HIGH; // the current state of the output pin
int reading1; // the current reading from the input pin
int previous1 = LOW; // the previous reading from the input pin
//States for Relay and Button (2)
int state2 = HIGH; // the current state of the output pin
int reading2; // the current reading from the input pin
int previous2 = LOW; // the previous reading from the input pin
//States for Relay and Button (3)
int state3 = HIGH; // the current state of the output pin
int reading3; // the current reading from the input pin
int previous3 = LOW; // the previous reading from the input pin
//States for Relay and Button (4)
int state4 = HIGH; // the current state of the output pin
int reading4; // the current reading from the input pin
int previous4 = LOW; // the previous reading from the input pin
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time1 = 0; // the last time the output pin was toggled
long time2 = 0;
long time3 = 0;
long time4 = 0;
long debounce1 = 200; // the debounce time, increase if the output flickers
long debounce2 = 200;
long debounce3 = 200;
long debounce4 = 200;
void setup()
{
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
pinMode(button4, INPUT);
pinMode(rl1, OUTPUT);
pinMode(rl2, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(rl4, OUTPUT);
}
void loop() {
reading1 = digitalRead(button1);
reading2 = digitalRead(button2);
reading3 = digitalRead(button3);
reading4 = digitalRead(button4);
// if the input just went from LOW and HIGH and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
//Condition Relay 1
if (reading1 == HIGH && previous1 == LOW && millis() - time1 > debounce1) {
if (state1 == HIGH)
state1 = LOW;
else
state1 = HIGH;
time1 = millis();
}
//Condition Relay 2
if (reading2 == HIGH && previous2 == LOW && millis() - time2 > debounce2) {
if (state2 == HIGH)
state2 = LOW;
else
state2 = HIGH;
time2 = millis();
}
//Condition Relay 3
if (reading3 == HIGH && previous3 == LOW && millis() - time3 > debounce3) {
if (state3 == HIGH)
state3 = LOW;
else
state3 = HIGH;
time3 = millis();
}
//Condition Relay 4
if (reading4 == HIGH && previous4 == LOW && millis() - time4 > debounce4) {
if (state4 == HIGH)
state4 = LOW;
else
state4 = HIGH;
time4 = millis();
}
digitalWrite(rl1, state1);
digitalWrite(rl2, state2);
digitalWrite(rl3, state3);
digitalWrite(rl4, state4);
previous1 = reading1;
previous2 = reading2;
previous3 = reading3;
previous4 = reading4;
}
I'm trying to find a way to use one button to enable/disable commands. (actually, it's a multicolor LED i'm trying to start/stop changing colors)
My code is under here, but it does not work, if anyone could tell me what's wrong, i can't see it...
int red = 0;
int redPin = 9;
int blue = 0;
int bluePin = 11;
int green = 0;
int greenPin = 10;
int state = 0;
int stateModulo = 0;
void setup() {
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(9, OUTPUT);
pinMode(2, INPUT);
}
void checkButton(int var, int result) {
if (digitalRead(2) == HIGH) {
var++;
result = var%2;
}
}
void changecolor(int startColor,int endColor,int startPin,int endPin,int delayTime)
{
for (endColor = 0; endColor <= 255; endColor++)
{
checkButton(state,stateModulo);
if (stateModulo == 0) {
startColor = 255 - endColor;
analogWrite(endPin, endColor);
analogWrite(startPin, startColor);
delay(delayTime);
}
}
}
void loop() {
changecolor(red,green,redPin,greenPin,10);
changecolor(green,blue,greenPin,bluePin,10);
changecolor(blue,red,bluePin,redPin,10);
}
In the code below, result is not passed by reference, nor returned.
The same applies to var, after you have modified it you throw away any edit you have made.
void checkButton(int var, int result) {
if (digitalRead(2) == HIGH) {
var++;
result = var%2;
}
}
I can recommend you a good C++ book where to learn some language basics.
My suggestion: Thinking in C++, by Bruce Eckel.
Consider this:
//Buttons
int button1 = 7;
int button2 = 6;
int button3 = 4;
int button4 = 2;
//Relays
int rl1 = 13;
int rl2 = 12;
int rl3 = 11;
int rl4 = 8;
//States for Relay and Button (1)
int state1 = HIGH; // the current state of the output pin
int reading1; // the current reading from the input pin
int previous1 = LOW; // the previous reading from the input pin
//States for Relay and Button (2)
int state2 = HIGH; // the current state of the output pin
int reading2; // the current reading from the input pin
int previous2 = LOW; // the previous reading from the input pin
//States for Relay and Button (3)
int state3 = HIGH; // the current state of the output pin
int reading3; // the current reading from the input pin
int previous3 = LOW; // the previous reading from the input pin
//States for Relay and Button (4)
int state4 = HIGH; // the current state of the output pin
int reading4; // the current reading from the input pin
int previous4 = LOW; // the previous reading from the input pin
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time1 = 0; // the last time the output pin was toggled
long time2 = 0;
long time3 = 0;
long time4 = 0;
long debounce1 = 200; // the debounce time, increase if the output flickers
long debounce2 = 200;
long debounce3 = 200;
long debounce4 = 200;
void setup()
{
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
pinMode(button4, INPUT);
pinMode(rl1, OUTPUT);
pinMode(rl2, OUTPUT);
pinMode(rl3, OUTPUT);
pinMode(rl4, OUTPUT);
}
void loop() {
reading1 = digitalRead(button1);
reading2 = digitalRead(button2);
reading3 = digitalRead(button3);
reading4 = digitalRead(button4);
// if the input just went from LOW and HIGH and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
//Condition Relay 1
if (reading1 == HIGH && previous1 == LOW && millis() - time1 > debounce1) {
if (state1 == HIGH)
state1 = LOW;
else
state1 = HIGH;
time1 = millis();
}
//Condition Relay 2
if (reading2 == HIGH && previous2 == LOW && millis() - time2 > debounce2) {
if (state2 == HIGH)
state2 = LOW;
else
state2 = HIGH;
time2 = millis();
}
//Condition Relay 3
if (reading3 == HIGH && previous3 == LOW && millis() - time3 > debounce3) {
if (state3 == HIGH)
state3 = LOW;
else
state3 = HIGH;
time3 = millis();
}
//Condition Relay 4
if (reading4 == HIGH && previous4 == LOW && millis() - time4 > debounce4) {
if (state4 == HIGH)
state4 = LOW;
else
state4 = HIGH;
time4 = millis();
}
digitalWrite(rl1, state1);
digitalWrite(rl2, state2);
digitalWrite(rl3, state3);
digitalWrite(rl4, state4);
previous1 = reading1;
previous2 = reading2;
previous3 = reading3;
previous4 = reading4;
}