I Am having problems in my code... i am using a ac dimmer module with arduino and i want to make the light glow for 5sec and then blink twice then repeat
int AC_LOAD = 3; // Output to Opto Triac pin
int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF
void setup()
{
pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
attachInterrupt(0, zero_crosss_int, RISING); // Choose the zero cross interrupt # from the table above
}
//the interrupt function must take no parameters and return nothing
void zero_crosss_int() //function to be fired at the zero crossing to dim the light
{
// Firing angle calculation : 1 full 50Hz wave =1/50=20ms
// Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
// For 60Hz => 8.33ms (10.000/120)
// 10ms=10000us
// (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65
int dimtime = (75*dimming); // For 60Hz =>65
delayMicroseconds(dimtime); // Wait till firing the TRIAC
digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC
delayMicroseconds(10); // triac On propogation delay
// (for 60Hz use 8.33) Some Triacs need a longer period
digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}
void loop()
{
{
int e = 5;
dimming = e;
delay(200);
}
{
for (int i=128; i >= 5; i--){
dimming=i;
delay(2);
}
for (int j=5; j <= 128; j++){
dimming=j;
delay(2); // this value is the light delay timing
}
//delay(3); // this value is the gap timing
for (int i=128; i >= 5; i--){
dimming=i;
delay(2);
}
for (int j=5; j <= 128; j++){
dimming=j;
delay(2); // this value is the light delay timing
}
//delay(3); // this value is the gap timing
}}
when i use this code the light doesnt glow for 5 sec and then blink . it gets a 5 sec delay and then blinks
{
int e = 5;
dimming = e;
delay(200);
}
but if i use only this part of the code with the codes below it. it glows
i am really new to programming please help me out
The 5 second delay you're observing is the boot time of the Arduino. Arduinos bootloader will wait for new firmeware befor your sketch is executed.
If you want to have your light on for 5 seconds, replace delay(200); by delay(5000);.
Related
I'm trying to make an arduino UNO circuit that allows me to set the blinking duration of an LED with two pushbuttons, but I'm having trouble with the program. First of all, the default blinking duration is 0,5 s. And I want to program the first pushbutton to be able to extend the blinking duration by 0,1 seconds, whereas the second one is for speeding up the duration by 0,1 seconds.
So in my current code, I use if statements to check whether the two buttons are pressed or not. If the inc button is pressed, the program should increase the duration by 100 ms, whereas when dec button is pressed, the program should decrease the duration by 100 ms.
However when I run it on the arduino circuit, the duration is stuck in 600 and 500. So in every loop, the program adds 100 ms to the duration time and then decreases it again by 100, even when I do nothing to the buttons.
Here's my code so far:
const int led = 7;
const int buttonUp = 6;
const int buttonDown = 5;
int duration = 500;
void setup(){
pinMode(led, OUTPUT);
pinMode(buttonUp, INPUT);
pinMode(buttonDown, INPUT);
Serial.begin(9600);
}
void loop(){
int inc = digitalRead(buttonUp);
int dec = digitalRead(buttonDown);
if(inc == HIGH){
duration += 100;
Serial.println(duration);
}
if(dec == HIGH){
duration -= 100;
if(duration < 0){
duration = 100;
}
Serial.println(duration);
}
digitalWrite(led, HIGH);
delay(duration);
digitalWrite(led, LOW);
delay(duration);
}
the code and circuit
serial monitor
Will be extremely grateful if anyone can point out any mistakes!! Thank you!
duration is 500ms. So you basically poll your button states once every second. The time window where you can detect a button click is very short compared to the time you cannot detect it. So chances that you register a click are very little. You need to push the button for at least a second to capture the signal every time.
If you push both buttons you add and subtract 100. That's a total change of 0. What do you expect?
This can be avoided by checking your button state more frequently or by using interrupts.
Find out how to use non-blocking delays and interrupts. The internet is full of tutorials.
bool blink(unsigned int duration) {
// demo code only
// (usable only once per sketch, due to static variables)
static unsigned long last;
static bool state;
if (millis() - last >= duration) {
last = millis();
state = ! state;
}
return state;
}
This is the BlinkWithoutDelay pattern. Usage:
digitalWrite(led,blink(duration));
Button handling is trickier than a beginner thinks: often you want to detect a state change between pressed and released, and you want to ignore the bouncing of a mechanical switch happening during a state change. Or you want to repeat some action, when the button is pressed for a long time.
Easiest you do a little delay(10); after detecting a state change to pass the bouncing time. Or look for libraries doing all that button handling.
Or do such a lazy delay anyway, to slow down your fast microcontroller below button bouncing speed.
const int led = 7;
const int buttonUp = 6;
const int buttonDown = 5;
void setup(){
pinMode(led, OUTPUT);
pinMode(buttonUp, INPUT);
pinMode(buttonDown, INPUT);
Serial.begin(9600);
}
unsigned int duration = 500;
int lastbutton = 0; // 0 / -100 / +100 to detect button changes
void loop(){
bool inc = digitalRead(buttonUp);
bool dec = digitalRead(buttonDown);
delay(5); // debounce
if( (inc || dec) && lastbutton == 0){
lastbutton = (inc - dec) * 100;
duration += lastbutton;
if (duration == 0) duration = 100; // Minimum
Serial.println(duration);
}
if (lastbutton != 0 && !inc && !dec) lastbutton = 0;
digitalWrite(led, blink(duration) );
}
I am using a zumo bot with a reflectance sensor used to follow a black line. I want to use an arduino to make the zumo bot stop once it gets a certain distance from an obstacle.
I have an ultrasonic sensor (HC-SR04) which ive connected to the bot.
Both of these tasks work independently but once i merge the code together(so it follows the line aswell as stoping when it detects an object using the ultrasonic sensor), it doesn't work properly.. (the zumo bot no longer follows the line)
I THINK it is to do with the pulsein() function blocking any other tasks but not sure.
My code is below. Can anyone help please?
#include <ZumoShield.h>
ZumoBuzzer buzzer;
ZumoReflectanceSensorArray reflectanceSensors;
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
int lastError = 0;
// This is the maximum speed the motors will be allowed to turn.
// (400 lets the motors go at top speed; decrease to impose a speed limit)
const int MAX_SPEED = 400;
#define echoPin A4
#define trigPin A5
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup()
{
reflectanceSensors.init();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Initialize the reflectance sensors module
// Wait for the user button to be pressed and released
button.waitForButton();
// Turn on LED to indicate we are in calibration mode
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// Wait 1 second and then begin automatic sensor calibration
// by rotating in place to sweep the sensors over the line
delay(1000);
int i;
for(i = 0; i < 80; i++)
{
if ((i > 10 && i <= 30) || (i > 50 && i <= 70))
motors.setSpeeds(-200, 200);
else
motors.setSpeeds(200, -200);
reflectanceSensors.calibrate();
// Since our counter runs to 80, the total delay will be
// 80*20 = 1600 ms.
delay(20);
}
motors.setSpeeds(0,0);
// Turn off LED to indicate we are through with calibration
digitalWrite(13, LOW);
// Wait for the user button to be pressed and released
button.waitForButton();
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}
void loop()
{
unsigned int sensors[6];
// Get the position of the line. Note that we *must* provide the "sensors"
// argument to readLine() here, even though we are not interested in the
// individual sensor readings
int position = reflectanceSensors.readLine(sensors);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Our "error" is how far we are away from the center of the line, which
// corresponds to position 2500.
int error = position - 2500;
// Get motor speed difference using proportional and derivative PID terms
// (the integral term is generally not very useful for line following).
// Here we are using a proportional constant of 1/4 and a derivative
// constant of 6, which should work decently for many Zumo motor choices.
int speedDifference = error / 4 + 6 * (error - lastError);
lastError = error;
// Get individual motor speeds. The sign of speedDifference
// determines if the robot turns left or right.
int m1Speed = MAX_SPEED + speedDifference;
int m2Speed = MAX_SPEED - speedDifference;
if (m1Speed < 0)
m1Speed = 0;
if (m2Speed < 0)
m2Speed = 0;
if (m1Speed > MAX_SPEED)
m1Speed = MAX_SPEED;
if (m2Speed > MAX_SPEED)
m2Speed = MAX_SPEED;
motors.setSpeeds(m1Speed, m2Speed);
//if (distance <20){
// motors.setSpeeds(0,0);
// }
////////////////////////////////////////////
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} ```
Of course pulseIn is blocking function. Arduino project is open source, you can easily check source code
Here is C equivalent countPulseASM function which does measurement.
unsigned long pulseInSimpl(volatile uint8_t *port, uint8_t bit, uint8_t stateMask, unsigned long maxloops)
{
unsigned long width = 0;
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to start
while ((*port & bit) != stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to stop
while ((*port & bit) == stateMask) {
if (++width == maxloops)
return 0;
}
return width;
}
If you need measure pulse length in non blocking way, use hw counters.
I'm using an Arduino Uno to control LED. I want the LED to turn on every m seconds and remain ON for n seconds.
I've tried this code using the delay() function (by adding delays after LED is turned ON and OFF) and also using the millis() function (by keeping a track of the time passed since the previous event - ON/OFF). However, in both the approaches, the LED develops a lag of ~1 second after a few (!10) iterations of the ON-OFF cycle. What can I do to increase the accuracy of the time at which the events occur?
int led = 13;
long experimentTime = 240000;
long ledOFFDuration = 8000;
void setup() {
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
for (int i = 0; i < 100; i++){
digitalWrite(led, HIGH);
delay(10000);
digitalWrite(led, LOW);
delay(10000);
}
}
I've also tried using the watchdog timer (shown below). However, it has the same issue:
#include <avr/wdt.h>
int led = 13;
volatile byte watchDogState = 0b01000000;
volatile int counter = 0;
int counterMax = 5;
bool state = 1;
void setup() {
// put your setup code here, to run once:
wdt_disable();
pinMode(led, OUTPUT);
digitalWrite(led, 1);
setWDT(watchDogState);
}
void loop() {
// put your main code here, to run repeatedly:
// if (time_elapsed == 40){
//state = !state;
//}
}
void setWDT(byte sWDT){
WDTCSR |= 0b00011000;
WDTCSR = sWDT | WDTO_2S;
wdt_reset();
}
ISR (WDT_vect){
counter++;
if (counter >= counterMax){
state = !state;
digitalWrite(led, state);
counter = 0;
}
}
I tried using the port registers directly to avoid using digitalWrite completely. But that doesn't work either. There's a lag of ~5s after 20 minutes using the following code:
int led = 13;
int m = 10;
int n = 10;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = millis();
if (!on && change < now) {
on = true; //led is now on
change = now + n*1000; //turn off in <n> seconds
PORTB |= B00100000;
}
else if (on && change < now){
on = false; //led is now off
change = now + m*1000; //turn on in <m> seconds
PORTB &= B11011111; // Set pin 4 to 0
}
}
The lag is caused by the digitalWrite-calls. Your processing application waits until digitalWrite has finished and this may take 0.05 seconds or so. To fix your problem I would save the current time in milliseconds.
int led = 13;
int m = 24;
int n = 8;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = System.currentTimeMillis();
if (!on && change < now) { //led is off and time for change has come
on = true; //led is now on
change = += n*1000; //turn off in <n> seconds
digitalWrite(led, HIGH); //turn on led
} else if (on && change < now) { //led is on and time for change has come
on = false; //led is now off
change = += m*1000; //turn on in <m> seconds
digitalWrite(led, LOW); //turn off led
}
}
the lamp will now instantly turn on on startup, wait n seconds, turn off, wait m seconds and restart from the beginning.
If you want to create a delay at the beginning so that the lamp doesn't get turned on immediately you can simply add this to your setup-function:
change = now + SECONDS*1000;
EDIT
You pointed out that it still gives you lag.
One problem might be that loop() is not run every millisecond. So I maybe got a solution for you.
Replace the following two lines:
change = now + n*1000; //turn off in <n> seconds
...
change = now + m*1000; //turn on in <m> seconds
to this:
change += n*1000; //turn off in <n> seconds
...
change += m*1000; //turn on in <m> seconds
Now it won't take the current time anymore which means that even if loop is only run every second or two it should still not cause any lag.
If this won't work I'm afraid it looks like the timer on the arduino might not be the most precise one. If this is the case try to measure the exact offset and then create a miltiplicator for the time.
I want to implement a simple LED controller with an Arduino Uno, that goes to sleep and has different buttons.
Functions of buttons are:
Digital 2: Button for ON OFF
Digital 3: Button for Wake up
Everything works ok, but when it goes to sleep, the LEDs also turn off. I want that after 30 seconds, when Arduino goes to sleep, lights stays on.
Here is my code:
#include <avr/sleep.h>
#define REDPIN 10
#define GREENPIN 11
#define BLUEPIN 9
#define delayTime 20 //za fading cas
unsigned long interval= 30000;
unsigned long previousMillis = 0;
const int ledPin = 12; // the pin that the LED is attached to
const int buttonPin1 = 2; //on off
bool vklop = false;
int bela = 10;
int barva;
int prejsnja_barva = 0;
int buttonPushCounter1 = 0; // counter for the number of button presses
int buttonState1 = 0; // current state of the button
int lastButtonState1 = 0; // previous state of the button
/////////////////////////////////////*SETUP*/////////////////////////////////////////
void setup()
{
pinMode(buttonPin1, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
pinMode(3,INPUT); //because of interrupts PIN digital 3
digitalWrite(3,HIGH);
}
/////////////////////////////////////*LOOP*/////////////////////////////////////////
void loop()
{
unsigned long currentMillis = millis();
if ((currentMillis-previousMillis) > interval) //15s timer
{
previousMillis = currentMillis;
Serial.println("SLEEP!"); // kaj delaj po preteku 5s
delay(50);
sleepSetup(); //sleep mode
}
else
{
buttonState1 = digitalRead(buttonPin1);
/////////////////////////////////////ON/OFF/////////////////////////////////////////
/////////////////////////////////////ON/OFF/////////////////////////////////////////
if (buttonState1 != lastButtonState1) // compare the buttonState to its previous state
{
if (buttonState1 == HIGH) // if the state has changed, increment the counter
{
buttonPushCounter1++; // if the current state is HIGH then the button went from off to on:
Serial.println("on");
Serial.print("number of BUTTON1 pushes: ");
Serial.println(buttonPushCounter1);
digitalWrite(ledPin, HIGH);
if(buttonPushCounter1 % 2 == 0)
{
setColor(bela, bela, bela);
vklop = true;
barva = 13;
}
else
{
setColor(0, 0, 0);
vklop = false;
}
}
else // if the current state is LOW then the button went from on to off:
{
Serial.println("off");
digitalWrite(ledPin, LOW);
}
delay(50); // Delay a little bit to avoid bouncing
}
lastButtonState1 = buttonState1; // save the current state as the last state, for next time through the loop
}
}
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
void setColor(int red, int green, int blue)
{
analogWrite(REDPIN, red);
analogWrite(GREENPIN, green);
analogWrite(BLUEPIN, blue);
}
void sleepSetup(void)
{
sleep_enable(); // Set sleep enable (SE) bit:
attachInterrupt(1, pinInterrupt, LOW); // Set pin 2 as interrupt and attach handler:
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // define our preferred sleep mode:
digitalWrite(13,LOW);
sleep_cpu();
Serial.println("Just woke up!"); //OD TU SE NADALJUJE PO PRITISKU TIPKE
digitalWrite(13,HIGH);
}
void pinInterrupt() //ISR
{
sleep_disable();
detachInterrupt(0);
}
You're using AVR's Power Down sleep mode. In this mode all timers are turned off to save power.
No timers -> no PWM -> no analogue output -> no PWM driven LEDs
To keep the LED on use another sleep mode.
See
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf for details.
But to be honest I am not quite sure if this makes any sense. If you're driving an LED through 3 outputs the power you can save by putting the MCU into sleep is maybe a few percent.
And as sleep stops the CPU and hence your program you won't be able to have the LEDs turn off after 30s.
Why not just wait 30s befor going to sleep? The alternative would be some external timing circuitry that would also consume power. So I guess having a few milliamps more for 30 seconds is still a better alternative.
I have two separate sketches and the pressure sensor and the pulse sensor are working fine. Alone, these are fine, but when I try to combine both they stop working on me. How can I fix this problem?
//Code for pressure sensor
int fsrAnalogPin = 0; // FSR is connected to analog 0
int LEDpin0 = 11; // Connect red LED to pin 11 (PWM pin)
int LEDpin1 = 10;
int LEDpin2 = 9;
int fsrReading; // The analog reading from the FSR resistor divider.
int LEDbrightness;
void setup(void) {
Serial.begin(9600); // We'll send debugging information via the Serial monitor.
pinMode(LEDpin0, OUTPUT);
pinMode(LEDpin1, OUTPUT);
pinMode(LEDpin2, OUTPUT);
}
void loop(void) {
fsrReading = analogRead(fsrAnalogPin);
Serial.print("Analog reading = ");
Serial.println(fsrReading);
// We'll need to change the range from the analog reading (0-1023) down to the range
// used by analogWrite (0-255) with map!
LEDbrightness = map(fsrReading, 0, 1023, 1, 255);
// LED gets brighter the harder you press.
analogWrite(LEDpin0, LEDbrightness);
analogWrite(LEDpin1, LEDbrightness);
analogWrite(LEDpin2, LEDbrightness);
delay(100);
}
//Code for pulse sensor comes in two tabs this is the first tab.
int analogPinR = 11;
int analogPinG = 10;
int analogPinB = 9;
//The buffer
int RGB[9];
//Values of red, green and blue.
int R=0;
int G=0;
int B=0;
int pulsePin = 1; // Pulse Sensor purple wire connected to analog pin 0.
int fadeRate = 0; // Used to fade LED on with PWM on fadePin.
//int fadePin = 9; // Pin to do fancy classy fading blink at each beat.
//int fadePin1 = 10; // Pin to do fancy classy fading blink at each beat.
//int fadePin2 = 11; // Pin to do fancy classy fading blink at each beat.
// These variables are volatile, because they are used during the interrupt service routine!
volatile int BPM; // Used to hold the pulse rate..
volatile int Signal; // Holds the incoming raw data.
volatile int IBI = 600; // Holds the time between beats, the Inter-Beat Interval.
volatile boolean Pulse = false; // True when pulse wave is high, false when it's low.
volatile boolean QS = false; // Becomes true when Arduino finds a beat.
void setup()
{
Serial.begin(9600); // We agree to talk fast!
interruptSetup(); // Sets up to read the pulse sensor signal every 2 ms.
}
void loop(){
sendDataToProcessing('S', Signal); // Send Processing the raw pulse sensor data.
if (QS == true){ // Quantified Self flag is true when Arduino finds a heartbeat
fadeRate = 255; // Set 'fadeRate' variable to 255 to fade the LED with a pulse.
sendDataToProcessing('B',BPM); // Send heart rate with a 'B' prefix.
sendDataToProcessing('Q',IBI); // Send time between beats with a 'Q' prefix.
QS = false; // Reset the Quantified Self flag for next time.
}
delay(20); // Take a break
if (BPM > 120) {
pinMode(analogPinR,255); // Pin that will blink to your heartbeat!
pinMode(analogPinG,0); // Pin that will blink to your heartbeat!
pinMode(analogPinB,0); // Pin that will blink to your heartbeat!
}
else if (BPM > 90){ //Yellow
pinMode(analogPinR,255); // Pin that will blink to your heartbeat!
pinMode(analogPinG,80); // Pin that will blink to your heartbeat!
pinMode(analogPinB,5); // Pin that will blink to your heartbeat!
}
else if (BPM > 85){//turk
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,204); // Pin that will blink to your heartbeat!
pinMode(analogPinB,102); // Pin that will blink to your heartbeat!
}
else if (BPM > 80){//green/blue
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,255); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
}
else if (BPM > 75){//blue/green
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,128); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
}
else if (BPM > 70){//blue/purple
pinMode(analogPinR,102); // Pin that will blink to your heartbeat!
pinMode(analogPinG,102); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
}
else if (BPM > 65){//purple
pinMode(analogPinR,178); // Pin that will blink to your heartbeat!
pinMode(analogPinG,102); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
}
else if (BPM > 60){//blue
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,0); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
}
//AURORA
else {
//Blue
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,0); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
delay(300);
//Green
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,255); // Pin that will blink to your heartbeat!
pinMode(analogPinB,0); // Pin that will blink to your heartbeat!
delay(300);
//Orange
pinMode(analogPinR,255); // Pin that will blink to your heartbeat!
pinMode(analogPinG,128); // Pin that will blink to your heartbeat!
pinMode(analogPinB,0); // Pin that will blink to your heartbeat!
delay(300);
//Yellow
pinMode(analogPinR,255); // Pin that will blink to your heartbeat!
pinMode(analogPinG,255); // Pin that will blink to your heartbeat!
pinMode(analogPinB,0); // Pin that will blink to your heartbeat!
delay(300);
//Light blue
pinMode(analogPinR,0); // Pin that will blink to your heartbeat!
pinMode(analogPinG,255); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
delay(300);
//Purple
pinMode(analogPinR,255); // Pin that will blink to your heartbeat!
pinMode(analogPinG,0); // Pin that will blink to your heartbeat!
pinMode(analogPinB,255); // Pin that will blink to your heartbeat!
delay(300);
}
}
void ledFadeToBeat(){
fadeRate -= 15; // Set LED fade value
fadeRate = constrain(fadeRate,0,255); // Keep LED fade value from going into negative numbers!
// analogWrite(fadePin2,fadeRate); // Fade LED
}
void sendDataToProcessing(char symbol, int data ){
Serial.print(symbol); // Symbol prefix tells Processing what type of data is coming
Serial.println(data); // The data to send culminating in a carriage return
Serial.println(BPM); // Print to the laptop screen
ledFadeToBeat();
if(Serial.available()==9){
for(int i =0;i<9;i++){
RGB = Serial.read() - '0';
}
//Get the data from the integer array
R = RGB[0]*100+RGB[1]*10+RGB[2];
G = RGB[3]*100+RGB[4]*10+RGB[5];
B = RGB[6]*100+RGB[7]*10+RGB[8];
}
}
//This is the second tab
volatile int rate[10]; // Used to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // Used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // Used to find the inter beat interval
volatile int P =512; // Used to find peak in pulse wave
volatile int T = 512; // Used to find trough in pulse wave
volatile int thresh = 512; // Used to find instant moment of heart beat
volatile int amp = 100; // Used to hold amplitude of pulse waveform
volatile boolean firstBeat = true; // Used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = true; // Used to seed rate array so we startup with reasonable BPM
void interruptSetup(){
// Initializes Timer2 to throw an interrupt every 2mS.
TCCR2A = 0x02; // Disable PWM on digital pins 3 and 11, and go into CTC mode.
TCCR2B = 0x06; // Don't force compare, 256 prescaler.
OCR2A = 0X7C; // Set the top of the count to 124 for 500 Hz sample rate.
TIMSK2 = 0x02; // Enable interrupt on match between TIMER2 and OCR2A.
sei(); // Make sure global interrupts are enabled.
}
// This is the timer 2 interrupt service routine.
// Timer 2 makes sure that we take a reading
// every 2 miliseconds.
ISR(TIMER2_COMPA_vect){ // Triggered when Timer2 counts to 124
cli(); // Disable interrupts while we do this
Signal = analogRead(pulsePin); // Read the pulse sensor
sampleCounter += 2; // Keep track of the time in ms with this variable.
int N = sampleCounter - lastBeatTime; // Monitor the time since the last beat to avoid noise.
// Find the peak and trough of the pulse wave
if (Signal < thresh && N > (IBI/5)*3){ // Avoid dichrotic noise by waiting 3/5 of last IBI.
if (Signal < T){ // T is the trough.
T = Signal; // Keep track of lowest point in pulse wave.
}
}
if (Signal > thresh && Signal > P) { // A threshold condition helps avoid noise.
P = Signal; // P is the peak.
} // Keep track of highest point in pulse wave.
// Now it's time to look for the heart beat
// signal surges up in value every time there is a pulse
if (N > 250){ // Avoid high frequency noise
if ( (Signal > thresh) &&
(Pulse == false) &&
(N > (IBI/5)*3) ){
Pulse = true; // Set the pulse flag when we think there is a pulse.
digitalWrite(analogPinR,HIGH); // Turn on bluepin LED.
digitalWrite(analogPinG,HIGH); // Turn on redpin LED.
digitalWrite(analogPinB,HIGH); // Turn on greenpin LED.
IBI = sampleCounter - lastBeatTime; // Measure time between beats in ms.
lastBeatTime = sampleCounter; // Keep track of time for next pulse.
if (firstBeat){ // If it's the first time we found a beat, if firstBeat == TRUE
firstBeat = false; // Clear firstBeat flag.
return; // IBI value is unreliable so discard it.
}
if (secondBeat){ // If this is the second beat, if secondBeat == TRUE.
secondBeat = false; // Clear secondBeat flag.
for(int i=0; i<=9; i++){ // Seed the running total to get a realisitic BPM at startup.
rate = IBI;
}
}
// Keep a running total of the last 10 IBI values.
word runningTotal = 0; // Clear the runningTotal variable
for(int i=0; i<=8; i++){ // Shift data in the rate array
rate = rate[i+1]; // And drop the oldest IBI value
runningTotal += rate; // Add up the 9 oldest IBI values
}
rate[9] = IBI; // Add the latest IBI to the rate array
runningTotal += rate[9]; // Add the latest IBI to runningTotal
runningTotal /= 10; // Average the last 10 IBI values
BPM = 60000/runningTotal; // How many beats can fit into a minute? that's BPM!
QS = true; // Set Quantified Self flag
// QS flag is not cleared inside this interupt service routine (ISR)
}
}
if (Signal < thresh && Pulse == true){ // When the values are going down, the beat is over.
// digitalWrite(analogPinR,LOW); // Turn off red LED.
// digitalWrite(analogPinG,LOW); // Turn off green LED.
// digitalWrite(analogPinB,LOW); // Turn off blue LED.
Pulse = false; // Reset the pulse flag, so we can do it again.
amp = P - T; // Get amplitude of the pulse wave.
thresh = amp/2 + T; // Set thresh at 50% of the amplitude.
P = thresh; // Reset these for next time.
T = thresh;
}
if (N > 2500){ // If 2.5 seconds go by without a beat
thresh = 512; // Set thresh default
P = 512; // Set P default
T = 512; // Set T default
lastBeatTime = sampleCounter; // Bring the lastBeatTime up to date
firstBeat = true; // Set these to avoid noise
secondBeat = true; // When we get the heartbeat back
}
sei(); // Enable interrupts when youre done!
}// end ISR
The second set of code contains errors.
pinMode() is not the way to set analog outputs. All these are not correct:
//orange
pinMode(analogPinR,255);
pinMode(analogPinG,128);
pinMode(analogPinB,0);
And you have not configured the pins as output.
What you need is to configure once in setup:
pinMode(ledG, OUTPUT);
and write in the loop:
analogWrite(ledG, 128);
Fix that and at least the LED's should function as you expect.
This is tricky, I don't know your experience (and I don't want to make you mad).
If you are new to programming
Sr. Richie asks if this was one file? In an Arduino sketch (and most computer languages) each function must have its own name. Furthermore, Arduino has special functions named setup() and loop().
If you have been around the block
ISR(TIMER2_COMPA_vect){ // Triggered when Timer2 counts to 124
This could really mess with your control flow. Regardless of where/what you are doing, you will stop and do this ISR request. Maybe you're in the middle of doing the following when you jump away and do the ISR.
RGB = Serial.read() - '0';
This could mess up your serial communication (or anything time-dependent).
I assume it was you in the forum post
Arduino UNO - Controling LED strip with presure sensor & pulse sensor .