My project is to allow automatic lightening by detecting motion using PIR Sensors.
THis is what I want to do :
when the first motion sensor "inputpin" is HIGH which means a motion1 is detected , ledPin1 is set to HIGH.... then I check the signal from the other PIR sensor "inputpin2" if it is HIGH ledPin3 should be HIGH , If it is LOW ledpin2 should be HIGH.
I wrote this code , but what it actually do is after a motion is detected from the first sensor"inputPin" , ledPin3 is set to high as if the second sensor is always HIGH !
Can any one help me with this problem.
Thanks
` ``
int ledPin1 = 13; // choose the pin for the LED
int ledPin2 = 12;
int ledPin3 = 11;
int inputPin = 2; // choose the input pin (for PIR sensor)
int inputPin2 = 1;
int pirState1 = LOW; // we start, assuming no motion detected
int pirState2 = LOW;
int val = 0; // variable for reading the pin status
int val2 = 0;
int pinSpeaker = 10; //Set up a speaker on a PWM pin (digital 9, 10, or 11)
void setup() {
pinMode(ledPin1, OUTPUT); // declare LED as output
pinMode(ledPin2, OUTPUT); // declare LED as output
pinMode(ledPin3, OUTPUT);
pinMode(inputPin, INPUT); // declare sensor 1 as input
pinMode(inputPin2, INPUT); // declare sensor 2 as input
// pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin1, HIGH); // turn LED ON
delay (1500);
if (pirState1 == LOW) {
// we have just turned on
Serial.println("Motion1 detected!");
// We only want to print on the output change, not state
pirState1 = HIGH;
}
delay (1500);
// check sensor 2 after delay
val2 = digitalRead(inputPin2);
if (val2 == HIGH){
digitalWrite(ledPin2, LOW);
delay(1500);
digitalWrite(ledPin3,HIGH);
//playTone(300, 160);
delay(1500);
if (pirState2 == LOW) {
// we have just turned on
Serial.println("Motion1 from sensor 2 detected!");
// We only want to print on the output change, not state
pirState2 = HIGH;
}
}
if(val2 == LOW){
digitalWrite(ledPin2, HIGH);
//playTone(300, 160);
delay(1500);
digitalWrite(ledPin3,LOW);
delay(1500);
}
} else {
digitalWrite(ledPin1, LOW); // turn LED OFF
delay (1500);
digitalWrite(ledPin2, LOW); // may be already
//playTone(0, 0);
delay(1500);
digitalWrite(ledPin3, LOW); // turn LED OFF
delay (1500);
if (pirState1 == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState1 = LOW;
}
if (pirState2 == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState2 = LOW;
}
}
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}
`
Change inputPin2 from 1 to 3 for example. Just don't use the pins 0 or 1 (those assigned for Tx and Rx), hope this works.
Related
I'm an undergraduate student. We have an assignment to use Energia and the MSP432-P401R microcontroller to create an OR gate and AND gate IC tester.
You place the IC in the tester circuit and the tester will first determine if the IC is an AND or OR IC. Then, it will indicate which gates on the chip are functioning properly.
My issue is regrading the logical HIGH output voltage of the MSP432. My input signals, a and b, are passed to the IC gates. When my "a" signal is logical HIGH, its voltage is 2.8V. When my "b" signal is logical HIGH, its voltage is 0.7V. This 0.7V is too low for my ICs to register as a HIGH input. I am reading the voltage directly from the MSP432 pin.
I have tried using different GPIO pins and resetting the board. However, the "b" signal is still 0.7V.
My code for setting up "a" and "b" are similar, so I'm not sure why they are outputting different voltages.
My code:
//IC TEST
//Gate inputs pin assignment
int APin=11;
int BPin=8; //other pins tried: 12, 18, 5
//Gate output read pins
int output1Pin=38;
int output2Pin=37;
int output3Pin=36;
int output4Pin=35;
//LED pins
int gate1LEDPin=31;
int gate2LEDPin=32;
int gate3LEDPin=33;
int gate4LEDPin=34; //Gate functioning indicators
int orLEDPin = 40;
int andLEDPin= 39; //Logic of IC indicators
//Truth Table Arrays with inputs a and b
int aValue[]={0, 0, 1, 1};
int bValue[]={0, 1, 0, 1};
int orTrue[]={0, 1, 1, 1};
int andTrue[]={0, 0, 0, 1};
//Function Declaration
int workTest(int,int); //checks if gate is working
//by comparing gate output to
//expected truth result
int logicTest(); //Returns 0 for OR IC, 1 for AND IC
//Progrram variables
int i; //for loop counter
int gate1Result;
int gate2Result;
int gate3Result;
int gate4Result; //Stores number of times gate outputs
//correct value for each ab input
int logicRead; //0 is OR gate. 1 is AND gate
//--------------SETUP-----------------
void setup()
{
Serial.begin(9600);
pinMode(APin, OUTPUT);
pinMode(BPin, OUTPUT);
pinMode(output1Pin, INPUT);
pinMode(output2Pin, INPUT);
pinMode(output3Pin, INPUT);
pinMode(output4Pin, INPUT); //gate output reads
pinMode(orLEDPin, OUTPUT);
pinMode(andLEDPin, OUTPUT);
pinMode(gate1LEDPin, OUTPUT);
pinMode(gate2LEDPin, OUTPUT);
pinMode(gate3LEDPin, OUTPUT);
pinMode(gate4LEDPin, OUTPUT);
}
//END SETUP
//-----------------LOOP---------------------
void loop()
{
gate1Result = 0;
gate2Result = 0;
gate3Result = 0;
gate4Result = 0;
//test IC for its logic function
logicRead = logicTest(); //logicTest returns 0 for OR, 1 for AND
if(logicRead == 9) //logic of IC cannot be determined
{
Serial.println("Try again");
}
if(logicRead != 9)
{
for(i=0; i<4; i++)
{
digitalWrite(APin, aValue[i]); //Load ith value of aValue array
digitalWrite(BPin, bValue[i]); //Load ith value of bValue array
Serial.print("AB = ");
Serial.print(aValue[i]);
Serial.println(bValue[i]);
delay(4000); //Stabilize input signals
if(logicRead == 0) //OR Testing
{
Serial.print("OR Output should be ");
Serial.println(orTrue[i]);
Serial.print("Gate 1: ");
gate1Result = gate1Result + workTest(orTrue[i], output1Pin);
Serial.print("Gate 2: ");
gate2Result = gate2Result + workTest(orTrue[i], output2Pin);
Serial.print("Gate 3: ");
gate3Result = gate3Result + workTest(orTrue[i], output3Pin);
Serial.print("Gate 4: ");
gate4Result = gate4Result + workTest(orTrue[i], output4Pin);
}
if(logicRead == 1) //AND Testing
{
Serial.print("AND Output should be ");
Serial.println(andTrue[i]);
Serial.print("Gate 1: ");
gate1Result = gate1Result + workTest(andTrue[i], output1Pin);
Serial.print("Gate 2: ");
gate2Result = gate2Result + workTest(andTrue[i], output2Pin);
Serial.print("Gate 3: ");
gate3Result = gate3Result + workTest(andTrue[i], output3Pin);
Serial.print("Gate 4: ");
gate4Result = gate4Result + workTest(andTrue[i], output4Pin);
}
}
//Write gate 1 LED
if(gate1Result == 4)
{
digitalWrite(gate1LEDPin, HIGH);
Serial.println("Gate 1 works");
}
else
{
digitalWrite(gate1LEDPin, LOW);
Serial.println("Gate 1 FAIL");
}
//Write gate 2 LED
if(gate2Result == 4)
{
digitalWrite(gate2LEDPin, HIGH);
Serial.println("Gate 2 works");
}
else
{
digitalWrite(gate2LEDPin, LOW);
Serial.println("Gate 2 FAIL");
}
//Write gate 3 LED
if(gate3Result == 4)
{
digitalWrite(gate3LEDPin, HIGH);
Serial.println("Gate 3 works");
}
else
{
digitalWrite(gate3LEDPin, LOW);
Serial.println("Gate 3 FAIL");
}
//Write gate 4 LED
if(gate4Result == 4)
{
digitalWrite(gate4LEDPin, HIGH);
Serial.println("Gate 4 works");
}
else
{
digitalWrite(gate4LEDPin, LOW);
Serial.println("Gate 4 FAIL");
}
}
Serial.println();
Serial.println();
delay(10000); //Wait 10 sec before running code again
}//End void loop
//-----------Function Definitions-----------------------
//This function tests if all gates of the IC are working
//Returns 1 if gate is functioning
//Returns 0 if gate is not functioning
int workTest(int truth, int gateNum)
{
int gateRead = 0; //Updates for each gate output
int result = 0; //TotResult is 1 for all gates pass, 0 for any gate fail
gateRead= digitalRead(gateNum);
if(gateRead == truth)
{
result = 1;
}
else
{
result = 0;
}
Serial.println(gateRead);
return result; //1 for pass, 0 for gate fails
}
//This function tests the logic of the IC
//Returns 1 if IC is an AND gate
//Returns 0 if IC is an OR gate
//Allows for 1 broken gate
//If more than 1 gate broken, logic cannot
//be determined
int logicTest()
{
int aVal[]={0, 1};
int bVal[]={1, 0};
int outputCount = 0;
int logicGate = 0;
int c;
int gate1;
int gate2;
int gate3;
int gate4;
for(c=0; c<2; c++) //only testing ab = 01 and ab = 10
{
digitalWrite(APin, aVal[c]);
digitalWrite(BPin, bVal[c]);
delay(1000); //Stabilize input delay
gate1=digitalRead(output1Pin);
gate2=digitalRead(output2Pin);
gate3=digitalRead(output3Pin);
gate4=digitalRead(output4Pin);
outputCount = outputCount + gate1 + gate2 + gate3 + gate4;
}
if(outputCount < 3) //IC is likely AND gate w/ 1 broken gate
{
logicGate = 1;
Serial.println("IC is an AND gate");
digitalWrite(andLEDPin, HIGH);
digitalWrite(orLEDPin, LOW);
}
else if(outputCount > 5 && outputCount < 9) //IC is likely OR gate w/ 1 broken gate
{
logicGate = 0;
Serial.println("IC is an OR gate");
digitalWrite(andLEDPin, LOW);
digitalWrite(orLEDPin, HIGH);
}
else
{
logicGate = 9;
digitalWrite(andLEDPin, LOW);
digitalWrite(orLEDPin, LOW);
Serial.println("Logic of IC could not be determined");
Serial.println("IC could be broken. Make sure IC is connected properly.");
Serial.println();
}
return logicGate;
}
Here is the circuit setup:
I am trying to use Arduino IDE to detect temperature and pulse rate using LM35 sensor and pulse sensor.
This is the code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <SoftwareSerial.h>
float pulse = 0;
float temp = 0;
SoftwareSerial ser(9,10);
String apiKey = "MVLG8S8L6138FCR4";
// Variables
int pulsePin = A0; // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 7 ; // pin to blink led at each beat
int fadePin = 13; // pin to do fancy classy fading blink at each beat
int fadeRate = 0; // used to fade LED on with PWM on fadePin
// Volatile Variables, used in the interrupt service routine!
volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
volatile int Signal; // holds the incoming raw data
volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when nota "live beat".
volatile boolean QS = false; // becomes true when Arduoino finds a beat.
// Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
volatile int rate[10]; // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // used to find IBI
volatile int P = 512; // used to find peak in pulse wave, seeded
volatile int T = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 525; // used to find instant moment of heart beat, seeded
volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM
void setup()
{
lcd.begin(16, 2);
pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
Serial.begin(115200); // we agree to talk fast!
interruptSetup(); // sets up to read Pulse Sensor signal every 2mS
// IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
// UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
// analogReference(EXTERNAL);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Patient Health");
lcd.setCursor(0,1);
lcd.print(" Monitoring ");
delay(4000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Initializing....");
delay(5000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Getting Data....");
ser.begin(9600);
ser.println("AT");
delay(1000);
ser.println("AT+GMR");
delay(1000);
ser.println("AT+CWMODE=3");
delay(1000);
ser.println("AT+RST");
delay(5000);
ser.println("AT+CIPMUX=1");
delay(1000);
String cmd="AT+CWJAP=\"Alexahome\",\"98765432\"";
ser.println(cmd);
delay(1000);
ser.println("AT+CIFSR");
delay(1000);
}
// Where the Magic Happens
void loop()
{
serialOutput();
if (QS == true) // A Heartbeat Was Found
{
// BPM and IBI have been Determined
// Quantified Self "QS" true when arduino finds a heartbeat
fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED with pulse
serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
QS = false; // reset the Quantified Self flag for next time
}
ledFadeToBeat(); // Makes the LED Fade Effect Happen
delay(20); // take a break
read_temp();
esp_8266();
}
void ledFadeToBeat()
{
fadeRate -= 15; // set LED fade value
fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // fade LED
}
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 500Hz SAMPLE RATE
TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}
void serialOutput()
{ // Decide How To Output Serial.
if (serialVisual == true)
{
arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer
}
else
{
sendDataToSerial('S', Signal); // goes to sendDataToSerial function
}
}
void serialOutputWhenBeatHappens()
{
if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work
{
Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness
Serial.print("BPM: ");
Serial.println(BPM);
}
else
{
sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
}
}
void arduinoSerialMonitorVisual(char symbol, int data )
{
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 1024; // sensor maximum, discovered through experiment
int sensorReading = data; // map the sensor range to a range of 12 options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
// do something different depending on the
// range value:
switch (range)
{
case 0:
Serial.println(""); /////ASCII Art Madness
break;
case 1:
Serial.println("---");
break;
case 2:
Serial.println("------");
break;
case 3:
Serial.println("---------");
break;
case 4:
Serial.println("------------");
break;
case 5:
Serial.println("--------------|-");
break;
case 6:
Serial.println("--------------|---");
break;
case 7:
Serial.println("--------------|-------");
break;
case 8:
Serial.println("--------------|----------");
break;
case 9:
Serial.println("--------------|----------------");
break;
case 10:
Serial.println("--------------|-------------------");
break;
case 11:
Serial.println("--------------|-----------------------");
break;
}
}
void sendDataToSerial(char symbol, int data )
{
Serial.print(symbol);
Serial.println(data);
}
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)
{ // thresh 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(blinkPin,HIGH); // turn on pin 13 LED
IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
lastBeatTime = sampleCounter; // keep track of time for next pulse
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[i] = IBI;
}
}
if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
{
firstBeat = false; // clear firstBeat flag
secondBeat = true; // set the second beat flag
sei(); // enable interrupts again
return; // IBI value is unreliable so discard it
}
// 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[i] = rate[i+1]; // and drop the oldest IBI value
runningTotal += rate[i]; // 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 ISR
pulse = BPM;
}
}
if (Signal < thresh && Pulse == true)
{ // when the values are going down, the beat is over
digitalWrite(blinkPin,LOW); // turn off pin 13 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 = false; // when we get the heartbeat back
}
sei(); // enable interrupts when youre done!
}// end isr
void esp_8266()
{
// TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80
String cmd = "AT+CIPSTART=4,\"TCP\",\"";
cmd += "184.106.153.149"; // api.thingspeak.com
cmd += "\",80";
ser.println(cmd);
Serial.println(cmd);
if (ser.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr +="&field1=";
getStr +=String(pulse);
getStr +="&field2=";
getStr +=String(temp);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=4,";
cmd += String(getStr.length());
ser.println(cmd);
Serial.println(cmd);
delay(1000);
ser.print(getStr);
Serial.println(getStr); //thingspeak needs 15 sec delay between updates
delay(3000);
}
void read_temp()
{
int temp_val = analogRead(A1);
float mv = (temp_val/1024.0)*5000;
float cel = mv/10;
temp = (cel*9)/5 + 32;
Serial.print("Temperature:");
Serial.println(temp);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("BPM :");
lcd.setCursor(7,0);
lcd.print(BPM);
lcd.setCursor(0,1);
lcd.print("Temp.:");
lcd.setCursor(7,1);
lcd.print(temp);
lcd.setCursor(13,1);
lcd.print("F");
}
This is the error:
C:\Users\vaadh\OneDrive\Documents\Arduino\testing_LED_blinking\testing_LED_blinking.ino: In function 'void esp_8266()':
C:\Users\vaadh\OneDrive\Documents\Arduino\testing_LED_blinking\testing_LED_blinking.ino:282:21: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
if (ser.find("Error")){
It is a problem of the Arduino core Stream class's find method. The type of the parameter should be const char* but it is char*.
Cast the parameter to char* to indicate to the compiler that it is OK.
ser.find((char*) "Error")
/*
== MASTER CODE ==
*/
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#define ledPin 9
int state = 0;
int Vry = 0;
int Vrx = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
BTSerial.begin(38400); // HC-05 default speed in AT command more
}
void loop() {
if(BTSerial.available() > 0){ // Checks whether data is comming from the serial port
state = BTSerial.read(); // Reads the data from the serial port
}
// Controlling the LED
/*if (state == '1') {
digitalWrite(ledPin, HIGH); // LED ON
state = 0;
}
else if (state == '0') {
digitalWrite(ledPin, LOW); // LED ON
state = 0;
}
*/
// Reading the potentiometer
//Vry = analogRead(A0);
/*
Vrx = analogRead(A1);
int VrxMapped = map(Vrx, 0, 1023, 0, 255);
//int Vry_mapped = map(Vrx, 0, 1023, 0, 255);
//int Vrx_mapped = map(Vry, 0, 1023, 0, 255);
Serial.print("Vrx");
Serial.println(VrxMapped);
//Serial.print("Vry");
//Serial.println(Vry);
*/
Vrx = analogRead(A1);
BTSerial.write(Vrx);
Serial.print("Vrx: ");
Serial.println(Vrx);
//BTSerial.write(Vry);
delay(2000);
}
and the slave code is as follows,
/*
== SLAVE CODE ==
*/
#include <SoftwareSerial.h>
#define button 8
SoftwareSerial BTSerial(5, 3); // RX | TX
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
int enB = 11;
int in3 = 7;
int in4 = 6;
int jx = A0;
int jy = A1;
int mx = 0; //right motor
int my = 0; //left motor
int state = 0;
int i = 0;
int buttonState = 0;
int ledPin = 13;
void setup() {
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
BTSerial.begin(38400); // HC-05 default speed
Serial.begin(9600);
pinMode(button, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
//my = analogRead(BTSerial.read());
// mx = analogRead(BTSerial.read());
if(BTSerial.available() > 0){ // Checks whether data is comming from the serial port
int state = BTSerial.read(); // Reads the data from the serial port
//Serial.print('y');
//Serial.println(my+100,DEC);
Serial.print('x');
Serial.println(state);
}
if (i == 2){
i=0;
}
/*int mapx = map(mx,0,1023,0,255);
int mapy = map(my,0,1023,0,255);
if (mapx>127)
{
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
analogWrite(enA,mapx);
}
else
{
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(enA,127-mapx);
}
if (mapy>127)
{
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enB,mapy);
}
else
{
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
analogWrite(enB,127-mapy);
}
delay(1000);
*/
/*Serial.println(state);
if(BTSerial.available() > 0){ // Checks whether data is comming from the serial port
state = BTSerial.read(); // Reads the data from the serial port
}
if (state > 120){
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000);
}
else{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
}
// Controlling the servo motor
// Reading the button
buttonState = digitalRead(button);
if (buttonState == HIGH) {
BTSerial.write('1'); // Sends '1' to the master to turn on LED
}
else {
BTSerial.write('0');
}
*/
delay(2000);
}
The problem here is following,
if I send 1 from master I get 130 at slave end, I have no idea how Serial communication works and how data can be received over bluetooth devices!
The serial of bluetooth in read function returns character.
Here is my code so far the system contains an SD card reader, two buzzers, two LEDs, a PIR motion sensor, and a IR receiver.
error message I get are as follows:
1) Final_Build:100: error: redefinition of 'int val'
2) Final_Build:5: error: 'int val' previously defined here
3) Final_Build:101: error: expected unqualified-id before 'if'
4) redefinition of 'int val'
//PIR sensor
int ledPin = 7; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
int pinSpeaker = 10; //Set up a speaker on a PWM pin (digital 9, 10, or 11)
//IR_Sensor
int dtect=3;
int sense=A0;
int buzzpin=9;
int lightPin=6;
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
//PIR sensor
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
//IR sensor
pinMode(dtect,OUTPUT);
pinMode(lightPin,OUTPUT);
pinMode(sense,INPUT);
pinMode(buzzpin,OUTPUT);
digitalWrite(dtect,HIGH);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop(){
//IR sensor
int val=analogRead(sense);
Serial.println(val);
if(val>=800)
{
digitalWrite(lightPin, HIGH);
buzz(50);
}
else {
digitalWrite(lightPin, LOW);
}
}
void buzz(unsigned char time)
{
analogWrite(buzzpin,170);
delay(time);
analogWrite(buzzpin,0);
delay(time);
}
//PIR sensor
int val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
playTone(300, 160);
delay(100);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
playTone(0, 0);
delay(300);
if (pirState == HIGH){
// we have just turned off
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}
This first val definition isn't necessary.
int val = 0; // variable for reading the pin status
You are redifining val at the begining of loop() .
UPDATE:
I think that this is what you want. Your problem is that added buzz function was defined inside loopfunction and you lost some parentesis{}. I just put it out and joined loopcode.
//PIR sensor
int ledPin = 7; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int pinSpeaker = 10; //Set up a speaker on a PWM pin (digital 9, 10, or 11)
//IR_Sensor
int dtect=3;
int sense=A0;
int buzzpin=9;
int lightPin=6;
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
//PIR sensor
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
//IR sensor
pinMode(dtect,OUTPUT);
pinMode(lightPin,OUTPUT);
pinMode(sense,INPUT);
pinMode(buzzpin,OUTPUT);
digitalWrite(dtect,HIGH);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop(){
//IR sensor
int val=analogRead(sense);
Serial.println(val);
if(val>=800)
{
digitalWrite(lightPin, HIGH);
buzz(50);
}
else {
digitalWrite(lightPin, LOW);
}
//PIR sensor
int val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
playTone(300, 160);
delay(100);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
playTone(0, 0);
delay(300);
if (pirState == HIGH){
// we have just turned off
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
void buzz(unsigned char time)
{
analogWrite(buzzpin,170);
delay(time);
analogWrite(buzzpin,0);
delay(time);
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}
My Code:
#include <SoftwareSerial.h>
SoftwareSerial bluetooth(2,3);
// Output
int redPin = 6; // Red LED,
int grnPin = 11; // Green LED,
int bluPin = 5; // Blue LED,
// Color arrays
int black[3] = { 0, 0, 0 };
int white[3] = { 100, 100, 100 };
int red[3] = { 100, 0, 0 };
int green[3] = { 0, 100, 0 };
int blue[3] = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };
// etc.
// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];
int wait = 10; // 10ms internal crossFade delay; increase for slower fades
int hold = 0; // Optional hold when a color is complete, before the next crossFade
int r = 0;
int g = 0;
int b = 0;
char mode = '\0';
// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;
// Set up the LED outputs
void setup()
{
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(grnPin, OUTPUT);
pinMode(bluPin, OUTPUT);
Serial.begin(9600);
delay(1000);
bluetooth.begin(115200);
delay(100);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);
delay(100);
analogWrite(redPin, 0);
analogWrite(grnPin, 0);
analogWrite(bluPin, 0);
Serial.println("Bluetooth initiated.");
}
void printHEX() {
Serial.print(r, HEX);
Serial.print(g, HEX);
Serial.println(b, HEX);
bluetooth.print(r, HEX);
bluetooth.print(g, HEX);
bluetooth.println(b, HEX);
}
// Main program: list the order of crossfades
void loop()
{
//Read from bluetooth and write to usb serial
while(bluetooth.available())
{
if(mode == '\0') {
mode = (char)bluetooth.read();
}
if(mode == 'c'){
int r1 = bluetooth.parseInt();
int g1 = bluetooth.parseInt();
int b1 = bluetooth.parseInt();
if (bluetooth.read() == '\n') {
if(r1 != r || g1 != g || b1 != b) {
r = r1;
g = g1;
b = b1;
analogWrite(redPin, r);
analogWrite(grnPin, g);
analogWrite(bluPin, b);
printHEX();
mode = '\0';
} else {
printHEX();
mode = '\0';
}
}
} else if(mode == 'p') {
if (bluetooth.read() == '\n') {
printHEX();
mode = '\0';
}
}
}
//Read from usb serial to bluetooth
if(Serial.available())
{
char toSend = (char)Serial.read();
bluetooth.print(toSend);
}
}
If I run this code, everything works great. That is until I plug it into the power source and nothing else.
If I plug it into the power source, the program doesn't start (no bluetooth response). If I plug it into usb and power or usb only, the program works. If I unplug usb after plugging usb and power source the program still works! I have tried debugging as much as I can, but I don't know where the error is. The power supply is rated at 12V 2 Amps to light up the LED strips.
Update: I found out that if I press the reset button after power on everything starts to work. Is there a way to automatically reset arduino on startup???
I think you are using arduino leonardo.
Try this at very beginning of setup:
while(!Serial){}
while(!bluetooth){}
The arduino leonardo prepare the serial port after some while and may cause some problems.