I am Working on an Arduino mini project. its to design an automatic room light controller using IR modules and arduino UNO R3. Before coming to my question i'd explain it a bit .Its like an arduino is connected to an IR module and a counter keeps count of people entering the room, when the room is empty light turns off automatically.But my Code isnt working the way im expecting it to work. . given below is the code for my mini project.
#define x 14 // x sensor 1
#define y 19 // y sensor 2
#define relay 2 // relay for output
int count = 0; // initialisation
// void IN() //{ count ++;} // void OUT() // { cout--; // }
void setup()
{
// put your setup code here, to run once:
pinMode(x, INPUT);
pinMode(y, INPUT);
pinMode(relay, OUTPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
if(digitalRead(x)) //IN();
{
count++;
}
if (digitalRead(y)) // OUT();
{
count--;
}
if (count <= 0) {
digitalWrite(relay, LOW);
delay(20);
}
else
digitalWrite(relay, HIGH);
}
The problem with my code is that the transmitter and receiver sense interference both at the same time resulting in turning of the light while the person is still inside the room.As im new to arduino need your inputs.
Related
I am currently troubleshooting a code in Arduino for a temperature and humidity project. There is a line in the void setup(), Serial.println("Feather LoRa TX Test!");, which keeps popping up. My ideal code is to run that particular line once in the output and that will be it. However, the current code keeps repeating that line again, and again. May I know how do I rectify this issue (The whole code is below)? Thanks in advance!!
#include <RH_RF95.h>
#include <DHT.h>
#define DHTPIN 7 // what digital pin we're connected to
#define DHTTYPE DHT22 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 3
// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0
// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);
int node = 3; // to change based on node deployment
void setup()
{
pinMode(RFM95_RST, OUTPUT);
digitalWrite(RFM95_RST, HIGH);
while (!Serial);
Serial.begin(9600);
delay(100);
Serial.println("Feather LoRa TX Test!");
digitalWrite(RFM95_RST, LOW);
delay(100);
digitalWrite(RFM95_RST, HIGH);
delay(100);
while (!rf95.init()) {
Serial.println("LoRa radio init failed");
while (1);
}
Serial.println("LoRa radio init OK!");
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
if (!rf95.setFrequency(RF95_FREQ)) {
Serial.println("setFrequency failed");
while (1);
}
Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
dht.begin();
rf95.setTxPower(23, false);
}
void loop()
{
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
delay(1000);
return;
}
String d = "{\"Node\":"+ String (node) +",";
d += "\"Temp\":"+ String (t)+",";
d += "\"Hum\":"+ String (h);
d += "} "; // Add a trailing space is necessary
Serial.println("Transmitting...");
char data[d.length()];
d.toCharArray(data,d.length());
Serial.println(d);
rf95.send((uint8_t*)data, sizeof(data));
Serial.println("Waiting for packet to complete...");
delay(1000);
rf95.waitPacketSent();
Serial.println(" complete...");
delay(57000); // delay 1 minute
}
You have an infinite loop before you do any initialization. This will be detected because Arduino have a watchdog timer, and the system will reset.
And on reset setup is called again, and you again enter the infinite loop.
The loop it's about:
while (!Serial);
You must call Serial.begin(...) before that loop:
Serial.begin(9600);
while (!Serial);
Something is resetting your MCU before the code reaches the loop function. Therefore the setup function gets executed again and again. You can add more print messages in between lines so you'll know where it breaks.
I cannot explain to myself why this code works properly in some cases and in some not. Here is the situation:
I am trying to switch a relay with the Arduino Nano. Therefore I took the "Blink" example as a guide. It should switch on for like 5 minutes and switch off for like 25 minutes. Here is the code:
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
pinMode(2, OUTPUT); // sets PIN 2 as switcher for the relay
}
// the loop function runs over and over again forever
void loop() {
int count = 0;
int run_pump = 300; // 5 Min run
int stop_pump = 1500; // 25 Min stop
digitalWrite(LED_BUILTIN, LOW); // turn the LED off (HIGH is the voltage level)
digitalWrite(2, HIGH); // turn the pump on
while(count < run_pump) {
count++;
delay(1000); // wait for a second
}
count = 0;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on by making the voltage LOW
digitalWrite(2, LOW); // turn the pump off
while(count < stop_pump) {
count++;
delay(1000); // wait for a second
}
}
if I run this code on the Arduino it will just switch on the relay forever. BUT: If I set run_pump and stop_pump for like 10 sec. it will work properly! Is there an explanation why this does not work with the bigger counters? It's so confusing....
so this code here works absolutely fine, but why does the code above not?
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
pinMode(2, OUTPUT); // sets PIN 2 as switcher for the relay
}
// the loop function runs over and over again forever
void loop() {
int count = 0;
int run_pump = 5; // 5 sec run
int stop_pump = 10; // 10 sec stop
digitalWrite(LED_BUILTIN, LOW); // turn the LED off (HIGH is the voltage level)
digitalWrite(2, HIGH); // turn the pump on
while(count < run_pump) {
count++;
delay(1000); // wait for a second
}
count = 0;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on by making the voltage LOW
digitalWrite(2, LOW); // turn the pump off
while(count < stop_pump) {
count++;
delay(1000); // wait for a second
}
}
Hope someone has a clue.... Thanks!
Tom
OK guys, I solved it. The problem was a cheap relay that was trying to communicate with the Arduino... Replacing it with a better one solved the whole problem. Thanks for the idea with the LED, this brought some stones to roll... :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a problem with my code. I wired everything correctly, but the values that the sensors read are either wrong. Or the code I wrote is wrong. The car never stops when something is within 20cm of the front sensor. It rather just keeps driving. The RC car is hooked up to the arduino with 3 ultrasonic sensors. And the RC motors are driven by an H-bridge(not the shield). The commented code parts are the code for if the RC car had a servo. But this car had 2 RC motors.
Here is the code:
//Libraries.
//#include <Servo.h>
#include <NewPing.h>
//Variables.
/*const int pos = 103; //Servo midden 103*
const int StrLeft = 70; //Serv0 naar links.
const int StrRight = 133; //Servo naar rechts.*/
int Left = 5;
int Right = 4;
int Forwards = 3;
int Backwards = 2;
int potPin = A0;
int speed = 0;
#define TRIGGER_PIN1 11 //Front
#define ECHO_PIN1 12
#define TRIGGER_PIN2 7 //Left
#define ECHO_PIN2 8
#define TRIGGER_PIN3 9 //Right
#define ECHO_PIN3 10
#define MAX_DISTANCE 200
#define MAX_DISTANCEF 1000
//Name of the objects.
//Servo MyServo;
NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCEF);//Front
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);//Left
NewPing sonar3(TRIGGER_PIN3, ECHO_PIN3, MAX_DISTANCE);//Right
//Start of the program.
void setup() {
Serial.begin(9600);
int Fwd = false;
/*MyServo.attach(9); //Pin number of the attached Servo.
MyServo.write(pos); //Resets to this posistion automatically.*/
pinMode(Left, OUTPUT);
pinMode(Right, OUTPUT);
pinMode(Forwards, OUTPUT);
pinMode(Backwards, OUTPUT);
}
//During the program.
void loop() {
//Sturen
/*MyServo.write(pos);
delay(1000);
MyServo.write(StrLeft);
Serial.print("Links");
delay(1000);
MyServo.write(StrRight);
Serial.print("Rechts");
delay(1000);
MyServo.write(pos);
delay(1000);*/
//Value of the potentiometer
speed = analogRead(potPin);
speed = map(speed, 0, 1023, 0, 179);
Serial.print(speed);
//Sensor
unsigned int distanceF = sonar1.ping_cm();//Front
unsigned int distanceL = sonar2.ping_cm();//Left
unsigned int distanceR = sonar2.ping_cm();//Right
Serial.print(distanceF);
Serial.print(distanceL);
Serial.print(distanceR);
Serial.print("cm");
delay(50);
//Values for driving
if (distanceF > 50 ) {
int Fwd = true;
Serial.print("true");
} else {
int Fwd = false;
Serial.print("false");
Stp();
}
delay(50);
if ((distanceF = true) && (distanceL > distanceR)) {
fwdLeft();
} else if ((distanceF = true) && (distanceR > distanceL)){
fwdRight();
}
delay(50);
}
void fwdLeft() {
digitalWrite(Forwards, HIGH);
digitalWrite(Backwards, LOW);
digitalWrite(Left, HIGH);
digitalWrite(Right, LOW);
}
void fwdRight() {
digitalWrite(Forwards, HIGH);
digitalWrite(Backwards, LOW);
digitalWrite(Left, LOW);
digitalWrite(Right, HIGH);
}
void Stp() {
digitalWrite(Forwards, LOW);
digitalWrite(Backwards, LOW);
digitalWrite(Left, LOW);
digitalWrite(Right, LOW);
}
In the comments, you said that that Fwd variable never changes. Note that you have three different variables name Fwd, though it seems you probably intended to have one global one.
The first is in setup:
void setup() {
Serial.begin(9600);
int Fwd = false;
// ...
}
This Fwd is local to setup. It's set but never read. Once setup is finished, it no longer exists.
The other two are here:
if (distanceF > 50 ) {
int Fwd = true;
Serial.print("true");
} else {
int Fwd = false;
Serial.print("false");
Stp();
}
Each of those is a new variable that's local to the scope in which it's defined (from the definition until the closing curly brace). Again, these are set but never inspected.
I think what you intended is to declare a global variable outside of any function:
int Fwd = false;
Then, whenever you want to change it, you'd just assign to it without repeating the type:
Fwd = true;
Then you have lines like this:
if ((distanceF = true) && (distanceL > distanceR))
I'm not sure what you intended by (distanceF = true), but I don't think that code does what you think it does. Since you used a single =, that's an assignment not a comparison. So your if-condition is actually changing the value of distanceF to true rather than checking to see if it is true (or non-zero). I suspect you wanted Fwd there:
if (Fwd && (distanceL > distanceR))
None of that explains why the car doesn't actually stop though. I suspect you also have a problem reading the data from the ultrasonic sensor. Perhaps the units aren't what is expressed in the code or you need to do some averaging (or other filtering) of the readings in order to reduce noise and faulty readings.
Here's code, you just need to adjust code for yourself, but logic Works, at least car will stop if is something in front. Also watch how you write your code. In if statment instead of == you have =
Also give proper names for variables and functions.
if (distanceF < 50)
{
// Code that will stop the car
}
else
{
// Code that will drive car forward
}
if (Fwd)
{
if (distanceL > distanceR)
{
// Code that will drive car left
}
else
{
// Code that will drive car right
}
}
Note: The code is designed to run on a Particle Photon. Please keep this in mind while reading my question.
I want to make a led blink based on a variable called blink_type this variable will be changed dynamically in a later stage when I implement the API call to fetch the status of something else. I'm currently simulating this behaviour in the loop() function (also tried a thread but that also didn't work).
The blinking works fine until the variable changes from 0 to 1, after that it never blinks again until I do a reset.
Below you will find my code:
// This #include statement was automatically added by the Particle IDE.
#include <httpsclient-particle.h>
// Base variables.
int led = D0;
int buzzer = D1;
// Defining blink types. 0 is normal, 1 is breathe.
int blink_type = 0;
// Set the threads
Thread *normalBlinkThread;
Thread *ledBreatherThread;
void setup() {
// Setup the outputs.
pinMode(led, OUTPUT);
pinMode(buzzer, OUTPUT);
// Create the required threads.
normalBlinkThread = new Thread("rest_status_light", normalBlink);
ledBreatherThread = new Thread("rest_status_light", hearthBeatBlink);
}
os_thread_return_t normalBlink(void*) {
// Start never ending loop
for(;;) {
if(blink_type == 0) {
// Blink led
digitalWrite(led, HIGH);
delay(3000);
digitalWrite(led, LOW);
delay(3000);
}
}
}
os_thread_return_t hearthBeatBlink(void*) {
// Start never ending loop
for(;;) {
if(blink_type == 1) {
// Blink led
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(500);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(3000);
}
}
}
void loop() {
delay(10000);
switch (blink_type) {
case 0:
blink_type = 1;
break;
case 1:
blink_type = 0;
break;
}
}
To not get confused, the "buzzer" output (D1) is currently also wired to an LED.
If there would be a better approach to blink a led in two different ways based on a dynamic variable I'm happy to adopt to this sollution!
normalBlink() and hearthBeatBlink() have delays only when (blink_type == 1). When blink_type becomes 0 there are no delays in the for loops and one of them, the first which evaluates the variable change, happily spins for eternity. Try to add a small delay in the case blink_type is 0. Hope this helps!
Please bear with me. I am an amateur programmer at Arduino, and have never used Particle photon before.
I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it without the OLED screen.
I am now looking into using the same application and function using the same sensor on a Particle Photon (as it is smaller and has WiFi capability). I have never previously used this technology before but I saw online that it, more or less, uses the same code application. I have been through the sample codes for this online available on its website but I have no idea how to convert my code for the Arduino into code for the photon (Photon console compiles the code without any error but does not show any sensor data). Can someone either point me to the right direction/ appropriate online resources / help me change this code here to make it work on the Photon? (I just added the Particle.publish() wherever I was using Arduino's Serial.println() but it still doesn't print anything).
The result in the console shows:
Please be ready
This will now begin
then it prints number 1 to 20 every second followed by sensor readings.
Again sorry for the inconvenience and thank you for your help.
I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):
Grove heart bear sensor
Grove Temperature sensor
#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
//will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate
const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
//2000 meams 2 seconds. System return error
//if the duty overtrip 2 second.
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(9600);
while (!Serial){
;
}
Serial.println("Please be ready");
delay(5000);
arrayInit();
Serial.println("This will now begin.");
attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/
void sum()
{
if(data_effect)
{
heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
Serial.print("Heart_rate_is:\t");
Serial.println(heart_rate);
tempa = analogRead(tempPin);
tempa = tempa * 0.11;
Serial.print("Body Temperature = ");
Serial.print(tempa);
Serial.print("*C");
Serial.println();
delay(1000);
}
data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
temp[counter]=millis();
Serial.println(counter,DEC);
switch(counter)
{
case 0:
sub=temp[counter]-temp[20];
break;
default:
sub=temp[counter]-temp[counter-1];
break;
}
if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
{
data_effect=0;//sign bit
counter=0;
Serial.println("measurement error,test will restart!" );
arrayInit();
}
else if (counter==20&&data_effect)
{
counter=0;
sum();
}
else if(counter!=20&&data_effect)
{
counter++;
}
else
{
counter=0;
data_effect=1;
}
}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
for(unsigned char i=0;i < 20;i ++)
{
temp[i]=0;
}
temp[20]=millis();
}