Stack Overflow Asked by Atay Hassan on February 25, 2021
Hey everyone i am very new to Arduino and c++ and was struggling with some code and was hoping someone can just tell me whats wrong and i can fix it.
Basically i am trying to get a traffic light and a receiver script to run the same time. Currently what happens is once the light cycle is over it runs the receiver code once and only captures one signal being transmitted. I want it to be constantly ready to receive information from the transmitter.
I have tried creating two seperate functions but it still either doesnt work (no lights) or it does the once a cycle thing
#include <RH_ASK.h>
#include <SPI.h>
int ledPins[] = {2,3,4};
RH_ASK rf_driver;
void setup() {
int index;
for (index = 0; index <= 2; index++) { // Intilaize ASK object
rf_driver.init();
// Setup Serial Moniter
Serial.begin(9600);
}
{
pinMode(ledPins[index], OUTPUT);
}
}
void loop() { /****** LOOP: RUNS CONSTANTLY ******/
int oneAfterAnotherLoop();
int RadioController();
} //--(end main loop )---
void oneAfterAnotherLoop() {
int delayTime = 100;
digitalWrite(ledPins[0], HIGH);
delay(4000);
digitalWrite(ledPins[0], LOW);
digitalWrite(ledPins[1], HIGH);
delay(5000);
digitalWrite(ledPins[1], LOW);
digitalWrite(ledPins[2], HIGH);
delay(4000);
digitalWrite(ledPins[2], LOW);
}
void RadioController() {
uint8_t buf[19];
uint8_t buflen = sizeof(buf);
if (rf_driver.recv(buf, &buflen)) {
Serial.print("Message Recived: ");
Serial.println((char*)buf);
}
}
As some people have said, most Arduinos are 1-thread only. However, I refactored your code and this should help solve the problem.
#include <RH_ASK.h>
#include <SPI.h>
int ledPins[] = {2, 3, 4};
RH_ASK rf_driver; // Intilaize ASK object
void setup() {
rf_driver.init(); //start rf_driver
Serial.begin(9600); //begin serial
for (int i = ledPins[0]; i <= ledPins[(sizeof(arr) / sizeof(arr[0])) - 1]; i++) {
//set every pin in ledPins to output (flexible, if ledPins changes no need to change the loop)
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
RadioController(); //only call RadioController() in loop, since oneAfterAnotherLoop() is now called there
}
void oneAfterAnotherLoop() { //left untouched
digitalWrite(ledPins[0], HIGH);
delay(4000);
digitalWrite(ledPins[0], LOW);
digitalWrite(ledPins[1], HIGH);
delay(5000);
digitalWrite(ledPins[1], LOW);
digitalWrite(ledPins[2], HIGH);
delay(4000);
digitalWrite(ledPins[2], LOW);
}
void RadioController() {
uint8_t buf[19];
uint8_t buflen = sizeof(buf);
if (rf_driver.recv(buf, & buflen)) {
Serial.print("Message Recived: ");
Serial.println((char * ) buf);
}
oneAfterAnotherLoop(); //call the loop down here (since most arduinos are singlethreaded, prioritize the listening for communications)
}
Answered by cuchufleto on February 25, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP