I’m kind of stuck on something. I am trying to work 2 leds using arduino with 2 buttons in processing. The goal is to link 1 button to one led.
Now the problem. I have tried several things, but i cannot get the second led to work. The first led is working on both buttons in processing.
Can someone help me to figure out what i did wrong?
ARDUINO CODE
int LED1 = 10;
int LED2 = 11;
int val1 = 0;
int val2 = 0;
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
Serial.begin(9600);
}
void loop() {
analogWrite(LED1, LOW);
analogWrite(LED2, LOW);
if (Serial.available() >1){
val1 = Serial.read();
val2 = Serial.read();
}
if (val1 >10 && val2 ==0){
digitalWrite(LED1, HIGH);
}else{
digitalWrite(LED1, LOW);
}
if (val2 >10 && val1 ==0){
digitalWrite(LED2, HIGH);
}else{
digitalWrite(LED2, LOW);
}
}
PROCESSING CODE
import processing.serial.*;
Serial myPort;
void setup() {
size(640, 360);
background(100);
noStroke();
String portName = Serial.list() [1];
myPort = new Serial(this, portName, 9600);
}
int value1 = 0;
int value2 = 0;
void draw() {
if (myPort.available()>0){
}
fill(value1);
rect(150, 50, 50, 50);
fill(value2);
rect(50, 210, 50, 50);
println("VALUE1_"+value1);
println("VALUE2_"+value2);
}
void mousePressed() {
if (mouseX > 149 && mouseX < 200 && mouseY > 49 && mouseY < 101) {
if (value1 == 0){
value1 = 255;
myPort.write(value1);
}else{
value1 = 0;
myPort.write(value1);
}
}
if (mouseX > 49 && mouseX < 100 && mouseY > 209 && mouseY < 250) {
if (value2 == 0){
value2 = 255;
myPort.write(value2);
}else {
value2 = 0;
myPort.write(value2);
}
}
}
First things first. Design your system! What's the smart way of communication? Sending so many bytes? or just one byte? If I am to do it, I would think of 4 different possible states : 1- Both LEDs should be on -> I would send A to Arduino to indicate this state 2- Left LED is on, while right LED is off -> send B to Arduino 3- Right LED is on, while left LED is off -> send C to Arduino 4- Both LEDs are off -> send D to Arduino
Now your processing code can be something like this:
import processing.serial.*;
Serial myPort;
boolean leftLed;
boolean rightLed;
void setup() {
size(640, 360);
background(100);
noStroke();
String portName = Serial.list() [1];
myPort = new Serial(this, portName, 9600);
leftLed=false;
rightLed=false;
}
void draw() {
fill(value1);
rect(150, 50, 50, 50);
fill(value2);
rect(50, 210, 50, 50);
}
void updateArduino(){
if(rightLed && leftLed) myPort.write("A");
else if(leftLed) myPort.write("B");
else if(rightLed) myPort.write("C");
else myPort.write("D");
}
void mousePressed() {
if (mouseX > 149 && mouseX < 200 && mouseY > 49 && mouseY < 101)
leftLed = !leftLed;
else if (mouseX > 49 && mouseX < 100 && mouseY > 209 && mouseY < 250)
rightLed=!rightLed;
updateArduino();
}
And in Arduino, read them like this:
if (Serial.available()){
char temp=Serial.read();
if(temp=='A') {
//turn on both lights
}
else if(temp=='B'){
//turn on left light
}
else if(temp=='C'){
//turn on right light
}
else if(temp=='D'){
//turn off both lights
}
}
Related
I was creating a PIR Motion sensor and GSM Module SMS 800A based Security System with Arduino UNO
But I am facing a problem from 2 to 3 days that whenever I send a SMS from my phone to my GSM module then the Motion sensor automatically detects a motion and makes the system active.
Please tell me why is this happening?
This is my code :->
#include <SoftwareSerial.h>
#include <Sim800L.h>
#include <MemoryFree.h>
Sim800L GSM(10, 11);
SoftwareSerial sim800(10, 11); //2 is TX and 3 is RX
int day, month, year, minute, second, hour;
int onDay, onMonth, onYear, onMinute, onSecond, onHour;
int offDay, offMonth, offYear, offMinute, offSecond, offHour;
unsigned long prevMillis;
unsigned long currentMillis;
const long interval = 30000;
boolean timeStatus = false;
int RTCPerm;
int led = 13;
int pin = 5;
int x = 1;
int m = 0;
char y;
char t;
int value = 0;
int pirState = LOW;
char n[3];
int j = 0;
int i = 0;
char data[200] = {};
int condition = 0;
char DTMF[200] = {};
int z;
int delayOnMinute, delayOffMinute, delayOnHour, delayOffHour;
// connections
//
// GSM ARDUINO UNO
//
// GND -----> GND
// TX -----> 2
// RX -----> 3
// Power Supply -----> 12V 1A or 5V 2A
//
// Motion Sensor Arduino UNO
//
// VCC -----> 5V
// GND -----> GND
// OUT -----> 4
void setup() {
pinMode(led, OUTPUT);
pinMode(12, OUTPUT);
pinMode(pin, INPUT);
Serial.begin(9600);
sim800.begin(9600);
delay(6000);
sim800.println(F("AT+CMGF=1"));
sim800.println(F("AT+CNMI=2, 2, 0, 0, 0"));
sim800.println(F("AT+DDET=1"));
GSM.begin(9600); // for RTC data input
delay(5000);
onMinute = 30;
onHour = 17;
offMinute = 00;
offHour = 15;
}
void loop() {
while (RTCPerm == 0) {
RTCStatus();
prevMillis = millis();
while (currentMillis - prevMillis != interval) {
// save the last time you blinked the LED
currentMillis = millis();
SMSRecieve();
if (timeStatus == true) {
value = digitalRead(pin);
if (value == HIGH) {
digitalWrite(led, HIGH);
if (pirState == LOW) {
goto Motion;
}
}
}
}
}
Serial.println("Hello");
value = digitalRead(pin);
if (value == HIGH) {
digitalWrite(led, HIGH);
if (pirState == LOW) {
Motion:
Serial.println(F("Motion Detected!"));
sim800.begin(9600);
So in the loop function you can see the SMS Receive function that checks whether there is any incoming SMS or not. So whenever I send a SMS to my GSM then my Motion sensor gets active and goes to label Motion which activates other functioning like starting the alarm etc.
This is the code of SMSRecieve() Function :->
void SMSRecieve() {
Samarth:
/* if (condition == 2) {
memset(data, 0, sizeof(data));
y = 0;
condition = 1;
}*/
if (sim800.available())
{ // Printing the collected data
y = sim800.read();
Serial.write(y);
if (y == '#') {
goto skip;
}
data[i] = y;
i++;
skip:
if (strstr(data, "off") || strstr(data, "OFF") || strstr(data, "Off")) {
// Do Something
} else if (strstr(data, "Lighton") || strstr(data, "lighton") || strstr(data, "LightOn") || strstr(data, "LIGHTON")) {
// Do Something
}else if (strstr(data, "Lightoff") || strstr(data, "lightoff") || strstr(data, "LightOff") || strstr(data, "LIGHTOFF")) {
// Do Something
}
}
}
Please help me where I am doing wrong ?
After testing the situation again and again I got the solution and the reason why that was happening.
REASON:- PIR Motion Sensors also detect the RF and other unseen frequencies in the air. So whenever I sent a SMS to my GSM, it was detected by my PIR Motion Sensor.
SOLUTION:- The GSM Module should be kept with at least 2 feet of distance from the PIR Motion Sensor
I'm trying to blink a LED according to press of toggle button. If I press the first toggle switch the first time, LED blinks at 5 Hz, when I press the toggle button for the second time, LED blink at 6 Hz and when I press the third time, LED turns off.
I tried using the program below, but It's not working as I wanted.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
// variables will change:
int buttonState = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
int x=0;
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
Serial.print(x);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH && x==0) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
Serial.print(x);
} else {
// turn LED off:
x = x+1;
}
if (buttonState == HIGH && x==1) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(2000);
digitalWrite(ledPin, LOW);
delay(2000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==2) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(3000);
digitalWrite(ledPin, LOW);
delay(3000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==3) {
// turn LED off:
digitalWrite(ledPin, LOW);
x = 0;
}
}
When I use this code it works for first case that is LED blinks at 1000 ms delay, but if I toggle switch it again works for first condition. How can I make it to execute second condition i.e. to blink at delay of 2000 ms?
Firstly this is your circuit. I tried this circuit and code and worked for me. I used interrupt for checking button state. And millis calculation is simple.
Frequency = 1 / Period
Period = Ton + Toff
6Hz = 1000 millis / T => T = 166 millis
166 = Ton + Toff (for %50 duty cycle Ton=Toff) => Ton = Toff = 83 millis
enter image description here
const int ledPin = 13;
const int buttonPin = 2;
int state = -1;
bool willLightOn = false;
unsigned long currentDelay = 0;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), changeState, FALLING);
}
void loop() {
if(state % 3 == 0) { //6Hz
currentDelay = 83;
willLightOn = true;
} else if (state % 3 == 1) { //5Hz
currentDelay = 100;
willLightOn = true;
} else if (state % 3 == 2) { //LED off
currentDelay = 0;
willLightOn = false;
digitalWrite(ledPin, LOW);
}
currentMillis = millis();
if (currentMillis - previousMillis >= currentDelay && willLightOn) {
previousMillis = currentMillis;
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
void changeState() {
state++;
}
Right now your logic checks 3 times for the value of x in a single loop.
Below code toggles light whenever x is greater than zero. x's value is changed when button is pressed.
But there is a big problem here: If button is pressed when there's something else going on in the processor or it is sleeping (like the long delays you want to use), it may be ignored. So you better study interrupts and implement this behavior using them.
if (x > 0)
{
digitalWrite(ledPin, HIGH);
delay(1000 * x);
digitalWrite(ledPin, LOW);
}
if (buttonState == HIGH)
{
x++;
if (x > 3)
x = 0;
}
You should create a global state of the application. This state is where you remember if you are blinking at 50hz/60hz/off. Then you can use a switch to do the right thing.
Then you check if the button is pressed and change the application state.
See my example below:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
// variables will change:
int applicationState = 0;
bool lightOn = true;
int currentDelay = 1000;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
if (digitalRead(buttonPin) == HIGH) {
applicationState++;
if(applicationState >= 3) {
applicationState = 0;
}
delay(100);
}
switch(applicationState){
case 0:
currentDelay = 1000;
lightOn = true;
break;
case 1:
currentDelay = 2000;
lightOn = true;
break;
case 2:
digitalWrite(ledPin, LOW);
lightOn = false;
break;
}
currentMillis = millis();
if (currentMillis - previousMillis >= currentDelay && lightOn) {
previousMillis = currentMillis;
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
I hope you understand what I try to say and demo with the example code.
Your code can not work:
You do need to check if the button state changes, detect when there is a edge. And make sure you detect a single edge only once.
You must repeat the blinking it in a loop till the button is pressed, then you can change the frequency.
You must check the button while you sleep, otherwise your program do not recognize when you press the button.
To make it work, you must change the complete program.
#define BLINK_SLEEP_TIME <some value> // insert value for 16.6666ms
//return 1 after a positive edge
bool button_read(void)
{
static bool lastState=1; //set this to 1, so that a pressed button at startup does not trigger a instant reaction
bool state = digitalRead(buttonPin);
if(state != lastState)
{
state=lastState;
return state;
}
return 0;
}
//Blink the LED with a given period, till button is pressed
//Times are in x*16.666ms or x/60Hz
//At least one time should be more than 0
void blink(uint8_t ontime, uint8_t offtime)
{
while(1)
{
for(uint8_t i=0;i<ontime;i++)
{
led_setOn();
delay(BLINK_SLEEP_TIME);
if(button_read())
{
return;
}
}
for(uint8_t i=0;i<offtime;i++)
{
led_setOff();
delay(BLINK_SLEEP_TIME);
if(button_read())
{
return;
}
}
}
}
const uint8_t time_table[][]=
{
{0,50},//LED is off
{6,6}, //LED blinks with 5Hz, 60Hz/2/6=5Hz
{5,5}, //LED blinks with 6Hz, 60Hz/2/5=6Hz
}
void endless(void)
{
uint8_t i=0;
for(;;)
{
i++;
if(i>2)
{
i=0;
}
blink(time_table[i][0],time_table[i][1]);
}
}
A better approach would be to use a hardware PWM-Module and change the values after a edge on the button.
I am using keypad 4*4 with an Arduino Mega, I have sensors connected to the Arduino I want to press a key from the keypad and have response in the same time, I don't want to wait till the loop continue, I want to save up to 10 numbers entered from the keypad, so is there a way to make the keypad as an interrupt for my code?
void loop()
{
char key = kpd.getKey();
if (key != NO_KEY) {
if (key == 'C') //clear the array
{
index = 0;
numbers[index] = '\0';
}
else if (key == '.') {
numbers[index++] = '.';
numbers[index] = '\0';
}
else if (key >= '0' && key <= '9') {
for (int z = 0; z == 10; z++) {
numbers[index++] = key;
numbers[index] = '\0';
}
}
else if (key == 'A') {
float len = atof(numbers); //conversion from string to numeric
if (fona.callPhone(numbers)) {
Serial.println(F("RING!"));
Serial.print(F("Phone Number: "));
Serial.println(numbers); //print out on serial monitor
}
}
else if (key == 'D') {
if (fona.pickUp()) {
Serial.println(F("Failed"));
}
}
else if (key == '#') {
if (fona.hangUp()) {
Serial.println(F("Failed"));
}
}
}
gas = analogRead(gasPin);
dtostrf(gas, 4, 2, gass);
Serial.println(gas);
delay(1000); // Print value every 1 sec.
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
delay(150);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
else {
digitalWrite(ledPin, LOW); // turn LED OFF
delay(300);
if (pirState == HIGH) {
// we have just turned off
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
int ldrStatus = analogRead(ldrPin);
if (ldrStatus <= 550) {
digitalWrite(led, HIGH);
Serial.println("LDR is DARK, LED is ON");
}
else {
digitalWrite(led, LOW);
}
valee = analogRead(tempPin);
float cel = (valee * 0.48828125) / 2.12304;
dtostrf(cel, 4, 2, temp);
Serial.print("TEMPRATURE = ");
Serial.print(cel);
Serial.print("*C");
Serial.println();
delay(1000);
This question already has answers here:
What are forward declarations in C++?
(8 answers)
Closed 5 years ago.
Im working with Arduino IDE, which doesn't allow nested functions, or calling a function before it had been declared(it doesnt jump to find it)..
In my code, I need either one or the other..
Also, making it all one big function does not work because when i check back to an earlier sensor, i have to write what to do if yes and if no over and over forever.
Here, im trying to sense light, if theres light, go to the PIR sensor, if not, run light sensor again. now if the PIR senses motion twice in 3.5 sec, check color, if not, check light.
Now the color senses color and clasifies it(r g or b). now it checks for PIR again and if there's movement, it check color again and checks pir again. now if the pir doesnt sense movement, it sends to the lines to serial..
I declared some functions before I used them(print lines) but some of them not because i get stuck in a loop.
When i check light, if its positive, i run the PIR,so i would need to declare the pir function before ligth. but in the pir, if its negative(no movement), i run light sensor, implying that i should declare light sensor before pir.
Im stuck in that loop...
int lightPin = A0;
int valLight = 0;
int ledTrans = 2;
int pirTrans = 3;
int pirPin = 4;
int pirState = LOW;
int CalTime = 30;
int colorTrans = 5;
int s2 = 6;
int s3 = 7;
int OUTpin= 8;
boolean RD= false;
boolean GD = false ;
boolean BD = false;
int rfPin = 9;
void setup() {
pinMode(A0,INPUT);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,INPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,INPUT);
pinMode(9,OUTPUT);
Serial.begin(9600);
}
void printlines();
void pirSensor();
void colorSensor();
void pirSensor2();
void lightSensor() {
//light sensor
valLight = analogRead(A0);
delay(1000);
if (valLight >= 300) {
ledTrans = HIGH;
pirTrans = HIGH;
pirSensor();
} else {
delay(8000);
}
}
void pirSensor() {
// Calibration
for ( byte i = 0; i < 30; i++) {
delay(1000);
}
// Check PIR state
int pirState = digitalRead(2);
delay(1500);
pirState = digitalRead(2);
if (pirState == HIGH) {
colorTrans = HIGH;
colorSensor();
} else if (pirState == LOW) {
pirState = LOW;
lightSensor();
}
}
void colorSensor(){
//Check Color reads pulse for RGB
// void checkred
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
unsigned int RW = 255 - (pulseIn(OUTpin, LOW)/ 400 - 1); // turns into 0-255
delay(6000);
// void checkgreen
digitalWrite(s2,LOW);
digitalWrite(s3,HIGH);
unsigned int GW = 255 - (pulseIn(OUTpin, LOW)/ 400 - 1);
delay(6000);
// void checkblue
digitalWrite(s2, HIGH);
digitalWrite( s3, HIGH);
unsigned int BW = 255 - (pulseIn(OUTpin, LOW) / 400 - 1);
delay(6000);
// seeing which color I got(r g or b)
if (RW > BW && RW > GW){
RD = true;
delay(7000);
} else if (GW > RW && GW > BW){
GD = true;
delay(7000);
} else if (BW > RW && BW > GW){
BD = true;
delay(4000);
}
}
void pirSensor2(){
pirState = digitalRead(2);
delay(1500);
pirState = digitalRead(2);
if(pirState = HIGH){
colorSensor();
}else{
printlines();
}
}
void printlines(){
if(RD){
Serial.print("RED DETECTED");
} else if(GD){
Serial.print("GREEN DETECTED");
}else if(BD){
Serial.print("BLUE DETECTED");
}else if(RD && GD){
Serial.print("RED & GREEN DETECTED");
}else if(RD && BD){
Serial.print("RED & BLUE DETECTED");
}else if(BD && GD){
Serial.print("GREEN & BLUE DETECTED");
}else if(RD && GD && BD){
Serial.print("RED, GREEN, BLUE DETECTED");
}
delay(7000);
}
You can declare a function before you define it:
void setup();
Then you can call it:
setup();
...and somewhere later in the file you can write its definition:
void setup() {
// implementation here
}
I just bought a new arduino adafruit motorshield because i needed to control 4 dc motors and it seemed to be the right decision. My arduino IDE is currently on a linux Virtual Box because i needed a specific library that I could only find on linux...The code below is supposed to receive data from websockets (that is working ) but when i use the Adafruit motor library something simply doesnt work...a humming sound comes out of the motors, but no actual movement.
(btw the "x" and "y" coordinates are being printed on the Serial Port)
#include <AFMotor.h>
int x = -10;
int y = -10;
int b = 0;
AF_DCMotor motor_shoulderx(1);
AF_DCMotor motor_shouldery(2);
AF_DCMotor motor_elbow(3);
AF_DCMotor motor_wrist(4);
void setup(){
Serial.begin(9600);
}
void loop(){
if (Serial.available())
{ if (b == 0)
{ x = Serial.read();
b =1;
}
else {
y = Serial.read();
b = 0;
}
if (x != -10){
Serial.println("x is:");
Serial.println(x);
if(x > 200) {
motor_shoulderx.run(FORWARD);
}
else {
motor_shoulderx.run(BACKWARD);
}
}
if (y != -10){
Serial.println ("y is:");
Serial.println (y);
if (y > 200){
motor_shouldery.run(FORWARD);
motor_elbow.run(FORWARD);
motor_wrist.run(FORWARD); }
else {
motor_shouldery.run(BACKWARD);
motor_elbow.run(BACKWARD);
motor_wrist.run(BACKWARD);
}
}
}}