Arduino Micro: SP02 Custom Sensor, IR & Red LEDS. Serial Output Inconsistant - c++

thank you in advance for the community's help.
As of right now, we are looking to get consistent data to output to the serial monitor.
We are seeing output to the monitor several seconds after turning on the device, and sometimes the output takes more than 15 seconds. Furthermore, we are getting a oxogyn concentration of a value well above 100%.
There are times when we get a HR value, and a O2 value which seem reasonable, however, this is not always the case and rather inconsistent.
Is there something wrong with the timing of the interrupts or even the frequency in which we write to the serial monitor?
The code is as follows:
#include <LiquidCrystal.h> //Including this so we can test the code as is
//We can always remove the LCD code later
#include "floatToString.h" //SEE COMMENTS BELOW
/*
* You need to include the float to string header file. I am unsure if this goes in the
* main direcotry withe the code or just the library. For completness I have incouded it on my
* computer in both locations. Please do the same untill we can test further.
*/
#include "Arduino.h" //Formally floatToString.h This changed years ago, using Arduino.h
#include <SoftwareSerial.h> //bluetooth
#include <TimerOne.h> //interrupts SEE COMMENT BELOW
//**********************************************************
//Read Below..........................................
/*
* Need a library for the above timeerOne file
* without the library, you will get an error.
* See Github at https://github.com/PaulStoffregen/TimerOne
* Download the timerOne-master.zip file and place the entire
* TimerOne-master folder in my Documents > Arduino > libraries
*/
//**********************************************************
#define analogPin A0
#define Theta 0.6
#define RxD 1 //bluetooth read
#define TxD 0 //bluetooth transmit
#define DEBUG_ENABLED //bluetooth
#define redLED 5 //High is Red led on, Low is Infrared on.
//#define iredLED 6
volatile int maxTemp,minTemp; //shared variables between interrupts and loop
volatile int lastcount,count;
int Rmax, Rmin, IRmax, IRmin;
float R, Spo2,HeartR_frq;
int Sp02_int;
int HeartRate, HeartR;
float LastHeartRate = 70; //default
int average = 140; //average is average crossing
//int average2 = 220;
int interrupts_counter =0; //count the times of interrupts
float value=0.5;
float Spo2_float;
char buffer[25];
SoftwareSerial blueToothSerial(RxD,TxD); //define bluetooth
void setup() {
pinMode(redLED, OUTPUT); //define LED
pinMode(RxD, INPUT); //bluetooth input
pinMode(TxD, OUTPUT); //bluetooth output
pinMode(analogPin, INPUT); //analog signal input
//initially switch on Red LED, after each interrupt will turn on the other
digitalWrite(redLED, HIGH);
Serial.begin(115200);
//bluetooth
setupBlueToothConnection();
//We might not need this, this might be for the LCD display. Leaving it in for now
init_interrupts();
Timer1.initialize(40000); //terrupt every 0.04 seconds
Timer1.attachInterrupt(max_min_num); //interrupt call max_min_num function
Rmax = 0;
IRmax = 0;
Rmin = 0;
IRmin = 0;
LastHeartRate = 70;
}
void loop() {
//initialize LCD
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // initialize LCD, the pins are all depends
lcd.begin(8, 2); //set up the LCD's number of columns and rows:
while(1){ //the whole while is used to avoid LCD reinitialize
digitalWrite(redLED,HIGH);
delay(2000); //let red led signal to be stable
//interrupts();
while(!((lastcount>average )&& (count<average)) ){ }
digitalWrite(redLED,HIGH);
init_interrupts();
while(!((lastcount>average )&& (count<average)) ){ }
noInterrupts(); // temporarily disabel interrupts, to be sure it will not change while we are reading
Rmax = maxTemp;
Rmin = minTemp;
delay(100);
HeartR_frq = 1/(0.04*interrupts_counter); //d is the times of ISR in 1 second,
interrupts(); //enable interrupts
HeartRate = HeartR_frq * 60;
if(HeartRate> 60 && HeartRate< 120){
HeartR = Theta*HeartRate + (1 - Theta)*LastHeartRate; //Use theta to smooth
LastHeartRate = HeartR;
}
digitalWrite(redLED, LOW);
//initialize lcd
lcd.setCursor(0,0);
lcd.print("HR:");
lcd.setCursor(5,0);
lcd.print(HeartR);
R = (Rmax - Rmin);
Spo2 = (R-180)*0.01 +97.838;
int Spo2_int = (int)Spo2; //float Spo2 to int Spo2_int
String Spo2_float = floatToString(buffer,Spo2,2);
lcd.setCursor(0,1);
lcd.print("SPO2:");
lcd.setCursor(5,1);
lcd.print(Spo2_int);
//transmit data to phone app through bluetooth
String H = String("H: ")+HeartR +String("S: ") +Spo2_float;
Serial.println(H);
delay(1000);
init_interrupts();
}
}
void setupBlueToothConnection() //initialize bluetooth
{
blueToothSerial.begin(115200); //Set BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //t the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=HC-06\r\n"); //t the bluetooth name as "HC-05"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
//blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
blueToothSerial.print("bluetooth connected!\n");
delay(2000); // This delay is required.
blueToothSerial.flush();
}
void init_interrupts()
{
maxTemp = 0;
minTemp = 1023;
count = 0;
lastcount =0;
interrupts_counter = 0;
}
void max_min_num()
{
lastcount = count;
count = analogRead(analogPin); //read signa
if(count> maxTemp){
maxTemp = count;
}
else if(count<minTemp){
minTemp = count;
}
interrupts_counter++; //interrupt counter
}
Thank you in advance for your time!

Related

Why is my Arduino code for running a Bluetooth controlled robot with obstacle sensor not working as it should be?

I have created a Bluetooth based smartphone controlled robot (a 4 wheel car) earlier using Arduino and an obstacle avoidance robot.
Now, I wanted to combine both of them. So, I combined their functions and codes in such a manner that felt right to me. But, it kinda seems wrong to my robot.
My Bluetooth Controlled robot was running smoothly. My obstacle avoiding robot was running flawless. But, when I tried to join them, both of them started crying.
I tried to change orders of the functions, adding some functions twice or thrice removing them from some places that didn't feel right then. Nothing was worthy.
I need to upload whole code because I'm not sure where am I doing it wrong
#include <SoftwareSerial.h>
#include <RemoteXY.h>
// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX A2
#define REMOTEXY_SERIAL_TX A3
#define REMOTEXY_SERIAL_SPEED 9600
// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
{ 255,8,0,54,0,176,0,8,228,4,
5,48,44,26,30,30,0,31,8,1,
6,0,-84,-142,20,20,0,2,26,129,
0,6,37,23,8,0,64,78,97,118,
101,100,0,131,3,51,1,20,5,1,
2,31,82,111,98,111,116,32,67,97,
114,0,131,0,62,5,19,5,2,2,
31,67,111,110,116,114,111,108,108,101,
114,0,129,0,10,45,13,7,0,16,
84,72,69,0,129,0,5,52,25,8,
0,136,83,104,101,105,107,104,0,1,
0,-34,-111,12,12,1,2,31,88,0,
1,4,79,44,12,12,0,37,151,240,
159,147,162,0,65,4,87,9,7,7,
0,65,1,87,17,7,7,0,65,2,
87,25,7,7,0,67,5,3,3,25,
14,0,94,24,51,2,0,86,1,11,
5,0,135,26,31,31,79,78,0,79,
70,70,0 };
// this structure defines all the variables of your control interface
struct {
// input variable
int8_t joystick_1_x; // =-100..100 x-coordinate joystick position
int8_t joystick_1_y; // =-100..100 y-coordinate joystick position
uint8_t rgb_1_r; // =0..255 Red color value
uint8_t rgb_1_g; // =0..255 Green color value
uint8_t rgb_1_b; // =0..255 Blue color value
uint8_t button_1; // =1 if button pressed, else =0
uint8_t button_2; // =1 if button pressed, else =0
uint8_t switch_1; // =1 if switch ON and =0 if OFF
// output variable
uint8_t red_led_r; // =0..255 LED Red brightness
uint8_t blue_led_b; // =0..255 LED Blue brightness
uint8_t green_led_g; // =0..255 LED Green brightness
char text_indicator[51]; // string UTF8 end zero
// other variable
uint8_t connect_flag; // =1 if wire connected, else =0
} RemoteXY;
#pragma pack(pop)
/////////////////////////////////////////////
// END RemoteXY include //
/////////////////////////////////////////////
#define PIN_BUTTON_2 A4
#define PIN_SWITCH_1 A5
#include<AFMotor.h>
#include <NewPing.h>
#include <Servo.h>
#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 250
//#define MAX_SPEED 150 // sets speed of DC motors
//#define MAX_SPEED_OFFSET 20
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
AF_DCMotor left_motor_A(1, MOTOR12_64KHZ);
AF_DCMotor left_motor_B(2, MOTOR12_64KHZ);
AF_DCMotor right_motor_A(3, MOTOR34_64KHZ);
AF_DCMotor right_motor_B(4, MOTOR34_64KHZ);
Servo myservo;
int distance = 100;
int right_motor_speed = 0;
int left_motor_speed = 0;
//define two arrays with a list of pins for each motor
AF_DCMotor RightMotor[2] = {right_motor_A, right_motor_B};
AF_DCMotor LeftMotor[2] = {left_motor_A, left_motor_B};
//speed control of motors
void Wheel (AF_DCMotor * motor, int v) // v = motor speed, motor = pointer to an array of pins
{
if (v > 100) v=100;
if (v < -100) v=-100;
if (v > 0){
motor[0].run(FORWARD);
motor[1].run(FORWARD);
motor[0].setSpeed(v * 1.75);
motor[1].setSpeed(v * 1.75);
}
else if ( v<0 ){
motor[0].run(BACKWARD);
motor[1].run(BACKWARD);
motor[0].setSpeed(v * 1.75);
motor[1].setSpeed(v * 1.75);
/* //digitalWrite (motor [1], FORWARD);
analogWrite (motor [2], (v) * 0.75);
//analogWrite (motor [2], (-v) * 0.75); */
}
else{
motor[0].run(RELEASE);
motor[1].run(RELEASE);
motor[0].setSpeed(0);
motor[1].setSpeed(0);
}
}
int lookRight()
{
RemoteXY.blue_led_b = 255;
RemoteXY.red_led_r = 0;
RemoteXY.green_led_g = 0;
sprintf(RemoteXY.text_indicator, "CHECKING THE RIGHT SIDE.");
myservo.write(50);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
}
int lookLeft()
{
RemoteXY.blue_led_b = 255;
RemoteXY.red_led_r = 0;
RemoteXY.green_led_g = 0;
sprintf(RemoteXY.text_indicator, "CHECKING THE LEFT SIDE.");
myservo.write(170);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
delay(100);
}
int readPing()
{
delay(100);
int cm = sonar.ping_cm();
if(cm==0)
{
cm = MAX_DISTANCE ;
}
return cm;
}
void moveStop()
{
left_motor_A.run(RELEASE);
left_motor_B.run(RELEASE);
right_motor_A.run(RELEASE);
right_motor_B.run(RELEASE);
}
void setup()
{
RemoteXY_Init ();
pinMode (PIN_BUTTON_2, OUTPUT);
pinMode (PIN_SWITCH_1, OUTPUT);
myservo.attach(10);
myservo.write(115);
delay(2000);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
}
void loop()
{
RemoteXY_Handler ();
digitalWrite(PIN_BUTTON_2, (RemoteXY.button_2==0)?LOW:HIGH);
digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);
int distanceR = 0;
int distanceL = 0;
delay(40);
if(distance<=27)
{
moveStop();
RemoteXY.blue_led_b = 0;
RemoteXY.red_led_r = 255;
RemoteXY.green_led_g = 0;
sprintf(RemoteXY.text_indicator, "AN OBSTACLE HAS COME IN FRONT OF YOUR ROBOT!!!");
digitalWrite(PIN_BUTTON_2, HIGH);
delay(1500);
distanceR = lookRight();
delay(250);
distanceL = lookLeft();
delay(250);
if(distanceR>=distanceL)
{
RemoteXY.blue_led_b = 255;
RemoteXY.red_led_r = 0;
RemoteXY.green_led_g = 0;
sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE RIGHT SIDE.");
}
else
{
sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE LEFT SIDE.");
}
}
else
{
RemoteXY.blue_led_b = 0;
RemoteXY.red_led_r = 0;
RemoteXY.green_led_g = 255;
//manage the right motor
Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);
}
distance = readPing();
//manage the right motor
//Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
//Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);
}
I want my Robot to work on my directions and when he senses something on its front end then he should stop there and tell me through a RemoteXY.text_string and then check for obstacles at the left and right side and tell me on which side it is available to go. After that, it should again take my orders via my mobile phone.
Firstly, it became impossible to connect the robot to the Smartphone using Bluetooth because the robot was very busy in doing some other stuffs (only he knows what was he doing). Then, I applied a "RemoteXY Button" on my code (that is not in the code that I'm posting here) with an "if" block; such that if this switch is pressed via the Smartphone, only then the robot will start moving. So, doing this thing helped me to connect my robot to my smartphone via Bluetooth but, when I was connection then the Servo Motor was regularly spinning (again, I don't know why) after secure connection, when I turned that switch on, then my robot took only my first order (which is usually moving forward) and it performed on my first order for almost first 3 to 5 seconds and then the Robot got his system hanged and my smartphone was automatically disconnected from the robot.
I am unable to figure out where is the filth in my code or my code is itself fully filthy. This is the matter, where I need you guys' help
Other information that you might need for better Support/help, I am using:
1). RemoteXY app for Android to Robot Communication
2). Arduino UNO as Microcontroller
3). Arduino IDE for Programming Arduino
4). One SG 90 Servo Motor.
5). Four Geared DC- Motors.
6). L293D Motor Driver Shield for driving Dc motors and the Servo
7). HC SR-04 ultrasonic sensor for obstacle sensing
8). A 12V battery
9). HC-05 Module for Bluetooth Communication
10). A buzzer for external indicator/horn. At pin A4
11). A filthy code for Arduino Programming 😜.
Any help with the code will be appreciated.
Thank You So Much in advance. ❤️
For an arduino robot that needs to perform a lot of function simultaneously you may want to look into this https://forum.arduino.cc/index.php?topic=223286.0

Arduino Sonar and Stepper Motor

I am trying to create an Arduino powered sonar / radar. I currently have a sonar sensor attached to a motor and working on the code. The issue is with the for loop below. The sensor will ping and the motor will then move, repeating the correct number of times. However the values that the sonar sensor returns are either 0 or 1 no matter what the distance is. Any help on identifying the issue would be very appreciated.
/*
Nathan Verdonk
3/15/2019
*/
#include <NewPing.h>
#include <Stepper.h>
const int stepsPerRevolution = 2048; // Steps per revolution
const int rotSpeed = 10; // Speed of rotation in RPM
const int triggerPin = 7; // Trigger pin on sonar sensor
const int echoPin = 6; // Echo pin on sonar sensor
const int maxDistance = 300; // Max distance expected from sensor in cm; do not exceed 400
int val;
Stepper stepper1(stepsPerRevolution, 8, 10, 9, 11); // initialize the stepper library on pins 8 through 11:
NewPing sonar1(triggerPin, echoPin, maxDistance); // initialize the new ping library with predefined values
void setup() {
stepper1.setSpeed(rotSpeed);
Serial.begin(115200);
}
void loop() {
for(int i = 0; i < 50; i++){
delay(50);
val = sonar1.ping_cm();
Serial.println(val);
stepper1.step(1);
}
delay(3000);
}
Problem is not with the code.
As it turns out, the sensor is picky about needing nearly exactly 5 V to run. With the servo and sensor using the same power source, the voltage would drop below 5 V when the servo was running.
Thank you to all who helped.
if you want to trap the distance you could do this process to validate your sensor has no problem (i suppose wiring is right):
// defines pins numbers
const int triggerPin = 7;
const int echoPin = 6;
// defines variables
long duration;
int distance;
void setup() {
pinMode(triggerPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(115200); // Starts the serial communication
}
void loop() {
delay(50);
// Clears the triggerPin
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the triggerPin on HIGH state for 10 micro seconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
In order to generate the ultrasound you need to set the Trig on a High State for 10 µs. That will send out an 8 cycle sonic burst which will travel at the speed sound and it will be received in the Echo pin. The Echo pin will output the time in microseconds the sound wave traveled.
the speed of the sound is 340 m/s or 0.034 cm/µs so you divide by 2 to trap the distance

Multiple if statements and

Thanks in advance for your help.
So I'm working on a pressure sensor. The idea is that when the pressure sensor gets to a certain value, say 10 AND then decreases sharply after it has gotten to 10, activate the buzzer. (So it's like, I pump my car tire to 10 and I want to know if there is a leak)
I just for the life of me can not make this happen. I know I'm just missing something very small but I will greatly appreciate any help.
Below is my code:
#include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// These constants won't change: const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 5; // an arbitrary threshold level that's in the range of the analog input const int buzzer = 9; // pin that the buzzer is connected to.
void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initilizes the pin as an output. pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
// initialize serial communications: Serial.begin(9600); lcd.begin(16, 2); lcd.print ("Pressure in kpa"); }
void loop() { // read the value of the pressure sensor: float sensorValue = analogRead(analogPin); // int kpa = (((sensorValue*5)/1024)*(120/5)-116); // 116 was subtracted to equilibrate the sensor int kpa = ((sensorValue * 5 / 1024) * (15 / 5) * (6.894 / 1) - 10); // // if the analog value is greater than whatever threshold we use , turn on the LED:
if (kpa > threshold )
{
digitalWrite(ledPin, HIGH);
digitalWrite(buzzer, HIGH);
tone(buzzer, 1000); // this controls the picth of the sound. (Hz)
delay(1000); } else {
digitalWrite(ledPin, LOW);
digitalWrite(buzzer, LOW);
noTone(buzzer); // Stop sound...
delay(1000); }
// print the analog value: Serial.println(kpa); delay(1); // delay in between reads for stability lcd.setCursor (0, 1); lcd.print (kpa);
}
Thanks.
I have edited the code to reflect what you are trying to do.
Essentially you need to check if your pressure is increasing or decreasing.
So for this you can take two readings and compare them; one reading is taken before the other. If the latest reading is higher than the previous then its going up, no cause for alarm.
If the latest reading is less that the previous then the pressure is going down. So, cause for alarm but not just yet...
TWO conditions need to be met before the alarm sounds, the pressure needs to be on a downward path AND the pressure needs to be below the threshold value.
kpa must be going down AND be below threshold:
(val < previous && val < threshold)
See if this works, sorry I rushed it a bit and haven't tested it at all:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 13; // pin that the LED is attached to
const int threshold = 5; // an arbitrary threshold level that's in the range of the analog input
const int buzzer = 9; // pin that the buzzer is connected to.
int val = 0; // store value
int previous; // previous reading
void setup()
{
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
Serial.begin(9600); // initialize serial communications:
lcd.begin(16, 2);
lcd.print ("Pressure in kpa");
}
void loop() {
float sensorValue = analogRead(analogPin); // read the value of the pressure sensor:
int kpa = ((sensorValue * 5 / 1024) * (15 / 5) * (6.894 / 1) - 10);
// we want to check if this is going up or down.
previous = val;
val = kpa;
if (val > previous) {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, HIGH); // make LED flashy-flashy if its going up
delay(1000);
}
else if (val < previous && val < threshold) {
digitalWrite(ledPin, LOW); // ... and we switch off the LED
tone(buzzer, 1000); // WEE WAH WEE WAH WEE WAH
delay(1000);
}
}
I added a flashing LED to the code because flashing LEDs are just better.
I also used an else...if statement.
Hopefully this will work.
Cheers,
Ingwe.

Storing Last Reading in Arduino

Hello I am trying to write a sketch that reads the distance from an ultrasonic distance sensor and only sends the data if the previous and current readings are to different (20cm). Below is my sketch;
const int TRIG_PIN = 12;
const int ECHO_PIN = 11;
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;
void setup() {
// The Trigger pin will tell the sensor to range find
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
// We'll use the serial monitor to view the sensor output
Serial.begin(9600);
BTserial.begin(9600);
}
void loop() {
unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
float inches;
float lastcm;
float diff;
// Hold the trigger pin high for at least 10 us
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Wait for pulse on echo pin
while ( digitalRead(ECHO_PIN) == 0 );
// Measure how long the echo pin was held high (pulse width)
// Note: the () microscounter will overflow after ~70 min
t1 = micros();
while ( digitalRead(ECHO_PIN) == 1);
t2 = micros();
pulse_width = t2 - t1;
// Calculate distance in centimeters and inches. The constants
// are found in the datasheet, and calculated from the assumed speed
//of sound in air at sea level (~340 m/s).
cm = pulse_width / 58.0;
diff = cm - lastcm;
lastcm = cm;
// Print out results
if ( pulse_width > MAX_DIST ) {
BTserial.write("Out of range");
lastcm = cm;
} else {
Serial.println(diff);
Serial.println("Or act value");
Serial.println(cm);
lastcm = cm;
if (abs(diff)>20) {
BTserial.println(cm);
}
}
// Wait at least 60ms before next measurement
delay(150);
}
However this is not correctly calculating the difference between the two values - as the serial monitor just returns
29.24
Or act value
29.24
29.31
Or act value
29.31
28.83
Or act value
28.83
Any thoughts?
Your variable 'lastcm' is declared inside the loop function. You have two options. Either declare it external to the loop or else declare it where you do but make it static (in either case you also have to deal with the initial invalid reading that it contains)
You could simplify this sketch and make it less prone to error by using the NewPing library:
http://playground.arduino.cc/Code/NewPing

Stopping a program under certain conditions

I am greeting you today with a program question for my project that uses light as an input for a servo on a wall. Light will enter the room and the shade will go down, and in the absence of light, the shade will recede. I would like to make two conditions in a void loop in the arduino code only applicable one time unless the condition changes. By saying this I mean that, I want this void loop to run continually,in which i have two conditions. And if the same condition is met twice in a row,(ie. sensor reading between 800 and 10000, like 5000 and and then at 6032), nothing will run. If one condition is met and then the other is met afterwards, that's ok. Here's my code and any help as to what reference commands I should use or my next course of action would be greatly appreciated.
// Reports the frequency from the TSL230, higher number means brighter
// Part: http://www.sparkfun.com/products/8940
// Article: http://bildr.org/2011/08/tsl230r-arduino/
#include <Servo.h>
Servo myservo1;
int TSL230_Pin = 4; //TSL230 output
int TSL230_s0 = 3; //TSL230 sensitivity setting 1
int TSL230_s1 = 2; //TSL230 sensitivity setting 2
int TSL230_samples = 30; //higher = slower but more stable and accurate
void setup(){
Serial.begin(9600);
setupTSL230();
pinMode(5,OUTPUT);
}
void loop(){
float lightLevel = readTSL230(TSL230_samples);
Serial.println(lightLevel);
if(lightLevel>800 && lightLevel<1000)
{
myservo1.attach(5);
myservo1.writeMicroseconds(1300);delay(1000);
myservo1.writeMicroseconds(1500);delay(5000000);
}
else if(lightLevel<800)
{
myservo1.attach(5);
myservo1.writeMicroseconds(1700);delay(5000);
myservo1.writeMicroseconds(1500);delay(5000000);
}
}
void setupTSL230(){
pinMode(TSL230_s0, OUTPUT);
pinMode(TSL230_s1, OUTPUT);
//configure sensitivity - Can set to
//S1 LOW | S0 HIGH: low
//S1 HIGH | S0 LOW: med
//S1 HIGH | S0 HIGH: high
digitalWrite(TSL230_s1, LOW);
digitalWrite(TSL230_s0, HIGH);
}
float readTSL230(int samples){
//sample light, return reading in frequency
//higher number means brighter
float start = micros();
int readings = 0;
while(readings < samples){
pulseIn(TSL230_Pin, HIGH);
readings ++;
}
float length = micros() - start;
float freq = (1000000 / (length / samples)) * 10;
return freq;
}
First add this to your setup ...
void setup(){
Serial.begin(9600);
setupTSL230();
pinMode(5,OUTPUT);
myservo1.attach(5);
}
Then make a new variable and add it to your if statements
Boolean once; // declare this with your other int variables
if(lightLevel > 800 && lightLevel < 1000 && once==True)
{
myservo1.writeMicroseconds(1300);delay(1000);
myservo1.writeMicroseconds(1500);delay(1000);
once = False;
}
else if(lightLevel<800 && once == False)
{
myservo1.writeMicroseconds(1700);delay(5000);
myservo1.writeMicroseconds(1500);delay(1000);
once = True;
}