Arduino TM35 Temperature Sensor Wrong - c++

I am starting out trying to learn some C++ and embeded programming but i am having some real issues with my TM35 sensor.
It is worth noting my bedroom is not in the 50 degrees celsius, its mid 20's at the highest.
The Sensor is connected to the A0 Serial port, 5v and ground as it should, and i have checked its done the right way around with the middle leg of the sensor going to a0 and with the flat side facing you the left pin is going to 5v and right pin to ground.
Below is the code, it is not my code as im learning im just playing with other peoples code for now.
const byte tempPin = A0;
float calibration = 0.1039;
float temp; // Celcius
float volts;
void setup() {
Serial.begin(9600);
analogReference(INTERNAL1V1); // use internal 1.1volt Aref
// change INTERNAL to INTERNAL1V1 for a Mega
}
void loop() {
temp = analogRead(tempPin) * calibration; // get temp
volts = analogRead(tempPin);
Serial.print("Volts: ");
Serial.print(volts);
Serial.print(", Temperature: ");
Serial.print(temp, 1); // one decimal place resolution is all you get
Serial.println("*C");
delay(1000); // use a non-blocking delay when combined with other code
}
I have also tried this code too but same results.
float temp;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
temp = analogRead(A0);
temp = temp * 0.48828125;
Serial.print("Temperature: ");Serial.print(temp);Serial.print("*C");
Serial.println();
delay(1000);
}

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.

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

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!

Strange issue trying fade on arduino on multiple LEDs

I am trying to test out Fade on multiple LEDs on an Arduino Uno. Here's the code i have written
int led[2] = {9,10}; // the pin that the LED is attached to
int brightness[2] = {0,0}; // how bright the LED is
int fadeAmount[2] = {5,15}; // how many points to fade the LED by
long previousMillis[2] = {0,0}; // will store last time LED was updated
long interval[2] = {30, 50};
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led[0], OUTPUT);
pinMode(led[1], OUTPUT);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pins:
for (int counter = 0; counter < 2; counter++) {
unsigned long currentMillis = millis();
analogWrite(led[counter], brightness[counter]);
Serial.print("LED ");
Serial.print(led[counter]);
Serial.print(": Brightness ");
Serial.println(brightness[counter]);
if (currentMillis - previousMillis[counter] > interval[counter]) {
// change the brightness for next time through the loop:
brightness[counter] = brightness[counter] + fadeAmount[counter];
// reverse the direction of the fading at the ends of the fade:
if (brightness[counter] == 0 || brightness[counter] == 255) {
fadeAmount[counter] = -fadeAmount[counter] ;
}
}
}
}
Here's the weird thing. If i comment out the Serial stuff (print and begin), the fades don't work. They just "flicker" a little.
Any idea what is wrong?
I figured it out. It looks like I forgot a line of code.
previousMillis[counter] = currentMillis;
I should have put that in on the first if statement in the code. I guess the act of observing by using the serial print slowed things down enough that the code seemed to work.
Boy, do i feel foolish.