Interfacing HC 05 with Atmega?

Somebody please tell me the code to turn ON and OFF a Led on atmega8 board using hc 05 Bluetooth module Some what like this

Question by Mayoogh_Girish   |  last reply


Hc-05 and Arduino connection

Hello to everyone.I have make a bleutooth robot which i can control it via android(tablet) and i have a problem with the code.I want from the robot to stop when connection lost or bluetooth disconnected.Now when the connection lost the robot go ahead and falls on the objects.How to add this line on the code?Can you help me please?The STATE pin of HC-05 when is HIGH is connected and when is LOW is disconnected.I put this on my code but it doesn't stop.Thank you for your time The bluetooth that i use is HC-05 My code: #include Servo SERVO_1; // Initialize Servo1 // Motor Control Variables int PWM1 = 9; int ENABLE1 = 8; int PWM2 = 5; int ENABLE2 = 7; int PWM3 = 3; int ENABLE3 = 4; int PWM4 = 6; int ENABLE4 = 12; int STATE=2; void setup() {   SERVO_1.attach(10);   Serial.begin(9600);   pinMode(ENABLE1, OUTPUT);  //Δήλωση όλων των μεταβλητών ως έξοδος   pinMode(ENABLE2, OUTPUT);  //Δήλωση όλων των μεταβλητών ως έξοδος   pinMode(ENABLE3, OUTPUT);  //Δήλωση όλων των μεταβλητών ως έξοδος   pinMode(ENABLE4, OUTPUT);  //Δήλωση όλων των μεταβλητών ως έξοδος   pinMode(STATE, INPUT); } void loop() {    if(digitalRead(STATE)== HIGH)   // see if there's incoming serial data:   if (Serial.available() > 0) {     // read the oldest byte in the serial buffer:     int incomingByte = Serial.read();     // action depending on the instruction     // as well as sending a confirmation back to the app     switch (incomingByte) {       case 'F':         moveForward();         Serial.println("Going forward");         break;       case 'L' : // Case 'L' is received,         SERVO_1.write (180); // Στρίψε Αριστερά.         SERVO_1.attach(10);         break;       case 'N':         turnright();         Serial.println("Turning right");         break;       case 'M':         turnleft();         Serial.println("Turning left");         break;       case 'O' : // Case 'L' is received,         SERVO_1.write (0); // Στρίψε Αριστερά.         SERVO_1.attach(10);         break;       case 'B':         moveBackward();         Serial.println("Going forward");         break;       case 'P':         SERVO_1.write(90); // Στρίψε Αριστερά.         SERVO_1.attach(10);         break;       case 'S':         moveNone();         Serial.println("Stopping");         break;       default:         // if nothing matches, do nothing         break;     }   } } void moveForward() {   // turn the driving motor on to go forwards at set speed   digitalWrite(ENABLE1, HIGH);   digitalWrite(ENABLE2, HIGH);   digitalWrite(ENABLE3, HIGH);   digitalWrite(ENABLE4, HIGH);   analogWrite(PWM1, 255);   analogWrite(PWM2, 255);   analogWrite(PWM3, 255);   analogWrite(PWM4, 255); } void moveBackward() {   // turn the driving motor on to go backwards at set speed   digitalWrite(ENABLE1, LOW);   digitalWrite(ENABLE2, LOW);   digitalWrite(ENABLE3, LOW);   digitalWrite(ENABLE4, LOW);   analogWrite(PWM1, 255);   analogWrite(PWM2, 255);   analogWrite(PWM3, 255);   analogWrite(PWM4, 255); } void turnright() {   digitalWrite(ENABLE1, HIGH);   digitalWrite(ENABLE2, HIGH);   digitalWrite(ENABLE3, LOW);   digitalWrite(ENABLE4, LOW);   analogWrite(PWM1, 255);   analogWrite(PWM2, 255);   analogWrite(PWM3, 255);   analogWrite(PWM4, 255); } void turnleft() {   digitalWrite(ENABLE1, LOW);   digitalWrite(ENABLE2, LOW);   digitalWrite(ENABLE3, HIGH);   digitalWrite(ENABLE4, HIGH);   analogWrite(PWM1, 255);   analogWrite(PWM2, 255);   analogWrite(PWM3, 255);   analogWrite(PWM4, 255); } void moveNone() {   // turn the driving motor off   digitalWrite(ENABLE1, 0);   digitalWrite(ENABLE2, 0);   digitalWrite(ENABLE3, 0);   digitalWrite(ENABLE4, 0);   analogWrite(PWM1, 0);   analogWrite(PWM2, 0);   analogWrite(PWM3, 0);   analogWrite(PWM4, 0);   SERVO_1.detach(); }

Question by dimitrakis1992   |  last reply


"HC Off-Line Occured" while Interface Sysmex Xp100 machine using serial cable

We are Interface Sysmex XP100 Hematology machine, but we got "HC Off-Line Occured" error. We are using Serial Port 9-pin female pins (2-->3, 3-->2, 5-->5) Our Code To Open Serial Port: SerialPort comport = new SerialPort(); comport.BaudRate = int.Parse(cmbBaudRate.Text); comport.DataBits = int.Parse(cmbDataBits.Text); comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text); comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text); comport.PortName = cmbPortName.Text; comport.Open(); Port successfully open, but when XP100 machine send output, it shows "HC Off-Line Occured" error. Please provide possible solution.

Topic by vishal2   |  last reply


Arduino servos not being supplied enough power by 9V battery?

Hey guys, I'm working on my first instructable which is an robotic snake which you control via the HC-06 bluetooth module and an arduino. I'm using an arduino bluetooth app on my smartphone, but this isn't the problem. There are three servos which I am supplying power to, two continuous rotation servos for movement and one ordinary servo. I'm powering it through a 9V battery thing I got off of the adafruit store, which has the plug that goes into the power supply. When I try to control it like this, the servos twitch and barely move. The ordinary one doesn't as far as I can tell. However, when I supply power through my computer cable, the bluetooth still works from my phone, and the servos go at an ordinary rate. I'm supplying the two continuous rotation servos and the normal one through the 5 volt pin, and the bluetooth module through the 3.3 volt one. Can anyone tell me why it isn't working, or an alternate technique of powering it?

Question by RedCthulu   |  last reply


Can a 9V battery power a Bluetooth module (HC-05)?

I am trying to power Bluetooth module and the Arduino using a 9V battery. So tried to use a voltage regulator (KA7805) with 25volt 100miro farad and 63V 1 micro farad capacitors. I checked the circuit connecting these components using multimeter, it showed 5.06V as the output. But the problem comes when I connect the Bluetooth module to this output, which turns off after quickly. I checked the voltage at the bluetooth which is reducing quickly from 5V-2.5V in a matter of seconds and since the operating voltage of Bluetooth module HC-05 is 3.6V-7V, it turns off. I am not clear why this circuit behaving this way. Same output when I connected to the Arduino, it works seamlessly. Please let me know what are the mistakes that I need to rectify for this work. Thanks in advance

Question by Bhanu Kishan   |  last reply


How to power servo without driver/arduino?

Hi, I'm trying to make a servo motor spin without using a driver or micro controller, I just want to power it directly. It doesn't need to move a specific distance, or be precise. How would I wire this up? The idea is to power it on by using a HC-05 Bluetooth module, either directly, or by optocoupler. It would have to trigger the servo on whenever a Bluetooth device that has already been paired connects to the HC-05 module (in wireless range), and then off when a Bluetooth device disconnects (out of range). My idea is to use an app that automatically plays an audio file through the HC-06 when it connects (this app already exists), and that audio file happens to be the correct frequency to act as a PWM signal. Is this even possible?

Question by dmagryta124   |  last reply


How to make a app and program that triggers 3 led modes... on/Off , Blink , Fade ?

I have makes an Avengers Infinity War style Iron Man Arc Reactor From Arduino Uno R3, 21 Blue LEDs, Some Cardboard , Acrylic Glass/Plexiglass (To Make An Glowing Arc Reactor , And I Am A Noob and want to make an Android app that Control my Arc reactor in 3 ways Blink,FADE,On/Off via Bluetooth Please Help And I Have All 3 Codes To Run Individually (Blink/Fade/On/Off) but I can't figure out how to run them from android appAndroid app can Be Made With MIT App Inventer

Question by ANIKET JOSHI 


Voltage Regulator circuit

I am trying to power Bluetooth module and the Arduino using a 9V battery. So tried to use a voltage regulator (KA7805) with 25volt 100miro farad and 63V 1 micro farad capacitors. I checked the circuit connecting these components using multimeter, it showed 5.06V as the output. But the problem comes when I connect the Bluetooth module to this output, which turns off after quickly. I checked the voltage at the bluetooth which is reducing quickly from 5V-2.5V in a matter of seconds and since the operating voltage of Bluetooth module HC-05 is 3.6V-7V, it turns off. I am not clear why this circuit behaving this way. Same output when I connected to the Arduino, it works seamlessly. Please let me know what are the mistakes that I need to rectify for this work. Thanks in advance

Topic by Bhanu Kishan 


What is the sensor in the night light for it to turn off during daylight and on during night time?

I just saw this instructable https://www.instructables.com/id/LED-CLOCK-cum-NIGHT-LAMP/ I just thought of an idea not to waste my battery so that is why i am asking what is the sensor called my night light looks like this http://www.google.com.ph/imglanding?q=Omni+LED+night+light&um;=1&hl;=en&sa;=N&rlz;=1C1DVCC_enPH364PH364&tbs;=isch:1&tbnid;=wNfOs1_LTi0egM:&imgrefurl;=http://www.mchomedepot.com/index.php%253Froute%253Dproduct/product%2526manufacturer_id%253D104%2526product_id%253D6346&imgurl;=http://www.mchomedepot.com/image/cache/data/2800510000037-500x500.jpg&ei;=s6OITZyBJYHSuwPty8yCDg&zoom;=1&w;=500&h;=500&iact;=hc&oei;=s6OITZyBJYHSuwPty8yCDg&page;=1&tbnh;=162&tbnw;=162&start;=0&ved;=1t:429,r:3,s:0&biw;=1600&bih;=799 i'm asking what is the middle part of it :D and sorry for my bad english :D

Question by tobyscool   |  last reply


Converting delay to millis.? need help !!!! Answered

/* * Hi Everyone.  I am just starting with Arduino uno. I was wondering if you could help me? I would like to replace "delay" with  "millis()"   My Project Out Line. *  "LED Light" On/Off with delay using "Relay Module" and "Bluetooth Hc-05" *   working fine with "delay sketch" but I cannot schedule 2 Events at the same time. *   So remodifing sketch using "Millis" *   original sketch link: https://docs.google.com/document/d/1GpPH8rG_bR2Vp282nv7kyB1Zwa0shtpDcAj3-_txnxE/pub   what will happen is when I send a command A to H the relay will be switched on and if I send a to h the relay will be switched off.   I have programmed it so that   A is relay one on (latched)   B is relay two on (latched)   C is relay one on for 30 Minutes   D is relay two on for 1 Hr   E is relay one on for 2 Hrs   F is relay two on for 5 Hrs   G is relay one on for 1 second, then relay two on then both off   H will switch relay one on and off for 1000 times   the relays switch on when the digital pin is grounded. and the relay switches off when the digital pin goes high   here is the code */ //========================================== // On and Off Times (as int, max=32secs) const unsigned int onTime = 1000; const unsigned int offTime = 500; // Tracks the last time event fired unsigned long previousMillis = 0; // Interval is how long we wait int interval = onTime; // Used to track if LED should be on or off boolean LED2state = true; //========================================== char val;         // variable to receive data from the serial port int ledpin = 2;  // LED connected to pin 2 (on-board LED) const int LED = 13; //  ####### Setup ####### void setup() {   pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT   pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT   Serial.begin(9600);       // start serial communication at 115200bps   pinMode(LED, OUTPUT); } //  ####### loop ####### void loop() {   if ( Serial.available() )      // if data is available to read   {     ;   }   val = Serial.read();         // read it and store it in 'val'   //  #####  Simple LED ON/OFF with out Delay #####   if ( val == 'a' )              // if 'a' was received led 2 is switched off   {     digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2   }   if ( val == 'A' )              // if 'A' was received led 2 on   {     digitalWrite(ledpin = 2, LOW);  // turn ON pin 2   }   if ( val == 'b' )              // if 'b' was received led 3 is switched off   {     digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3   }   if ( val == 'B' )              // if 'B' was received led 3 on   {     digitalWrite(ledpin = 3, LOW);  // turn ON pin 3   } //else (ledpin = 3, LOW)        //set led pin 3 to low state   // Need Help   //  #####  Simple LED ON/OFF with Delay using Millis #####   if ( val == 'C' )              // if 'C' was received led 2 on for 30 Minutes   {     digitalWrite(ledpin = 2, LOW);  // turn ON pin 2     // Grab snapshot of current time, this keeps all timing     // consistent, regardless of how much code is inside the next if-statement     unsigned long currentMillis = millis();     // Compare to previous capture to see if enough time has passed     ((unsigned long)(currentMillis - previousMillis) >= interval); {       // Change wait interval, based on current LED state       if (LED2state) {         // LED is currently on, set time to stay off         interval = offTime;       } else {         // LED is currently off, set time to stay on         interval = onTime;       }       // Toggle the LED's state, Fancy, eh!?       LED2state = !(LED2state);       // Save the current time to compare "later"       previousMillis = currentMillis;       // wait 30 Minutes       digitalWrite(ledpin, HIGH);      // turn Off pin 2     }   } } //Thanks in advance  //Krish

Question by bvamsikr   |  last reply


How do you repair a broken ceramic piggy bank? Answered

My sister's piggy bank broke and she is REALLY torn up about it  (she got it forChristmas and she has broken a bunch of glass lately) and i want to fix it, it is mostly in large pieces, what adhesive, glue, filler, paint should I use? Please respond fast! Thanks! http://www.google.com/imgres?hl=en&safe;=off&sa;=X&biw;=1400&bih;=959&tbm;=isch&prmd;=imvns&tbnid;=Egziqd0BezZXkM:&imgrefurl;=http://www.ohdeedoh.com/ohdeedoh/decorative-accessories-pillows/ugly-dolls-can-save-your-pennies-142081&docid;=87LBDC8Zpw67qM&imgurl;=http://i-cdn.apartmenttherapy.com/uimages/ohdeedoh/032110-ugly.jpg&w;=540&h;=351&ei;=ThX9TrP6MM3sggerhr3iDA&zoom;=1&iact;=hc&vpx;=171&vpy;=479&dur;=1112&hovh;=181&hovw;=279&tx;=101&ty;=91&sig;=110872985198211297103&page;=1&tbnh;=118&tbnw;=181&start;=0&ndsp;=34&ved;=1t:429,r:14,s:0

Question by Zaphod Beeblebrox   |  last reply


Home automation & Home door sequrity including one android apk file project available ???

Please help me for this project. how will be arduino program code , which pin are connect to apparatus to apparatus. please give me all description step by step this project implimentation. Project planning:-                   1.Home automation & Home door sequrity including one android apk file.                   2. 4 Relay:   1. Blue led light.                                 2. Red  led light.                                 3. White led light for bath room using PIR sensor.(this light switch on/off only using pir sensor,                                            because-wet hand electric shock on switch or, damged mobile display).                                 4. Fan using voltage regulator.                                  note:- light switch on/off & fan switch & voltage regulataor incease/decrease including appk file.                   3.Home squrity switch board on/off may be   a.display board on wall of house.                                                                b. display in android apk file.                   4.when open door with corect srquirty,then photo upload in memory card.if incorect password then a lout of sound.                   5.when fire in house ,alarm using gas sensor. Room temperature, huminity show in display. Apparatues:            A: Led light on/off by mobile app.                  1.ESP8266 Serial Wi-Fi Wireless Transceiver Module for IOT.                  2.Generic(unbranded )4-channel relay control board module with optocoupler, 4 way relay module for arduino                  3.Arduino Uno R3 ATmega328P ATMEGA16U2 Compatible with USB Cable.                     or,xcluma Atmel Atmega 2560 Mega2560-16Au (16 Mhz) R3 Board+Usb Cable For Arduino.                  4.Led light 3(Blue,Red,White for Bath room),Motor Fan.                  5.REES52 REES_2 Bread Board or Solderless Pieces Circuit Test Board Project Board.                  6.Jumper Wires Male to Male, male to female, female to female.                  7.Generic KG001 HC-SR501 PIR Sensor Pyroelectric Infrared Module 2pcs(for bath room & door open).                  8.Adraxx LM7805 7508 Positive Voltage Regulator IC, 5V 1A.                  9.Resister 1k ohm.                  10.REES52 MQ2 Arduino Compatible Gas Sensor, Methane, Butane, LPG, Smoke Sensor.           B: Home sequrity.                  1.Quantum QHM495LM 25MP Web Camera.                  2.SanDisk Ultra MicroSDHC 32GB UHS-I Class 10 Memory Card With Adapter.                  3.REES52 621033926893 Universial 16 Key Switch Keypad Keyboard Fit for Arduino by REES52.                  4.Silicon Technolabs 20x4 Line LCD Display With Blue backlight HD44780 for ALL Arduino,Rasp Pi,AVR,ARM,8051 (Blue). Software:      1. Arduino-1.8.5.                2. wampserver & notepad++ (for php web page).                3. Android Apk file.      please help me for this project. how will be arduino program code , which pin are connect to apparatus to apparatus. please give me all description step by step this project implimentation.  i will waiting for you.

Question by somnathpanjaproject2018   |  last reply


i want to start and stop my line follower robot robot by blutooth

Please help me , i have no idea how to change it. i have line follower robot , and i want to operate my robot by blutooth , i want start and stop my line follower robot by blutooh ,my line follower robot code is //code is int rightmotor1=12; int leftmotor1=13; int rightmotor2=9; int leftmotor2=8; int sensorleft=5; int sensorcenter=6; int sensorright=7; int l1=1; int l2=1; int l3=1; int f1=0; int f2=0; int f3=0; ////////////////////////////////////// void setup() { pinMode(rightmotor1,OUTPUT); pinMode(leftmotor1,OUTPUT); pinMode(rightmotor2,OUTPUT); pinMode(leftmotor2,OUTPUT); pinMode(sensorleft,INPUT); pinMode(sensorcenter,INPUT); pinMode(sensorright,INPUT); } /////////////////////////////////////////////////// void loop() { l1=digitalRead(sensorleft); l2=digitalRead(sensorcenter); l3=digitalRead(sensorright); ///////////////////////////////////////////////////////////////////// if(l1==1&&l2;==1&&l3;==1)   //feedback when comes all sensor on white { l1=f1; l2=f2; l3=f3; } //////////////////////////////////////////////////////////////////////////// if(l1==0&&l2;==1&&l3;==1||l1==0&&l2;==0&&l3;==1)   //left turn {   digitalWrite(rightmotor1,1);   digitalWrite(rightmotor2,0);   digitalWrite(leftmotor1,0);   digitalWrite(leftmotor2,0); } else if(l1==1&&l2;==1&&l3;==0||l1==1&&l2;==0&&l3;==0)  //right turn {   digitalWrite(rightmotor1,0);   digitalWrite(rightmotor2,0);   digitalWrite(leftmotor1,1);   digitalWrite(leftmotor2,0); } else if(l1==1&&l2;==0&&l3;==1)  //go forward straight {   digitalWrite(rightmotor1,1);   digitalWrite(rightmotor2,0);   digitalWrite(leftmotor1,1);   digitalWrite(leftmotor2,0); } else if(l1==0&&l2;==0&&l3;==0) //stop {   digitalWrite(rightmotor1,0);   digitalWrite(rightmotor2,0);   digitalWrite(leftmotor1,0);   digitalWrite(leftmotor2,0);   delay(2000);    digitalWrite(rightmotor1,1);   digitalWrite(rightmotor2,0);   digitalWrite(leftmotor1,1);   digitalWrite(leftmotor2,0);   } /////////////////////////////////////////////////////////////////// f1=l1; f2=l2; f3=l3;        //memory variables //////////////////////////////////////////////////////////////////// } , i want to keep all code in function and want to call in blutoooh code i want my robot start and stop by blutooth please help me my blutooth code is #include SoftwareSerial mySerial(10, 11); // RX, TX String state;// string to store incoming message from bluetooth int  LED = 5; // LED on pin 13 void setup() { mySerial.begin(9600); Serial.begin(9600); // serial communication to check the data on serial monitor    pinMode(LED, OUTPUT); mySerial.println("Welcome to the wonderful world of bluetooth communication");   delay(1000);   mySerial.println("Sending a '1' will turn on the LED, Sending a '0' will turn off the LED");   delay(1000);   mySerial.println("a '3' will flash the LED and a '4' will kick out a lot of data from the LDR"); } //-----------------------------------------------------------------------//  void loop() {   while (mySerial.available()){  //Check if there is an available byte to read   delay(10); //Delay added to make thing stable   char c = mySerial.read(); //Conduct a serial read   state += c; //build the string- either "On" or "off"   }    if (state.length() > 0) {     Serial.println(state);   if(state == "turn on")   {     digitalWrite(5, HIGH);           }     else if(state == "turn off")   {     digitalWrite(5, LOW);      }      else if(state == "turn1 on")   {     digitalWrite(5, HIGH);           }     else if(state == "turn2 off")   {     digitalWrite(5, LOW);      }     state ="";}} //Reset the variable i am using arduino atmega2560 and blutooth hc 06 and using  l298n 3 sensor

Topic by ShaidK 


Arduino heating controller: solar panel, oil burner, stove. NEED HELP AND ADVICE

HI this is my first time with arduino and electronics so please be forgiving.i want to make a controller for my home heating system and if it possible be able to control (change temp. setting, see statistic, etc. by phone - Bluetooth).so, i have three source of heat: solar panels (water), oil burner, wet stove. first part of plan is to connect all electrical components correctly (to make sure nothing blowup), second step is the program. third connect controller with phone by android or have a option to send sms to turn on/off oil burner.let's startthe heating system should looks like that (photo attach)please don't focus on the plumbing (that's only sketch), electronic and programing is more important.program (second step) should do:1. if T5 >T2 pomp P2 work 2. if T3>55'C , P3 work but only if O1 is switch off (automatically P1 and M1 is off, because they will be connect directly to O1 power) 3. option to on/off O1 by click on the phone (or by modul GSM in the future e.g sim800L) 4. additionally options 2 and 3 they are conditioned by other sub-option of 5 zones (where hot waterwill flow, so what will be heat): a)olny hot water in the tank- M3 open, b)only underfoor h.- M2 open, c)only radiators- M4 open, d) all heating, no tank- M2 i M3 open, e) all M2 M3 M4 open. so, before turn on O1 start making fire T3, one of the zone have to be pre-sellect.also if T1 >60st.C (and O1 and P3 are off), P4 will turn on (dump extra hot water to underfloor h.).that's all, nothing more .... but it's to much complicate for me right now. :smiley-confuse: and third part: all should be controll by simple phone app (android) e.g. turn on/off oil burner (maybe timer), change temp. in tank, change zone, see statistics etc.thera are elements what i have already- arduino nano-logging data module-relay 8 ports-bluetooth modul At-09, ble-4.0-extension board nano v3.0- temp. sensors DS18B20 i connect everything by all info what i've found in internet. also i tried to do simulation in THINKERCAD but many of my elements are not exist in the program, stiil no win. i didnt want to connect power just in case of blow off :o this is what i already found online:http://www.reuk.co.uk/wordpress/arduino-solar-water-heating-pump-controller-design-and-code/https://thesolaruniverse.wordpress.com/2016/11/21/monitoring-temperatures-in-floor-heating-loops-with-an-arduino-with-data-display-on-a-3-5-tft-screen/http://house4u.com.ua/articles/solar-controller/en/part11.phphttps://www.instructables.com/id/2nd-Gen-Arduino-Hot-Water-Solar-Collector-Controll/https://forum.arduino.cc/index.php?topic=70048.0and about bluetoothhttps://arduino.stackexchange.com/questions/19517/hc-05-bluetooth-module-inq-command-doesnt-worki only showing the links to proof my hour's spend in google.i think first two are the best.so i put together all what i found and this is my first program:const int TANKSENSORT1 = A0; const int TANKSENSORT2 = A1; const int PANELSENSORT5 = A2; const int STOVESENSORT3 = A3; const int FLOORSENSORT4 = A4;const int RELAYO1 = 3; const int RELAYM2 = 4; const int RELAYM3 = 5; const int RELAYM4 = 6; const int POMP2 = 7; const int POMP3 = 8; const int POMP4 = 9;const int diffON = 6; const int diffOFF = 3;void setup(){ Serial.begin(9600);pinMode(PANELSENSORT5, INPUT); pinMode(TANKSENSORT1, INPUT); pinMode(TANKSENSORT2, INPUT); pinMode(STOVESENSORT3, INPUT); pinMode(FLOORSENSORT4, INPUT);pinMode(RELAYO1, OUTPUT); digitalWrite(RELAYO1, LOW); pinMode(RELAYM2, OUTPUT); digitalWrite(RELAYM2, LOW); pinMode(RELAYM3, OUTPUT); digitalWrite(RELAYM3, LOW); pinMode(RELAYM4, OUTPUT); digitalWrite(RELAYM4, LOW); pinMode(POMP2, OUTPUT); digitalWrite(POMP2, LOW); pinMode(POMP3, OUTPUT); digitalWrite(POMP3, LOW); pinMode(POMP4, OUTPUT); digitalWrite(POMP4, LOW);}void loop(){ float solarPanelTemperature = ((analogRead(PANELSENSORT5) / 1024.0) * 5000)/10; float hotWaterTankTemperature = ((analogRead(TANKSENSORT2) / 1024.0) * 5000)/10; if(solarPanelTemperature > (hotWaterTankTemperature + diffON)){ digitalWrite(POMP2, HIGH); do{ delay(250); solarPanelTemperature = ((analogRead(PANELSENSORT5) / 1024.0) * 5000)/10; hotWaterTankTemperature = ((analogRead(TANKSENSORT2) / 1024.0) * 5000)/10; }while(solarPanelTemperature > (hotWaterTankTemperature + diffOFF)); digitalWrite(POMP2, LOW);float stoveTemperature = ((analogRead(STOVESENSORT3) / 1024.0) * 5000)/10; if(stoveTemperature > 55){ digitalWrite(POMP3, HIGH); do{ delay(250); stoveTemperature = ((analogRead(STOVESENSORT3) / 1024.0) * 5000)/10; }while(stoveTemperature < (55)); digitalWrite(POMP3, LOW); // musi byc dodane autoamtyczne wylaczenie pieca O1 jesli T3>55, a jesli T3<55 piec moze byc wlaczonyfloat hotwaterTemperature = ((analogRead(TANKSENSORT1) / 1024.0) * 5000)/10; if(hotwaterTemperature > (60)){ digitalWrite(POMP4, HIGH); do{ delay(250); hotwaterTemperature = ((analogRead(TANKSENSORT1) / 1024.0) * 5000)/10; }while(hotwaterTemperature < (60)); digitalWrite(POMP4, LOW); // still system have to be sure that O1 or stove P3 not working. // if one of those is on (O1 or P3) 'heat dumping' options cant start// still missing: // bluetooth modul // or logging data modul (statistics) // before heating will be on one of the zones have to be setup.(and save) // 'life' option for changing the zones M2, M3, M4 } delay(250); }and i stuck again.i'm looking for advise about proper electronic setup and program the arduino. i believe there are many people like me looking for help, so this post will have a bigger impact.regards

Topic by eukaliptus   |  last reply


new to arduino, want to run a dual display for 2 sensors

I'm new to the Arduino community.  wanting to set up a dual radar setup with 2 ultrasonic sensors,  (Ultrasonic Sensor Module HC-SR04), and outputting to a pair of 7 segment displays ( two 7 segment displays each).  I've found a code to do a single could use a lot of help to output two at the same time, basically 2 lanes without 2 units.  im using an arduino mega, ordered a unor3 and hopefully it can be made to run on one or the other. code is as follows: /* HC-SR04 Sensor    The circuit:     * VCC connection of the sensor attached to +5V     * GND connection of the sensor attached to ground     * TRIG connection of the sensor attached to digital pin 2     * ECHO connection of the sensor attached to digital pin 4  */    /*  This is a radar ping sensor that calcultates the speed of an  object traveling away or towards the sensor. I took some of this  code for the HC-SR04 Sensor implementation by Tautvidas Sipavicius. The rest  is original code from me. I know that the seven segment display  code is not the best to look at or the most optimized but it  serves its purpose just fine and is easy to understand.    Written by Matthew Ladd  */   const int trigPin = 2; const int echoPin = 4;   void setup() {   // initialize serial communication:   Serial.begin(9600);   //First 7 segment (ones place)   pinMode(30,OUTPUT);//F   pinMode(31,OUTPUT);//G   pinMode(32,OUTPUT);//E   pinMode(33,OUTPUT);//D   pinMode(34,OUTPUT);//C   pinMode(35,OUTPUT);//B   pinMode(36,OUTPUT);//A   //Second 7 segment (tens place)   pinMode(37,OUTPUT);//F   pinMode(38,OUTPUT);//G   pinMode(39,OUTPUT);//E   pinMode(40,OUTPUT);//D   pinMode(41,OUTPUT);//C   pinMode(42,OUTPUT);//B   pinMode(43,OUTPUT);//A } void zerofirst(){   digitalWrite(30,LOW);   digitalWrite(31,HIGH);   digitalWrite(32,LOW);   digitalWrite(33,LOW);   digitalWrite(34,LOW);   digitalWrite(35,LOW);   digitalWrite(36,LOW); } void onefirst(){   digitalWrite(30,HIGH);   digitalWrite(31,HIGH);   digitalWrite(32,HIGH);   digitalWrite(33,HIGH);   digitalWrite(34,LOW);   digitalWrite(35,LOW);   digitalWrite(36,HIGH); } void twofirst(){   digitalWrite(30,HIGH);//F   digitalWrite(31,LOW);//G   digitalWrite(32,LOW);//E   digitalWrite(33,LOW);//D   digitalWrite(34,HIGH);//C   digitalWrite(35,LOW);//B   digitalWrite(36,LOW);//A } void threefirst(){   digitalWrite(30,HIGH);//F   digitalWrite(31,LOW);//G   digitalWrite(32,HIGH);//E   digitalWrite(33,LOW);//D   digitalWrite(34,LOW);//C   digitalWrite(35,LOW);//B   digitalWrite(36,LOW);//A } void fourfirst(){   digitalWrite(30,LOW);//F   digitalWrite(31,LOW);//G   digitalWrite(32,HIGH);//E   digitalWrite(33,HIGH);//D   digitalWrite(34,LOW);//C   digitalWrite(35,LOW);//B   digitalWrite(36,HIGH);//A } void fivefirst(){   digitalWrite(30,LOW);//F   digitalWrite(31,LOW);//G   digitalWrite(32,HIGH);//E   digitalWrite(33,LOW);//D   digitalWrite(34,LOW);//C   digitalWrite(35,HIGH);//B   digitalWrite(36,LOW);//A } void sixfirst(){   digitalWrite(30,LOW);//F   digitalWrite(31,LOW);//G   digitalWrite(32,LOW);//E   digitalWrite(33,LOW);//D   digitalWrite(34,LOW);//C   digitalWrite(35,HIGH);//B   digitalWrite(36,LOW);//A } void sevenfirst(){   digitalWrite(30,HIGH);//F   digitalWrite(31,HIGH);//G   digitalWrite(32,HIGH);//E   digitalWrite(33,HIGH);//D   digitalWrite(34,LOW);//C   digitalWrite(35,LOW);//B   digitalWrite(36,LOW);//A } void eightfirst(){   digitalWrite(30,LOW);//F   digitalWrite(31,LOW);//G   digitalWrite(32,LOW);//E   digitalWrite(33,LOW);//D   digitalWrite(34,LOW);//C   digitalWrite(35,LOW);//B   digitalWrite(36,LOW);//A } void ninefirst(){   digitalWrite(30,LOW);//F   digitalWrite(31,LOW);//G   digitalWrite(32,HIGH);//E   digitalWrite(33,HIGH);//D   digitalWrite(34,LOW);//C   digitalWrite(35,LOW);//B   digitalWrite(36,LOW);//A } void zerosecond(){   digitalWrite(37,LOW);   digitalWrite(38,HIGH);   digitalWrite(39,LOW);   digitalWrite(40,LOW);   digitalWrite(41,LOW);   digitalWrite(42,LOW);   digitalWrite(43,LOW); } void onesecond(){   digitalWrite(37,HIGH);   digitalWrite(38,HIGH);   digitalWrite(39,HIGH);   digitalWrite(40,HIGH);   digitalWrite(41,LOW);   digitalWrite(42,LOW);   digitalWrite(43,HIGH); } void twosecond(){   digitalWrite(37,HIGH);//F   digitalWrite(38,LOW);//G   digitalWrite(39,LOW);//E   digitalWrite(40,LOW);//D   digitalWrite(41,HIGH);//C   digitalWrite(42,LOW);//B   digitalWrite(43,LOW);//A } void threesecond(){   digitalWrite(37,HIGH);//F   digitalWrite(38,LOW);//G   digitalWrite(39,HIGH);//E   digitalWrite(40,LOW);//D   digitalWrite(41,LOW);//C   digitalWrite(42,LOW);//B   digitalWrite(43,LOW);//A } void foursecond(){   digitalWrite(37,LOW);//F   digitalWrite(38,LOW);//G   digitalWrite(39,HIGH);//E   digitalWrite(40,HIGH);//D   digitalWrite(41,LOW);//C   digitalWrite(42,LOW);//B   digitalWrite(43,HIGH);//A } void fivesecond(){   digitalWrite(37,LOW);//F   digitalWrite(38,LOW);//G   digitalWrite(39,HIGH);//E   digitalWrite(40,LOW);//D   digitalWrite(41,LOW);//C   digitalWrite(42,HIGH);//B   digitalWrite(43,LOW);//A } void sixsecond(){   digitalWrite(37,LOW);//F   digitalWrite(38,LOW);//G   digitalWrite(39,LOW);//E   digitalWrite(40,LOW);//D   digitalWrite(41,LOW);//C   digitalWrite(42,HIGH);//B   digitalWrite(43,LOW);//A } void sevensecond(){   digitalWrite(37,HIGH);//F   digitalWrite(38,HIGH);//G   digitalWrite(39,HIGH);//E   digitalWrite(40,HIGH);//D   digitalWrite(41,LOW);//C   digitalWrite(42,LOW);//B   digitalWrite(43,LOW);//A } void eightsecond(){   digitalWrite(37,LOW);//F   digitalWrite(38,LOW);//G   digitalWrite(39,LOW);//E   digitalWrite(40,LOW);//D   digitalWrite(41,LOW);//C   digitalWrite(42,LOW);//B   digitalWrite(43,LOW);//A } void ninesecond(){   digitalWrite(37,LOW);//F   digitalWrite(38,LOW);//G   digitalWrite(39,HIGH);//E   digitalWrite(40,HIGH);//D   digitalWrite(41,LOW);//C   digitalWrite(42,LOW);//B   digitalWrite(43,LOW);//A } long distanceOverTime(long first,long second){  return ((first-second)/.1)*.0223693629;//taking cm/s to mph } long holder;//store the cm from last time through loop. long temp;//used to store the speed value after changes int counter; void loop() {   // establish variables for duration of the ping,   // and the distance result in inches and centimeters:   long duration, inches, cm;   int tens;   int ones;   long Speed;   // The sensor is triggered by a HIGH pulse of 10 or more microseconds.   // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:   pinMode(trigPin, OUTPUT);   digitalWrite(trigPin, LOW);   delayMicroseconds(2);   digitalWrite(trigPin, HIGH);   delayMicroseconds(10);   digitalWrite(trigPin, LOW);     // Read the signal from the sensor: a HIGH pulse whose   // duration is the time (in microseconds) from the sending   // of the ping to the reception of its echo off of an object.   pinMode(echoPin, INPUT);   duration = pulseIn(echoPin, HIGH);     // convert the time into a distance   inches = microsecondsToInches(duration);   cm = microsecondsToCentimeters(duration);   Speed=distanceOverTime(holder,cm);   holder=cm;//after speed caclulation so take the cm value for another calculation   Speed=abs(Speed);   if(Speed!=0 || counter==10){     temp=Speed;     counter=0;   }else{     counter++;   }   if(temp>=100){    zerofirst();    zerosecond();   }else{     ones=temp%10;     tens=temp/10;   }   if(ones == 0){     zerofirst();   }else if(ones==1){     onefirst();   }else if(ones==2){     twofirst();   }else if(ones==3){     threefirst();   }else if(ones==4){     fourfirst();   }else if(ones==5){     fivefirst();   }else if(ones==6){     sixfirst();   }else if(ones==7){     sevenfirst();   }else if(ones==8){     eightfirst();   }else if(ones==9){     ninefirst();   }   if(tens == 0){     zerosecond();   }else if(tens==1){     onesecond();   }else if(tens==2){     twosecond();   }else if(tens==3){     threesecond();   }else if(tens==4){     foursecond();   }else if(tens==5){     fivesecond();   }else if(tens==6){     sixsecond();   }else if(tens==7){     sevensecond();   }else if(tens==8){     eightsecond();   }else if(tens==9){     ninesecond();   }       Serial.print(inches);   Serial.print(" in, ");   Serial.print(cm);   Serial.print(" cm, ");   Serial.print(Speed);   Serial.print(" mph");   Serial.println();     delay(100); }   long microsecondsToInches(long microseconds) {   // According to Parallax's datasheet for the PING))), there are   // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per   // second).  This gives the distance travelled by the ping, outbound   // and return, so we divide by 2 to get the distance of the obstacle.   // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf   return microseconds / 74 / 2; }   long microsecondsToCentimeters(long microseconds) {   // The speed of sound is 340 m/s or 29 microseconds per centimeter.   // The ping travels out and back, so to find the distance of the   // object we take half of the distance travelled.   return microseconds / 29 / 2; } again, all your help and thought are appricated

Topic by herb1977   |  last reply


How to get data from a load sensor through bluetooth module on an Android App/Arduino?

I am creating a mobile android application which gets data from a load sensor connected to HC-06 Bluetooth module and sends the data to a mobile application. The mobile app has two activities one for listing the bluetooth devices available and the other is the main activity to get data from the load sensor. I have managed to connect/pair with the Bluetooth module but I am unable to get data from it. The main activity consists of a button 'btnScan' that will get the data, and a text field to display the data. Can someone please help?  Here is the MainActivity File package com.uniproj.senseplate; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;   public class MainActivity extends Activity {       Button btnscan;   TextView txtArduino, txtString, txtStringLength, calorie;   Handler bluetoothIn;   final int handlerState = 0;             //used to identify handler message   private BluetoothAdapter btAdapter = null;   private BluetoothSocket btSocket; //= null;   private StringBuilder recDataString = new StringBuilder();      private ConnectedThread mConnectedThread;       // SPP UUID service - this should work for most devices   private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");     // String for MAC address   private static String address; @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       //Link the buttons and textViews to respective views                    btnscan = (Button) findViewById(R.id.scanBtn);                 txtString = (TextView) findViewById(R.id.txtString);     txtStringLength = (TextView) findViewById(R.id.testView1);       calorie = (TextView) findViewById(R.id.sensorView1);     bluetoothIn = new Handler() {         public void handleMessage(android.os.Message msg) {             if (msg.what == handlerState) {          //if message is what we want              String readMessage = (String) msg.obj;                                                                // msg.arg1 = bytes from connect thread                 recDataString.append(readMessage);              //keep appending to string until ~                 int endOfLineIndex = recDataString.indexOf("~");                    // determine the end-of-line                 if (endOfLineIndex > 0) {                                           // make sure there data before ~                     String dataInPrint = recDataString.substring(0, endOfLineIndex);    // extract string                     txtString.setText("Data Received = " + dataInPrint);                                 int dataLength = dataInPrint.length();       //get length of data received                     txtStringLength.setText("String Length = " + String.valueOf(dataLength));                                         if (recDataString.charAt(0) == '#')        //if it starts with # we know it is what we are looking for                     {                      //get sensor value from string between indices 1-5                      String weight = recDataString.substring(1, 5);                      //update the textviews with sensor values                      calorie.setText(weight + "kg");                            }                     recDataString.delete(0, recDataString.length());      //clear all string data                    // strIncom =" ";                     dataInPrint = " ";                 }                        }         }     };           btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter     checkBTState();        // Set up onClick listeners for button to scan for data     btnscan.setOnClickListener(new OnClickListener() {       public void onClick(View v) {         mConnectedThread.read("1");       }     }); }   private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {             return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);       //creates secure outgoing connecetion with BT device using UUID   }       @Override   public void onResume() {     super.onResume();         //Get MAC address from DeviceListActivity via intent     Intent intent = getIntent();         //Get the MAC address from the DeviceListActivty via EXTRA     address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);     //create device and set the MAC address     BluetoothDevice device = btAdapter.getRemoteDevice(address);          try {         btSocket = createBluetoothSocket(device);     } catch (IOException e) {      Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();     }      // Establish the Bluetooth socket connection.     try     {       btSocket.connect();     } catch (IOException e) {       try       {         btSocket.close();       } catch (IOException e2)       {      //insert code to deal with this       }     }     mConnectedThread = new ConnectedThread(btSocket);     mConnectedThread.start();         //I send a character when resuming.beginning transmission to check device is connected     //If it is not an exception will be thrown in the write method and finish() will be called     //mConnectedThread.write("x");   }     @Override   public void onPause()   {     super.onPause();     try     {     //Don't leave Bluetooth sockets open when leaving activity       btSocket.close();     } catch (IOException e2) {      //insert code to deal with this     }   } //Checks that the Android device Bluetooth is available and prompts to be turned on if off   private void checkBTState() {     if(btAdapter==null) {      Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();     } else {       if (btAdapter.isEnabled()) {       } else {         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);         startActivityForResult(enableBtIntent, 1);       }     }   }     //create new class for connect thread   private class ConnectedThread extends Thread {         private final InputStream mmInStream;         @SuppressWarnings("unused")   private final OutputStream mmOutStream;               //creation of the connect thread         public ConnectedThread(BluetoothSocket socket) {          btSocket = socket;             InputStream tmpIn = null;             OutputStream tmpOut = null;             try {              //Create I/O streams for connection                 tmpIn = socket.getInputStream();                 tmpOut = socket.getOutputStream();             } catch (IOException e) { }                   mmInStream = tmpIn;             mmOutStream = tmpOut;         }                 public void run() {             byte[] buffer = new byte[1024];              int bytes;             // Keep looping to listen for received messages             while (true) {                 try {                     bytes = mmInStream.read(buffer);                     bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();                 } catch (IOException e) {                     break;                 }             }         }                 //write method         public void read(String input) {             byte[] bytes = input.getBytes();//converts entered String into bytes             try {                 mmInStream.read(bytes);//write bytes over BT connection via outstream             } catch (IOException e) {               //if you cannot write, close the application              Toast.makeText(getBaseContext(), "Connection Failed", Toast.LENGTH_LONG).show();              finish();                            }          }      } } Here is the Arduino file #include int led = 13; int button = 12; LiquidCrystal lcd(9, 8, 4, 5, 6, 7); // Pins used for inputs and outputs******************************************************** float sensorValue1; float containerValue; char inbyte = 0; int flag; const int numReadings = 50; int readings[numReadings]; int index = 0; int total = 0; int average = 0; //******************************************************************************************* void setup() {     pinMode(led, OUTPUT);   digitalWrite(led, HIGH);   Serial.begin(9600);     for (int thisReading = 0; thisReading < numReadings; thisReading++)   {       readings[thisReading] = 0;   }     lcd.begin(16, 2); //change to 16, 2 for smaller 16x2 screens   lcd.clear();   lcd.print("hello, world!");   delay (1000);   lcd.clear();   delay (500); } void loop() {   digitalWrite(led, HIGH);   readSensor2();    //DONE       printLCD();       //DONE   return; sendAndroidValues();   //when serial values have been received this will be true   if (Serial.available() > 0)   {     inbyte = Serial.read();     if (inbyte == '0')     {       //LED off       digitalWrite(led, LOW);     }     if (inbyte == '1')     {       //LED on       digitalWrite(led, HIGH);     }   }     //delay by 2s. Meaning we will be sent values every 2s approx   //also means that it can take up to 2 seconds to change LED state   delay(2000); void readSensor2() {   total = total - readings[index];     readings[index] = analogRead(A0);     total = total + readings[index];     index = index + 1;     if (index >= numReadings)   {      index = 0;   }     average = total / numReadings;        //sensorValue1 = (analogRead(A0) - 330)* i;    //delay(200);         Serial.println(average);    delay(100);          if( digitalRead(button) == HIGH && flag == 1)   {     flag = 0;     containerValue = 0;      }   else if (digitalRead(button) == HIGH && flag != 1) {   flag = 1;                        //when the button is pressed the initially sesnsor     containerValue = sensorValue1;      delay(10);   }     //Serial.println(digitalRead(button));    delay (1000);    } //sends the values from the sensor over serial to BT module void sendAndroidValues() {   //puts # before the values so our app knows what to do with the data Serial.print('#');   //for loop cycles through 4 sensors and sends values via serial   Serial.print(sensorValue1);   Serial.print('+');     //technically not needed but I prefer to break up data values     //so they are easier to see when debugging Serial.print('~'); //used as an end of transmission character - used in app for string length Serial.println(); delay(5000);        //added a delay to eliminate missed transmissions } void printLCD() {   lcd.setCursor(4, 0);   lcd.print("   GRAMS    ");   lcd.setCursor(4, 1);   lcd.print(sensorValue1); }

Question by AyoS1   |  last reply