Arduino street light with button attachInterrupt - button

I am trying to run a program in Arduino Uno where the street light that has 3 colors, red, yellow and green, and when I press a button, the street light goes from green to yellow to red and then the pedestrian street light goes from red to green, just like a normal street light. Problem is my program does not read my button when it's pressed for some reason, I thought it was maybe the protoboard or the Arduino but when I try to run it on circuits.io the result is the same, leading me to the conclusion that my code is what is wrong. So here it is:
//libreria
#define EVENT_NONE 0
#define EVENT_EVERY 1
#define EVENT_OSCILLATE 2
#define MAX_NUMBER_OF_EVENTS (10)
#define TIMER_NOT_AN_EVENT (-2)
#define NO_TIMER_AVAILABLE (-1)
class Event {
public:
Event(void);
void update(void);
void update(unsigned long now);
int8_t eventType;
unsigned long period;
int repeatCount;
uint8_t pin;
uint8_t pinState;
void (*callback)(void);
unsigned long lastEventTime;
int count;
};
Event::Event(void)
{
eventType = EVENT_NONE;
}
void Event::update(void)
{
unsigned long now = millis();
update(now);
}
void Event::update(unsigned long now)
{
if (now - lastEventTime >= period) {
switch (eventType) {
case EVENT_EVERY:
(*callback)();
break;
case EVENT_OSCILLATE:
pinState = !pinState;
digitalWrite(pin, pinState);
break;
}
lastEventTime = now;
count++;
}
if (repeatCount > -1 && count >= repeatCount) {
eventType = EVENT_NONE;
}
}
//libreria timer
class Timer {
public:
Timer(void);
int8_t every(unsigned long period, void (*callback)(void));
int8_t every(unsigned long period, void (*callback)(void), int repeatCount);
int8_t after(unsigned long duration, void (*callback)(void));
int8_t oscillate(uint8_t pin, unsigned long period, uint8_t startingValue);
int8_t oscillate(uint8_t pin, unsigned long period, uint8_t startingValue, int repeatCount);
/**
* This method will generate a pulse of !startingValue, occuring period after the
* call of this method and lasting for period. The Pin will be left in !startingValue.
*/
int8_t pulse(uint8_t pin, unsigned long period, uint8_t startingValue);
/**
* This method will generate a pulse of pulseValue, starting immediately and of
* length period. The pin will be left in the !pulseValue state
*/
int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
void stop(int8_t id);
void update(void);
void update(unsigned long now);
protected:
Event _events[MAX_NUMBER_OF_EVENTS];
int8_t findFreeEventIndex(void);
};
Timer::Timer(void)
{
}
int8_t Timer::every(unsigned long period, void (*callback)(), int repeatCount)
{
int8_t i = findFreeEventIndex();
if (i == -1)
return -1;
_events[i].eventType = EVENT_EVERY;
_events[i].period = period;
_events[i].repeatCount = repeatCount;
_events[i].callback = callback;
_events[i].lastEventTime = millis();
_events[i].count = 0;
return i;
}
int8_t Timer::every(unsigned long period, void (*callback)())
{
return every(period, callback, -1); // - means forever
}
int8_t Timer::after(unsigned long period, void (*callback)())
{
return every(period, callback, 1);
}
int8_t Timer::oscillate(uint8_t pin, unsigned long period, uint8_t startingValue, int repeatCount)
{
int8_t i = findFreeEventIndex();
if (i == NO_TIMER_AVAILABLE)
return NO_TIMER_AVAILABLE;
_events[i].eventType = EVENT_OSCILLATE;
_events[i].pin = pin;
_events[i].period = period;
_events[i].pinState = startingValue;
digitalWrite(pin, startingValue);
_events[i].repeatCount = repeatCount * 2; // full cycles not transitions
_events[i].lastEventTime = millis();
_events[i].count = 0;
return i;
}
int8_t Timer::oscillate(uint8_t pin, unsigned long period, uint8_t startingValue)
{
return oscillate(pin, period, startingValue, -1); // forever
}
/**
* This method will generate a pulse of !startingValue, occuring period after the
* call of this method and lasting for period. The Pin will be left in !startingValue.
*/
int8_t Timer::pulse(uint8_t pin, unsigned long period, uint8_t startingValue)
{
return oscillate(pin, period, startingValue, 1); // once
}
/**
* This method will generate a pulse of startingValue, starting immediately and of
* length period. The pin will be left in the !startingValue state
*/
int8_t Timer::pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue)
{
int8_t id(oscillate(pin, period, pulseValue, 1));
// now fix the repeat count
if (id >= 0 && id < MAX_NUMBER_OF_EVENTS) {
_events[id].repeatCount = 1;
}
return id;
}
void Timer::stop(int8_t id)
{
if (id >= 0 && id < MAX_NUMBER_OF_EVENTS) {
_events[id].eventType = EVENT_NONE;
}
}
void Timer::update(void)
{
unsigned long now = millis();
update(now);
}
void Timer::update(unsigned long now)
{
for (int8_t i = 0; i < MAX_NUMBER_OF_EVENTS; i++) {
if (_events[i].eventType != EVENT_NONE) {
_events[i].update(now);
}
}
}
int8_t Timer::findFreeEventIndex(void)
{
for (int8_t i = 0; i < MAX_NUMBER_OF_EVENTS; i++) {
if (_events[i].eventType == EVENT_NONE) {
return i;
}
}
return NO_TIMER_AVAILABLE;
}
This code was just a way to import the libraries since the circuits.io cannot use the #include Timer library
And this is the actual code:
// Street Light Code
int redCar = 12;
int yellowCar = 11;
int greenCar = 10;
int redWalk = 9;
int greenWalk = 8;
const int button = 2;
unsigned long lightChange = 1000;
volatile int buttonState = 0;
Timer t;
void setup() {
pinMode(redCar, OUTPUT);
pinMode(yellowCar, OUTPUT);
pinMode(greenCar, OUTPUT);
pinMode(redWalk, OUTPUT);
pinMode(greenWalk, OUTPUT);
pinMode(button, INPUT);
attachInterrupt(0, interrupcion, RISING);
digitalWrite(greenCar, HIGH);
digitalWrite(redWalk, HIGH);
}
void loop() {
t.update();
}
void interrupcion() {
buttonState = digitalRead(button);
start();
}
void start() {
digitalWrite(greenCar, HIGH);
digitalWrite(yellowCar, LOW);
digitalWrite(redCar, LOW);
digitalWrite(greenWalk, LOW);
digitalWrite(redWalk, HIGH);
t.after(lightChange, green_light_car);
}
void green_light_car() {
t.oscillate(greenCar, 50, LOW, 10);
digitalWrite(yellowCar, LOW);
digitalWrite(redCar, LOW);
digitalWrite(greenWalk, LOW);
digitalWrite(redWalk, HIGH);
t.after(lightChange, yellow_light_car);
}
void yellow_light_car() {
digitalWrite(greenCar, LOW);
digitalWrite(yellowCar, HIGH);
digitalWrite(redCar, LOW);
digitalWrite(greenWalk, LOW);
digitalWrite(redWalk, HIGH);
t.after(lightChange, red_light_car);
}
void red_light_car() {
digitalWrite(greenCar, LOW);
digitalWrite(yellowCar, LOW);
digitalWrite(redCar, HIGH);
digitalWrite(greenWalk, HIGH);
digitalWrite(redWalk, LOW);
t.after(lightChange, green_light_walk);
}
void green_light_walk() {
digitalWrite(greenCar, LOW);
digitalWrite(yellowCar, LOW);
digitalWrite(redCar, HIGH);
t.oscillate(greenWalk, 50, LOW, 10);
digitalWrite(redWalk, LOW);
t.after(lightChange, red_light_walk);
}
void red_light_walk() {
digitalWrite(greenCar, HIGH);
digitalWrite(yellowCar, LOW);
digitalWrite(redCar, LOW);
digitalWrite(greenWalk, LOW);
digitalWrite(redWalk, HIGH);
t.after(lightChange, interrupcion);
}

You are attaching the interrupt to digital pin 0, which doesn't seem to be connected to anything based on the source code you show. Also in your interrupt service routine, you read the button into the variable buttonState, but you don't access that variable anywhere else in the code.

Related

AttachIntrerrupt stops NRF24L01+ from working - ARDUINO

If I remove attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING); The code works. But once its added, the radio.available doesnt let anything under it run.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
struct InputData // define stuct
{
int x;
int y;
};
InputData data;
// Motor A connections
int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;
int encoder1 = 2;
int encoder2 = 3;
int counter = 0;
int angle = 0;
void setup() {
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1, address);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
// Set all the motor control pins to outputs
pinMode(motor_enA, OUTPUT);
pinMode(motor_in1, OUTPUT);
pinMode(motor_in2, OUTPUT);
// Turn off motors - Initial state
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
analogWrite(motor_enA, 255);
pinMode (encoder1, INPUT);
pinMode (encoder2, INPUT);
attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING);
}
void loop() {
readEncoder();
if (radio.available()) {
radio.read(&data, sizeof(data));
// Serial.println(data.y);
if (data.y > 5) {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
else if (data.y < -5) {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
else {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
}
}
if(counter>1){
counter=0;
angle+=2;
}else if(counter<-1){
counter=0;
angle-=2;
}
Serial.print("Position: ");
Serial.println(angle);
}
void readEncoder()
{
if(digitalRead(encoder1)==HIGH){
int b = digitalRead(encoder2);
if(b>0){
counter++;
}
else{
counter--;
}
}
}
I have tried removing and adding the line, as described above^^
as mentioned by Hcheung, make counter volatile and remove readEncoder(); from loop.
I simplify a bit ISR readEncoder();
volatile int counter = 0;
[....]
void readEncoder() {
//if(digitalRead(encoder1)==HIGH){ //we are precisely here because digitalRead(encoder1) = HIGH !
if(digitalRead(encoder2)) counter++;
else counter--;
}

Implementing the function interrupt with if statements

I want to implement the function interrupt () but I don't know exactly how..In this case there is 2 for loops which can be seen in the code:I want whenever one of the 2 buttons is pressed the process inside the loop to be interrupted immediately:
void loop() {
int brightButton = digitalRead(K1);
int ldrStatus = analogRead(ldrPin);
if (brightButton == LOW && ldrStatus >= 200)
{
for (int i = 0; i < 10; i++)
{
digitalWrite(greenLed, HIGH);
tone(buzzer,400);
delay(500);
noTone(buzzer);
delay(500);
}
}
else {
digitalWrite(greenLed, LOW);
}
int tempButton = digitalRead(K2);
int valNTC = analogRead(NTC);
if (tempButton == LOW && valNTC > 512)
{
for (int i = 0; i <10; i++)
{
digitalWrite(redLed, HIGH);
tone(buzzer,450);
delay(300);
noTone(buzzer);
delay(1000);
}
}
else {
digitalWrite(redLed, LOW);
}
}
Example code from the Arduino manual:
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
Note that this will interrupt the for loop and return to it once the interrupt service routine is finished.
If you want to abort the for loop check the pin state in every loop cycle and break if you want to leave the for loop or return if you want to leave loop().
Of course this is not "immediately".

Three Xbee synchronization blinking

I'm doing synchronization blinking with three XBee module and Arduino Uno,
the first is master, second is slave/master and the other one is a slave.
The master is going to give the command for both slave/master and slave to blinking, and when the master is switch off, the slave/master will taking over his job giving the command to blinking.
But the slave/master didn't go so well because of the coding didn't right.
Can anyone take a look at my coding and show me what is wrong with my coding.
Master Coding =
#include <SoftwareSerial.h>
#define Dout 2
#define Din 3
//#define LED 9
SoftwareSerial XBee(Dout, Din);
//char XBee_message;
int MasterSignalSent = 0;
const long interval = 2500;
unsigned long previousMillis = 0;
void setup() {
Serial.begin(9600);
XBee.begin(9600);
pinMode(13, OUTPUT);
}
void loop(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
Serial.println(currentMillis);
previousMillis = currentMillis;
{
delay(1500);
SendMasterSignal();//+
MasterSignalSent = 1;
delay(1000);
SendSyncSignal();//-
BlinkLed();
MasterSignalSent = 0;
}
}
}
void SendMasterSignal()
{
Serial.println("SendingMasterSignal. . .");
XBee.write('+');
}
void SendSyncSignal()
{
Serial.println("SendingSyncSignal. . .");
XBee.write('-');
}
void BlinkLed()
{
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
//delay(2200);
}
Slave/Master Coding =
#include <SoftwareSerial.h>
#define Dout 2
#define Din 3
SoftwareSerial XBee (Dout, Din);
const long interval = 2500;
unsigned long previousMillis = 0;
int MasterSignalReceived = 0;
int ReceiveSyncSignal = 0;
int MasterSignalSent = 0;
char XBee_signal;
void setup() {
Serial.begin(9600);
XBee.begin(9600);
pinMode(13, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
while(XBee.available()){
XBee_signal = XBee.read();
Serial.println(XBee_signal);
delay(1500);
if (MasterSignalReceived == 0)
{
BecomeMaster();
}
else if (MasterSignalReceived == 1)
{
if (XBee_signal = '-'){
BlinkLed();
(MasterSignalReceived = 0);
}
else{
digitalWrite(13, LOW);
}
}
}
}
}
void BecomeMaster()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
Serial.println(currentMillis);
previousMillis = currentMillis;
{
delay(1500);
SendMasterSignal();
MasterSignalSent = 1;
delay(2500);
SendSyncSignal();
BlinkLed();
MasterSignalSent = 0;
}
}
}
void SendMasterSignal()
{
XBee.write('+');
Serial.println("SendMasterSignalDone");
}
void SendSyncSignal()
{
XBee.write('-');
Serial.println("SendSyncSignalDone");
}
void BlinkLed()
{
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
}
The slave is waiting for the command to blinking but the slave/master didn't send any command as the coding write when the master switches off.

LED pins on Arduino aren't being initialized when using classes

I'm trying to implement classes in my traffic lights program. The issues I'm facing are that the lights do not blink and the inherited class does not seem to work. How can I fix them?
class Sensors {
public:
Sensors(int echopin, int trigpin);
Sensors();
void init();
double light();
double sensor();
// protected:
int ECHOPIN;
int TRIGPIN;
};
class Mode: public Sensors
//Add the VARIABLES into the CLASSES from the FUNCTIONS
{
public: Mode(int gled, int yled, int rled, int Delay1);
void init();
void mode1();
void mode2();
void mode3();
double sensor() {
Sensors::sensor();
}
private: int Gled;
int Yled;
int Rled;
int Delay;
};
Sensors sense(3, 2);
Mode mode(13, 12, 11, 2000);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
sense.init();
mode.init();
}
void loop() {
double measure;
double lightValue;
double MAXDISTANCE = 10;
double MAXLIGHT = 140;
measure = sense.sensor();
lightValue = sense.light();
if (measure < MAXDISTANCE) {
mode.mode2();
} else if (lightValue < MAXLIGHT) {
while (lightValue < MAXLIGHT) {
mode.mode3();
lightValue = sense.light();
}
} else {
mode.mode1();
}
}
Sensors::Sensors(int echopin, int trigpin) {
ECHOPIN = echopin;
TRIGPIN = trigpin;
}
Sensors::Sensors() {
ECHOPIN;
TRIGPIN;
}
double Sensors::light() {
//LIGHT SENSOR
int sensorPin = A0;
unsigned int value = 0;
value = analogRead(sensorPin);
Serial.print("Light value is: ");
Serial.println(value);
return value;
}
double Sensors::sensor() {
//Measure the distance for the RANGE FINDER
double distance;
double Time;
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
Time = pulseIn(ECHOPIN, HIGH);
distance = (Time * 340) / 20000;
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm \n");
return distance;
}
void Sensors::init() {
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
Mode::Mode(int gled, int yled, int rled, int Delay1) {
int Gled = gled;
int Yled = yled;
int Rled = rled;
int Delay = Delay1;
}
void Mode::init() {
pinMode(Gled, OUTPUT);
pinMode(Yled, OUTPUT);
pinMode(Rled, OUTPUT);
}
void Mode::mode1() {
//First Mode
digitalWrite(Gled, LOW);
digitalWrite(Rled, HIGH); //RED ON
delay(Delay);
digitalWrite(Rled, LOW);
digitalWrite(Yled, HIGH); //YELLOW ON
Delay -= 1000;
delay(Delay);
digitalWrite(Yled, LOW);
digitalWrite(Gled, HIGH); //GREEN ON
Delay += 1000;
delay(Delay);
digitalWrite(Yled, HIGH); //YELLOW ON
digitalWrite(Gled, LOW);
Delay -= 1000;
delay(Delay);
}
void Mode::mode2() {
int DELAY = 100;
int Y_LOOP = 10;
int buzz = 4;
pinMode(buzz, OUTPUT);
for (int i = 0; i < Y_LOOP; i++) {
tone(buzz, 20);
digitalWrite(Yled, HIGH);
delay(DELAY);
digitalWrite(Yled, LOW);
delay(DELAY);
}
noTone(buzz);
}
void Mode::mode3() {
double measure;
delay(1000);
measure = sensor();
if (measure < 10) {
digitalWrite(Rled, LOW);
digitalWrite(Gled, HIGH);
} else {
digitalWrite(Rled, HIGH);
digitalWrite(Gled, LOW);
}
delay(1000);
}
I expect the sensor method to return a distance, but it only does so the first time. When it is called as an inherited method it returns 0.
This code can be simplified to
struct foo
{
int myX;
foo(int x)
{
int myX = x;
}
};
int main()
{
foo f(42);
// f.myX is still garbage because in constuctor you initialize
// a local variable myX instead of object field
return 0;
}
So you should initialize class field in member initializer list instead:
foo(int x): myX{x}
{
// empty
}

Arduino program that allows me to change state through comm port?

new here! been recommended many times to come here for help so here I am.
I'm supposed to write a program that allows me to change the rate of a blinking LED light through the comm port. I'm sure this is easy but I've honestly got no clue as I am behind in this class.
anything would help really, i honestly want to learn how to do this, not just come here and get the answer.
thanks in advanced!
// global variables
#include <EEPROM.h>
unsigned long ms_runtime;
int state;
// possible values 0 -> 1 -> 2 -> 3 -> 0
int one_ms_timer;
// define all timers as unsigned long (they are incremented every 100ms = 0.1s)
unsigned long timer1;
unsigned long button_dbnc_tmr = 0;
// timer1 is used for blinking LED
const int LED1 = 13;
// function prototypes
void read_memory(void);
void update_memory(void);
void comm_control(void);
void led_control(void);
void turnoff(void);
void flash_1s(void);
void flash_2s(void);
void flash_3s(void);
void timers(void);
void setup()
{
read_memory();
pinMode(LED1, OUTPUT);
Serial.begin(9600);
//initialize uart
}
void loop()
{
static bool allow_change;
static int counter;
timers();
comm_control();
led_control();
}
void led_control()
{
switch (state)
{
case 0:
turnoff();
break;
case 1:
flash_1s();
break;
case 2:
flash_2s();
break;
case 3:
flash_3s();
break;
}
}
void turnoff()
{
digitalWrite(LED1, LOW);
}
void flash_1s()
{
if (timer1 < 10)
digitalWrite(LED1, HIGH);
else
{
digitalWrite(LED1, LOW);
if (timer1 >= 20)
timer1 = 0;
}
}
void flash_2s()
{
if (timer1<20)
digitalWrite(LED1, HIGH);
else
{
digitalWrite(LED1, LOW);
if (timer1 >= 30)
timer1 = 0;
}
}
void flash_3s()
{
if (timer1<30)
digitalWrite(LED1, HIGH);
else
{
digitalWrite(LED1, LOW);
if (timer1 >= 40)
timer1 = 0;
}
}
void read_memory()
{
timer1 = EEPROM.read(one_ms_timer);
timer1++;
EEPROM.write(one_ms_timer, timer1);
Serial.begin(9600);
}
void update_memory()
{
EEPROM.update(timer1, one_ms_timer);
}
void comm_control(void);
{
char comm_reveier = serial_read;
if (
)
}
void timers(void)
{
if (millis() > (ms_runtime + 1))
{
ms_runtime = ms_runtime + 1;
one_ms_timer++;
}
else if (ms_runtime > millis())
ms_runtime = millis();
if (one_ms_timer > 99) //every 100 ms
{
one_ms_timer = 0;
button_dbnc_tmr++;
timer1++;
}
}
Load the Standard Firmata library on your Arduino board. Then use a library of your choice to build your comm prog. An overview of these can be found here.
Assuming you are using the Arduino IDE, this code sample should give you the general idea of what you need to do:
// pins for the LEDs:
const int ledPin = 13;
// Default blink rate
int rate = 1000;
void setup() {
// initialize serial:
Serial.begin(9600);
// make the pins outputs:
pinMode(ledPin, OUTPUT);
}
void loop() {
// if there's any serial available, read it:
while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
int rate = Serial.parseInt();
}
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(rate); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(rate); // wait for a second
}

Resources