Arduino seeing only one button input and ingoring the rest without delay?

Heya! I'm making a project that involves precision timing but I ran into a problem. I when I press a button the Arduino registers many '1's'. But in my code I want it to only see the first input and ignore the rest until the pin goes low again. I'm not trying to debounce or anything. Thanks!

Posted by HavocRC 4 years ago


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

Asked by bvamsikr 2 years ago



What would happen if an Arduino had its crystal replaced with one at a different speed?

Would the time functions (delay, delayMicroseconds, millis, micros) wait the same amount of time (or increment as fast as for millis and micros), or would their time or speed be affected?

Asked by VirtualBoxer 5 years ago



Please can you Rate?

Please can anyone rate and suggest for my new instructable: https://www.instructables.com/id/Recycled-Milli-Volt-Power-Supply/

Posted by Patel Darshil 1 year ago


Switch button

I have connect Arduino with wave shield and 2 switch buttons to play wave when the buttons are pressed but it played it automatically with out any press and it repeat I don't now why .. void loop() {   trackNum = findGPSLatLng();   Serial.println(trackNum);     // Get if a button was pushed   buttonState1 = digitalRead(buttonPin0); buttonState2 = digitalRead(buttonPin1);        if(buttonState1 == HIGH && previous1 == LOW && millis() - time > debounce)   {     audioSelectFlag = 1;   }   else if(buttonState2 == HIGH && previous2 == LOW && millis() - time > debounce)   {    audioSelectFlag = 2;   } time = millis();     //  here is the wave files to play   switch (trackNum) {     case 5:     if(audioSelectFlag == 1  || audioSelectFlag == 2)         playcomplete("1.WAV");         break;         case 1:       if(audioSelectFlag == 1)         playcomplete("1.WAV");       else if(audioSelectFlag == 2)         playcomplete("1b.WAV");       break;     case 2:       if(audioSelectFlag == 1)         playcomplete("2a.WAV");       else if(audioSelectFlag == 2)         playcomplete("2b.WAV");       break;     case 3:       if(audioSelectFlag == 1)         playcomplete("3a.WAV");       else if(audioSelectFlag == 2)         playcomplete("3b.WAV");       break;   } }

Asked by moonwa 5 years ago



ATTINY As A Clock?

Will using time library with an Attiny/45/85/84 ( http://playground.arduino.cc/Code/Time ) create an accurate clock? I keep on seeing people using these external crystal things. Do I need one? Isn't millis pretty dang accurate? How would I sync the clock with real time?

Posted by HavocRC 3 years ago


Why isn't my ATTiny85 accepting this SoftwareSerial???!? Answered

My code is from the IR Cloud light instructable. I am trying to place a smaller, more abbreviated code into an ATTiny85. The tutorial written by MIT says we can put SoftWareSerial on it (reference: http://hlt.media.mit.edu/?p=1695). But anyway, Code: #include int RECV_PIN = 0; int green = 4; int yellow = 2; int blue = 3; int white = 1; #define powercode 16712445 #define stormcode 16745085                 IRrecv irrecv(RECV_PIN); decode_results results; void setup() {   pinMode(green, OUTPUT);     pinMode(yellow, OUTPUT);         pinMode(blue, OUTPUT);             pinMode(white, OUTPUT);   irrecv.enableIRIn(); // Start the receiver } int whitebool = 0; int rainbool = 0; int yellowbool = 0; int bluebool = 0; int greenbool = 0; unsigned long last = millis(); void loop() {   if (irrecv.decode(&results)) {                      //Sun if (results.value == 16712445) {       if (millis() - last > 250) {         whitebool = !whitebool;         digitalWrite(white, whitebool ? HIGH : LOW);       }       last = millis();     }     //red       if (results.value == 16745085) {       if (millis() - last > 250) {         greenbool = !greenbool;         digitalWrite(green, greenbool ? HIGH : LOW);       }       last = millis();     } //yellow     if (results.value == 16726725) { // Sun up       // If it's been at least 1/4 second since the last       // IR received, toggle the relay       if (millis() - last > 250) {         yellowbool = !yellowbool;         digitalWrite(yellow, yellowbool ? HIGH : LOW);       }       last = millis();     } //blue         if (results.value == 16759365) { // Sun up       // If it's been at least 1/4 second since the last       // IR received, toggle the relay       if (millis() - last > 250) {         bluebool = !bluebool;         digitalWrite(blue, bluebool ? HIGH : LOW);       }       last = millis();     }     irrecv.resume(); // Receive the next value   }     } And error : /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp: In member function 'void IRsend::mark(int)': /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:227: error: 'TCCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:227: error: 'COM2B1' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp: In member function 'void IRsend::space(int)': /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:235: error: 'TCCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:235: error: 'COM2B1' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp: In member function 'void IRsend::enableIROut(int)': /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:253: error: 'TIMSK2' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'TCCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'WGM20' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'TCCR2B' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'WGM22' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'CS20' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'OCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:263: error: 'OCR2B' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp: In member function 'void IRrecv::enableIRIn()': /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'TCCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'WGM21' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'TCCR2B' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'CS21' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'OCR2A' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:279: error: 'TCNT2' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:282: error: 'TIMSK2' was not declared in this scope /Users/pdyates/Documents/Arduino/libraries/IRremote/IRremote.cpp:282: error: 'OCIE2A' was not declared in this scope What's the big idea??? If this is way too deep, I'll just use an Arduino Uno for this project... I just really want this to be tiny. :(

Asked by pyates1 5 years ago


Arduino capacitive touch sensor help

So I have been messing around with the Arduino Capsense library with the immensely helpful guide; https://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay; #include #include                                           //change '42' to any desired pin... long time = 0; int state = HIGH; boolean yes; boolean previous = false; int debounce = 200; CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);  // To add more sensors... //CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil //CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil void setup()                    {    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);    pinMode(13, OUTPUT);   } void loop()                    {     long total1 =  cs_4_2.capacitiveSensor(30);            if (total1 > 60){yes = true;}     else {yes = false;}            // to toggle the state of state         if(yes == true && previous  == false && millis() - time>debounce){              if(state == LOW){          state = HIGH; }     else state = LOW;     time = millis();     }                     digitalWrite(13, state);            previous = yes;                 delay(10); } and here's the code for the two sensors and relays #include int led = 13;     int led2 = 12;    long time = 0; int state = HIGH; long time2 = 0; int state2 = HIGH; boolean yes; boolean previous = false; boolean yes2; boolean previous2 = false; int debounce = 200; CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);        void setup()                    {    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);    cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...    pinMode(led, OUTPUT);    pinMode(led2, OUTPUT); } void loop()                    {     int total1 =  cs_4_2.capacitiveSensor(30);     Serial.println(total1);     int total2 =  cs_5_7.capacitiveSensor(30);                     if (total1 > 60){yes = true;}     else {yes = false;}    if (total2 > 60){yes2 = true;}     else {yes2 = false;}           // to toggle the state of state     if(yes == true && previous  == false && millis() - time>debounce){                    if(state == LOW){          state = HIGH;        }        else          state = LOW;          time = millis();      }                          if(yes2 == true && previous2  == false && millis() - time2>debounce){                   if(state2 == LOW){          state2 = HIGH;        }        else          state2 = LOW;            time2 = millis();            }                 digitalWrite(led, state);       previous = yes;       digitalWrite(led2, state2);       previous2 = yes2;                  delay(10); } Any suggestions are always helpful.

Posted by dudes 3 years ago


what to do with extra dvd burner?

I have a extra dvd burner i want to make something from it PLEASE SUGGEST IDEAS i thought to make laser cutter but even if i will make one its power would to so less (this is my calculation that its power should be in milli Watts correct me if i am wrong)

Asked by Atul009 5 years ago


Arduino with flow sensor and relay

Hello. I'm needing help on a project with a water flow sensor. Basically, I'm trying to activate a relay (to turn on a motor) when the Arduino board senses any water flow present for 15 seconds or more. I was expecting the relay to turn on after the flow sensor picked up water flow for 15 seconds. After I ran the code, I had water flowing through the flow sensor for 5 seconds and then I shut off the water. The relay still turned on 10 seconds later. I didn't want this to happen. Instead, I would like to have the relay turn on only after there is water flow for at least 15 seconds. Please review my code below. I would appreciate any help. Thank you!!!byte sensorInterrupt = 0; byte statusLed = 13;byte sensorPin = 2;const int threshold = 15000; // thresholdfloat calibrationFactor = 4.5;volatile byte pulseCount; float flowRate;unsigned int flowMilliLitres;unsigned long totalMilliLitres;unsigned long oldTime;unsigned int countstart = 0;unsigned long starttime;unsigned long endtime;unsigned long elapsedtime;void setup(){ Serial.begin(9600); pinMode(statusLed, OUTPUT); digitalWrite(statusLed, HIGH); // We have an active-low LED attached pinMode(sensorPin, INPUT); digitalWrite(sensorPin, HIGH); pinMode(7, OUTPUT);// connected to relay pulseCount = 0; flowRate = 0.0; flowMilliLitres = 0; totalMilliLitres = 0; oldTime = 0; attachInterrupt(sensorInterrupt, pulseCounter, FALLING);}void loop(){ while (1){ if((millis() - oldTime) > 1000) // Only process counters once per second { detachInterrupt(sensorInterrupt); flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor; oldTime = millis(); flowMilliLitres = (flowRate / 60) * 1000; totalMilliLitres += flowMilliLitres; unsigned int frac; Serial.print("Flow rate: "); Serial.print(int(flowRate)); // Print the integer part of the variable Serial.print("L/min"); Serial.print("\t"); // Print tab space Serial.print("Output Liquid Quantity: "); Serial.print(totalMilliLitres); Serial.println("mL"); Serial.print("\t"); // Print tab space Serial.print(totalMilliLitres/1000); Serial.print("L"); pulseCount = 0; attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } if( totalMilliLitres > 0 && countstart == 0) { starttime = millis(); countstart = 1; } if ( totalMilliLitres > 0 ) { endtime = millis(); elapsedtime = endtime - starttime; } if (elapsedtime >= threshold){ digitalWrite(7,HIGH); // Activate relay to turn on motor delay(10000); digitalWrite(7,LOW); // Deactivate relay to turn on motor totalMilliLitres = 0; countstart = 0; elapsedtime = 0; break; } else{ digitalWrite(statusLed, LOW); // Turn the LED off digitalWrite(7, LOW);// turn relay OFF } }}void pulseCounter(){ // Increment the pulse counter pulseCount++;}

Posted by Eric-soberano 4 months ago


How can I get the MilliAmps lower on a adjustable power adapter?

Im looking to power a 12V 200mm Fan with a adjustable power adapter which is set to 12V DC. The thing is the fan only needs 0.16mA "Milli Amps" while the adapter gives 0.5 How can I lower this physically?Maybe open the adapter and break some things replace then etc etc. Thanks

Asked by Cartman007 8 years ago


Help with Arduino code. Works fine, then ignores parts of the code.

Alright, a bit of a complicated question, so bear with me (if you dare) __Purpose of project:__ Build a robot that solves the game "Fastest King" as fast as possible http://www.youtube.com/watch?v=GwGBUKCoIBs Here is a video of the game being played. The object is to clear the descending squares as fast as humanly (or robotically, in this case) possible. __Method of attack:__ -Four servos with attachments that allow interface with capacitve touch screens are positioned above each button -Four Photoresistors detect when a square is in the bottom position, ready to be pressed. -Potentiometer to control the speed of the arms and how fast they return to the "unpressed" position (denoted in the code by "d" or the delay in between the servo write commands) -On off switch, of course -All I/O is controlled by an arduino nano 328 IMAGES http://imgur.com/a/EprMu apologies for the terrible image quality, can update with better ones if necessary. (seems simple enough, right?) __Description of problem:__ Everything works swimmingly, except the game doesn't "remove" the square as soon as the correct button is pressed. this causes, when "d" is sufficiently low (100-75ms), the servos to press more than once for each square, causing mistakes within the game, slowing the overall time down. __Attempted fix:__ I attempted to implement some code that would cause each if statement checking for the square to also check that it hadn't pressed earlier within a certain time "doubletapdelay" effectively adding a delay in between doubletaps but leaving the rest of the servos free to activate. the odd thing is, the code i put in, (visible below, relevant parts bolded and commented) works well, but sometimes is completely ignored. even with the doubletap delay at 1000 ms while testing it, it would occasionally run as if it wasn't checking for double taps at all. If you think you can help out, or have a better idea for a way to do anything in this project, feel free to let me know. also, i can post any information you would like about this such as additional pictures or video, (though video is a bit difficult since my phone is inside of the machine whilst operating. Thanks again guys, you  rock. -------------------------------------------------code--------------------------------------------------------- important parts bolded #include Servo servo1; Servo servo2; Servo servo3; Servo servo4; boolean activate; int x; int i; int d = 125; int e; int inputYellow = 0; int inputBlue = 1; int inputGreen = 2; int inputPink = 3; int potPin1 = 4; int toggle = 12; int input1; int input2; int input3; int input4; int threshold = 450; int thresholdYellow = 200; int thresholdBlue = 400; int thresholdGreen = 200; int thresholdPink = 320; int doubletapdelay = 125; int delayYellow = 0; int delayBlue = 0; int delayGreen = 0; int delayPink = 0; void setup() { Serial.begin(9600); servo1.attach(9); servo2.attach(8); servo3.attach(7); servo4.attach(6); pinMode(toggle,INPUT_PULLUP); servo1.write(180); servo2.write(90); servo3.write(110); servo4.write(90); delay(1000); } void loop() { d = map(analogRead(potPin1), 0, 1023, 50, 200); if(!activate)Serial.println(d);   if(digitalRead(toggle) == HIGH) {    activate = false; } else { activate = true; }   if(activate) {         if(analogRead(inputYellow) // checks light level on  photoresistor   if((millis() - delayYellow) >= doubletapdelay){    // checks to see when last time this servo was activated   Serial.print("Yellow: "); Serial.println(analogRead(inputYellow));   //prints if servo activates successfully     servo1.write(120);     delay(d);     servo1.write(130);     delay(d);     delayYellow = millis();    //records last time servo successfully activated         }else{     Serial.println("yellow locked out");    //prints if servo tried again too soon   } } if(analogRead(inputBlue)   if((millis() - delayBlue) >= doubletapdelay){   Serial.print("Blue: "); Serial.println(analogRead(inputBlue));     servo2.write(17);     delay(d);     servo2.write(30);     delay(d);     delayBlue = millis();     }else{     Serial.println("blue locked out");   } } if(analogRead(inputGreen)   if((millis() - delayGreen) >= doubletapdelay){   Serial.print("Green: "); Serial.println(analogRead(inputGreen));     servo3.write(15);     delay(d);     servo3.write(40);     delay(d);     delayGreen = millis();     }else{     Serial.println("green locked out");   } }        if(analogRead(inputPink)   if((millis() - delayPink) >= doubletapdelay){   Serial.print("Pink: "); Serial.println(analogRead(inputPink));     servo4.write(160);     delay(d);     servo4.write(140);     delay(d);     delayPink = millis();     }else{     Serial.println("pink locked out");   } }    } else { servo1.write(180); servo2.write(90); servo3.write(110); servo4.write(90); } }

Asked by awesomesquared 5 years ago


Sequential Loops for Pin Activation?

Hi, I am starting with Arduino and I am in need of some help. I am trying to sequentially activate 5 pins. I need each pin to be active for 20 seconds in a PWM manner. During their active period I want an arduino sensor to read out the signals emmited by each pin effector. So far I have no problems with the PWM or sensing module code. However I am not able to find how to correctly sequentially activate the pins. I used millis(), etc, but so far I was able to only activate / read the signals from the first pin effector. The sketch doesn´t proceed to the 2nd --- pins. I really very much appreciate your help....Here goes the code so far... const int greenPin = 11; const int redPin = 10; const int irPin = 5; const int bluePin = 6; const int yellowPin = 9; const int outputLDR = 12; const int ldrSensor = A0; int brightness = 0; int increment = 1; int readingoutputLDR = 0; void setup() {   pinMode(greenPin, OUTPUT);   pinMode(redPin, OUTPUT);   pinMode(irPin, OUTPUT);   pinMode(bluePin, OUTPUT);   pinMode(yellowPin, OUTPUT);   Serial.begin(9600);     setup_parallax(); } void loop() { digitalWrite(outputLDR, HIGH); readingoutputLDR = analogRead(ldrSensor); while (millis()                 {                                       if(brightness > 255)                    {                     increment = -1; // count down after reaching 255                    }                    else if(brightness                    {                    increment = 1; // count up after dropping back down to 0                    }                    brightness = brightness + increment;                                                        analogWrite(greenPin, brightness); digitalWrite(redPin, LOW); digitalWrite(irPin, LOW); digitalWrite(bluePin, LOW); digitalWrite(yellowPin, LOW);                    Serial.print("Reading Green"); parallax_output();                                     } delay(1); while (millis()                 {                                       if(brightness > 255)                    {                     increment = -1; // count down after reaching 255                    }                    else if(brightness                    {                    increment = 1; // count up after dropping back down to 0                    }                    brightness = brightness + increment;                    delay(1);                    digitalWrite(greenPin, LOW); analogWrite(redPin, brightness); digitalWrite(irPin, LOW); digitalWrite(bluePin, LOW); digitalWrite(yellowPin, LOW);                   Serial.print("Reading Red"); parallax_output();                                  }   while (millis()                 {                                       if(brightness > 255)                    {                     increment = -1; // count down after reaching 255                    }                    else if(brightness                    {                    increment = 1; // count up after dropping back down to 0                    }                    brightness = brightness + increment;                    delay(1);                    digitalWrite(greenPin, LOW); digitalWrite(redPin, LOW); analogWrite(irPin, brightness); digitalWrite(bluePin, LOW); digitalWrite(yellowPin, LOW);                     Serial.print("Reading IR"); parallax_output();                                  } while (millis()                 {                                       if(brightness > 255)                    {                     increment = -1; // count down after reaching 255                    }                    else if(brightness                    {                    increment = 1; // count up after dropping back down to 0                    }                    brightness = brightness + increment;                    delay(1);                    digitalWrite(greenPin, LOW); digitalWrite(redPin, LOW); digitalWrite(irPin, LOW); analogWrite(bluePin, brightness); digitalWrite(yellowPin, LOW);                    Serial.print("Reading Blue"); parallax_output();                                  } while (millis()                 {                                       if(brightness > 255)                    {                     increment = -1; // count down after reaching 255                    }                    else if(brightness                    {                    increment = 1; // count up after dropping back down to 0                    }                    brightness = brightness + increment;                    delay(1);                    digitalWrite(greenPin, LOW); digitalWrite(redPin, LOW); digitalWrite(irPin, LOW); digitalWrite(bluePin, LOW); analogWrite(yellowPin, brightness);                   Serial.print("Reading Yellow"); parallax_output();                                  } } void parallax_output() {                    Serial.print("DATA,DATE,TIME,");                                                                Serial.println(readingoutputLDR);                    } void setup_parallax() {     Serial.println("CLEARDATA");     Serial.println("LABEL,Date,Time,Green Response, Red Response, IR Response, Blue Response, Yellow Response"); }

Asked by aureta 3 years ago


I need help seuencing 6 LED's with Potentiometer on Arduino to have lights move to end of line then return to the start?

OK - I have an arduino duemilanove. I am a novice trying to learn new tricks. I have connected up  a 6 LED chaser with a potentiometer controlling its speed. I don't want the light to go back and forth accross the line of LEDs knightrider style - I have tried this and it works no problem. No instead I want it to go to the end, then return to first LED. Can anyone help me with the code? I have the ASK Manual code which I want to alter for it? this is the ASK manual code that makes the LED chaser move back and forth - what do I need to change / add?  // Create array for LED pins byte ledPin[] = {8, 9, 10, 11, 12, 13}; int ledDelay; // delay between changes int direction = 1; int currentLED = 0; unsigned long changeTime; int potPin = 2;    // select the input pin for the potentiometer void setup() {   // set all pins to output   for (int x=0; x     pinMode(ledPin[x], OUTPUT); }     changeTime = millis(); } void loop() { // read the value from the pot ledDelay = analogRead(potPin);      // if it has been ledDelay ms since last change   if ((millis() - changeTime) > ledDelay) {     changeLED();     changeTime = millis();   } } void changeLED() {   // turn off all LED's   for (int x=0; x     digitalWrite(ledPin[x], LOW);   }   // turn on the current LED   digitalWrite(ledPin[currentLED], HIGH);   // increment by the direction value   currentLED += direction;   // change direction if we reach the end   if (currentLED == 5) {direction = -1;}   if (currentLED == 0) {direction = 1;} }

Asked by furnacehead 8 years ago


Arduino calculation error... Or operator error?

Below is a tachometer program that was patched together... Using a hall effect for the sensor. For some odd reason when the calculation is done for interrupts per second something goes wrong... When set at 30*1000 I get what seems to be a good RPM number... But when changed to 60*1000 the RPM jumps to 20-50k... Not sure what is going on... If someone would be so kind and have a look at the program and see if I am missing something... It would be appreciated.. int ledPin = 11; volatile byte rpmcount; unsigned int rpm; unsigned long timeold; #include LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7); void rpm_fun() {   rpmcount++; } void setup() {   lcd.begin(16, 2);   attachInterrupt(0, rpm_fun, FALLING);   pinMode(ledPin, OUTPUT);   rpmcount = 0;   rpm = 0;   timeold = 0; } void loop() {   delay(1000);   detachInterrupt(0);   rpm = 60 * 1000 / (millis() - timeold) * rpmcount;   timeold = millis();   rpmcount = 0;   lcd.clear();   lcd.print("Rotary Head RPM:");   lcd.setCursor(6, 1);   lcd.print(rpm);   if (rpm > 100)   {     digitalWrite(ledPin, HIGH);   }   else   {     digitalWrite (ledPin, LOW);   }   attachInterrupt(0, rpm_fun, FALLING);

Asked by fracture123 2 years ago


Arduino code sensor and moving wheel with encoder help with code

I'm still new at this but I been trying to figure this out for awhile now and can't seem to get it to work how I want it to. If  anyone can help or give advice on how I can go about doing this would be great. Thanks #include       const int BUTTON = A5;              // push button for starting       const int RIGHT_SERVO = 10;       const int LEFT_SERVO = 11;       Servo leftServo;       Servo rightServo;       int valButton;       int turnOnOff=0;             // the val of the pull up button is set to zero to start with             volatile int Lindex = 0;             void setup()       {         attachInterrupt(0,ltEncoderInterrupt,RISING);         Serial.begin(9600);         leftServo.attach(LEFT_SERVO);         rightServo.attach(RIGHT_SERVO);         leftServo.write(1500);         rightServo.write(1500);       }       void loop()       { Serial.println(turnOnOff);         turnOnOff=readButton();      // calls the function readButton to see if the button has been pressed(1)         int sensorValue = analogRead(A0);         if(turnOnOff==1)         {           if (sensorValue           {           delay(500);                  leftServo.write(1700);           rightServo.write(1300);                              }           else if (sensorValue >300)           {                     // It stop when it detect a black electrical tape.           leftServo.write(1500);           rightServo.write(1500);            Lindex = 0;           delay(500);             }                                // can't seem to get it to work it keep moving backward           {                     }           leftServo.write(1300);           rightServo.write(1700);                     while (Lindex           {                     }           turnOnOff = 0;           Lindex = 0;         }                 else         {           leftServo.write(1500);           rightServo.write(1500);                  }        }             /************* Subroutine for reading the button switch********************/       int readButton()       {         unsigned long contactTime;               //local variable; contactTime declared         valButton=analogRead(BUTTON);            // Read the pushbutton on an analog pin         if(valButton>512)                        // Since 5V will produce a value of 1023,          return turnOnOff;                       // return the value of turnOnOff without changing it         contactTime=millis();                    // set contactTime = to the millis() clock value         while(valButton         {                   // while the pushbutton is pushed           valButton=analogRead(BUTTON);           // read the button value again and keep reading until valButton is less than 512         }         if(millis()-contactTime          return turnOnOff;                       // return the turnOnOff value unchanged          return(1-turnOnOff);                      // if the button is held longer than 20 ms then change the turnOnOff                                                  // to the opposite value to what it was       }       /////////////////////////////////////////////////////////////////////////////             /******************ISR for wheel count**************************************/       void ltEncoderInterrupt()       {                Lindex++;       }       ///////////////////////////////////////////////////////////////////////////////

Posted by al2tistic 1 year ago


Dual H-Bridge Motor Driver - L298N not given enough power to motors

Hi there, am very new to the electronics community, I recent bought my first arduino. I wanted to build me own RC car, so I bought Dual H-Bridge Motor Driver L298N Module from ebay (http://www.ebay.co.uk/itm/Dual-H-Bridge-Motor-Driver-L298N-Module-For-Arduino-PIC-DC-Stepper-L298-Board-/251291436187?pt=UK_BOI_Industrial_Automation_Control_ET&hash=item3a8223049b) I think I have connected everything correctly but somehow the 2 dc motors connected to the motor driver don't seem to move, I have tried a 9v battery to power the motor shield but doesn't seem to do anything. I  used this diagram do the connection to the arduino http://i.imgur.com/JCBcSfL.jpg The arduino itself has it own 9v battery powering it. I have checked both motors and they work fine. when i switch on the rc car the led on the motor shield blinks but the motors just don't move. I used a digital multimeter to measure the voltage going into the motor. it goes upto 0.36v  then drops. does that mean there isn't enough voltage going into the motors? and how much voltage do you recommend to get it working? Images of the rc car http://imgur.com/K7zff2G http://imgur.com/9kaWQBy http://imgur.com/OEidI90 http://imgur.com/lnpjvNM http://imgur.com/izgDEtY http://imgur.com/tqhdQVv The code am running on the arduino //motor A int dir1PinA = 2; int dir2PinA = 3; int speedPinA = 9; //motor B int dir1PinB = 4; int dir2PinB = 5; int speedPinB = 10; unsigned long time; int speed; int dir; void setup(){   pinMode(dir1PinA,OUTPUT); pinMode(dir2PinA,OUTPUT); pinMode(speedPinA,OUTPUT); pinMode(dir1PinB,OUTPUT); pinMode(dir2PinB,OUTPUT); pinMode(speedPinB,OUTPUT); time = millis(); speed = 0; dir = 1; } void loop(){     analogWrite(speedPinA, speed);   analogWrite(speedPinB,255 - speed);     //set direction   if(1 == dir){     digitalWrite(dir1PinA, LOW);     digitalWrite(dir2PinA, HIGH);     digitalWrite(dir1PinB, HIGH);     digitalWrite(dir2PinB, LOW);   }else{     digitalWrite(dir1PinA, HIGH);     digitalWrite(dir2PinA, LOW);     digitalWrite(dir1PinB, LOW);     digitalWrite(dir2PinB, HIGH);   }     if(millis() - time > 5000){     time = millis();     speed += 20;     if(speed > 255){       speed = 0;     }     if(1 == dir){       dir = 0;     }else{       dir = 1;     }   }   }

Posted by Raphael1 4 years ago



arduino moisture sensor values

Hey guys i have made this program but im a little concerned because my values from my moisture sensor jump around quite a bit and if the sensor values are wrong for to long it may keep the heaters on for too long which can cause a fire i did use an if statment instead of while im just trying differnt ways here is my code... #include LiquidCrystal lcd(7,8,9,10,11,12); int sen = 5; int hOn = 6; int mot = 3; void setup() {   Serial.begin(9600);   lcd.begin(16,2);   pinMode(hOn, OUTPUT);   pinMode(sen, OUTPUT);   pinMode(mot, OUTPUT);   lcd.print("Start Up");   lcd.setCursor(0,1);   lcd.print("Complete"); } void loop() {   digitalWrite(hOn, HIGH);   digitalWrite(mot, HIGH);   digitalWrite(sen, HIGH);   analogRead(4);   delay(5000);   digitalWrite(sen, LOW);     int val = analogRead(4);   int good = 451;   int bad = 450;   lcd.clear();    while(val   {     lcd.clear();     lcd.setCursor(0,0);     lcd.print("Heaters On.");     lcd.setCursor(0,1);     lcd.print(val);     lcd.setCursor(4,1);     lcd.print("UpT:");     lcd.print(millis()/1000);     digitalWrite(hOn, LOW);     Serial.print (val);     Serial.println (" Moisture Level Is Bad ");     digitalWrite(mot, LOW);     delay(120000);     digitalWrite(mot, HIGH);     delay(300000);     digitalWrite(mot, LOW);     delay(120000);     digitalWrite(mot, HIGH);     delay(60000);   }   while(val >= good)   {     lcd.clear();     lcd.setCursor(0,0);     lcd.print("Heaters Off.");     lcd.setCursor(0,1);     lcd.print(val);     lcd.setCursor(4,1);     lcd.print("UpT:");     lcd.print(millis()/1000);     Serial.print (val);     Serial.println (" All Is Good ");     digitalWrite(hOn, HIGH);     digitalWrite(mot, LOW);     delay(120000);     digitalWrite(mot, HIGH);     delay(300000);     digitalWrite(mot, LOW);     delay(120000);     digitalWrite(mot, HIGH);     delay(60000);   } }

Posted by yaene21 4 years ago


CNC protype service. Laser cutting and 5 axis milling.

Hello. I offer cnc prototype service.Serial work is also possible. Worldwide shipping to any country. Material: any ferrous and nonferrous metals,plastics and wood. Number of axes cnc milling center: 5 axis Laser cutting any ferrous and nonferrous metals, plastics and wood. (Maximum thickness  20 mm for steel.) Wire EDM cnc machine processing. Finishing: painting, polishing, electroplating and other. Detail size : any Minimal order: 1 piece. Format for drawing: Any digital format. Better SolidWorks or AutoCad. Shipping: Worldwide (EMS,DHL or other postal service) Payment: any Please contact: cnc5axiscut@gmail.com

Posted by cnc5axiscut 4 years ago


Binary Arduino Alarm Clock HELP!

I am currently working on THIS INSTRUCTABLE:https://www.instructables.com/id/Arduino-Binary-Alarm-Clock/ I have had to modify the libraries to work with IDE 1.0 and newer because this was written 5 years ago. I'm using a push button momentary switch instead of the capacitive sensor for the snooze button. I've got everything working except for the Alarm/snooze. For some reason, the speaker is constantly beeping a high, then low tone, as though the snooze button is being held down, even when I completely disconnect the snooze button from the clock. Can anyone give me any ideas how to fix this problem? Here is my modified button code: void update_buttons_state() {   hour_button_state    = digitalRead(hour_button_pin);   minute_button_state  = digitalRead(minute_button_pin);   setTime_button_state = digitalRead(setTime_button_pin);   setAlarm_button_state = digitalRead(setAlarm_button_pin);   snooze_button_state = digitalRead(snooze_button);     } // "INTERNAL" VARIABLES FOR BUTTONS FUNCTION: boolean first_time_hour = true;   // these are used to make sure that the hours boolean first_time_minute = true; // and minutes only is increased once every keypress. unsigned long snooze_button_timer; // used to keep track of how long the snooze button has                                    // been held down. when the button has been held down                                    // a certain amount of time, the alarm will be turned                                    // of completely. void buttons() {   // LOW == button pressed   // HIGH == button released   // (this is because pullup resistors is used)     // Decide if we should set time or alarm:   // (this also makes the display show the alarm time)   if(setAlarm_button_state==LOW) // LOW = Set time   {     hours_p = &alarm_hours;     minutes_p = &alarm_minutes;   } else if(setTime_button_state==LOW) // LOW = Set Alarm   {     hours_p = &hours;     minutes_p = &minutes;   }   // If hour button is pressed, increase hours:   if(hour_button_state==LOW && first_time_hour) // only increase the hours once   {                                             // every button press.     if(*hours_p       (*hours_p)++;     else       *hours_p = 0;         first_time_hour = false;          }   else if(hour_button_state==HIGH)   {     first_time_hour = true; // reset when button is released,   }                         // so that the next press will be registerd.     // If minute button is pressed, increase minutes:   if(minute_button_state==LOW && first_time_minute) // only increase the minutes   {                                                 // once every button press.     if(*minutes_p       (*minutes_p)++;     else       *minutes_p = 0;           first_time_minute = false;   }   else if(minute_button_state==HIGH)   {     first_time_minute = true; // reset when button is released,   }                           // so that the next press will be registerd.     if(snooze_button_state==LOW)   {     if(signal_on)     {       // set the time when the alarm signal will start again,       // this will give 10 minutes snooze:       if(minutes       {         snooze_off_minutes = minutes+10;         snooze_off_hours = hours;       }       else       {         snooze_off_minutes = minutes - 50;         snooze_off_hours = hours + 1;       }       snooze_on = true;       signal_on = false;     }     // if the snooze button has been held down for more than 3 seconds turn off/on the alarm     if((millis() - snooze_button_timer) > 5000)     {       if(alarm_on) // if on, turn off       {         signal_on = false;         alarm_on = false;         snooze_on = false;         // play tone so the user know the alarm turned off:         tone_maker.play(NOTE_A3, 100);       }       else if(alarm_on==false) // if off, turn on       {         alarm_on = true;         // play tone so the user know the alarm turned off:         tone_maker.play(NOTE_A7, 100);       }       //reset the snooze button timer       snooze_button_timer=millis();     }       }   else   {     //reset the snooze button timer     snooze_button_timer=millis();   } }

Posted by holidayv 4 years ago


Untouchable Android Device?

Hey,  So i am in a turkish school and the Turkish National Education Ministry (Milli eğitim bakanlığı) gave half the schools in turkey educational tablets for free. But the goverment cant just not touch anything.... These tablets (writing this post with one of them now) are on what i am declaring ANDROID LOCKDOWN. (actually sounds catchy) They have deleted play store, disabled the ability to install apks on them, made the bluetooth as expensive as a paperwieght.. And connection with a computer?? Trust me dont even go there. So the question is *İs there any possible way to install apks WİTHOUT rooting??* Help me please The tablets are General mobile e tab 5 Android 4.4 kitkat octa core 1.7 ghz 2 gb ram 32 gig memory. İt pains me to see them like this..

Posted by Doc Penguin 2 years ago


I want to replace or alter the crystal oscillator on my UNO as part of a electronics suicide workshop

I want to replace or alter the crystal oscillator on my UNO as part of a electronics suicide workshop, look at it as circuit bending i guess. I want to know approximately what could happen- is it going to run a simple standalone program, I think serial and flashing will not be possible  post-lobotomy but i can load the program before i bend it. The processing speed will be the same but any Millis() or clock functions will be way out? Will it just trip over its own feet and crash? I have heard interesting things about using your finger over the solder spots to make it run at 60Hz etc...Anyway i will experiment but i wanted to get some predictions from people who know this stuff at a more fundamental level! Cheers!!

Asked by oliverkellow 5 years ago


I need help for my electric imp/arduino project....

Hey, I have been working on a project centered around what chris nafis has already done with the grove dust sensor. So far, I have managed to get the dust sensor hooked up to an arduino and I have been getting it to display data, but that's about it. My next step was to get an elecrric im on sparkfun's imp shield to read serial data from the arduino in the form of numbers and then output it to COSM. However, for some reason, this does not seem to want to work on the leval of the imp. I followed most of jimb0's instructions on sparkfun for imps and arduino, but this does not seem to work. I have an arduino leonardo outputting serial data with serial1 at 19200 through pins 1 and 0 to the shield, which it then supposed to connect an imp running a program to patch this to a cosm node. I know nothing about squirrel, just using this code to do things: // Transmit data between UART and Input/OutputPorts on the impee // by: Jim Lindblom //     SparkFun Electronics // date: September 26, 2012 // license: BeerWare //          Please use, reuse, and modify this code as you need. //          We hope it saves you some time, or helps you learn something! //          If you find it handy, and we meet some day, you can buy me a beer or iced tea in return. local rxLEDToggle = 1;  // These variables keep track of rx/tx LED toggling status local txLEDToggle = 1; // impeeIn will override the InputPort class. // Whenever data is received to the impee, we'll jump into the set(c) function defined within class impeeIn extends InputPort {     name = "UART Out";     type = "number";         // This function takes whatever character was sent to the impee     // and sends it out over the UART5/7. We'll also toggle the txLed     function set(c)     {         hardware.uart57.write(c);         toggleRxLED();     } } local impeeInput = impeeIn();  // assign impeeIn class to the impeeInput local impeeOutput = OutputPort("UART In", "number");  // set impeeOutput as a string function initUart() {     hardware.configure(UART_57);    // Using UART on pins 5 and 7     hardware.uart57.configure(19200, 8, PARITY_NONE, 1, NO_CTSRTS); // 19200 baud worked well, no parity, 1 stop bit, 8 data bits } function initLEDs() {     // LEDs are on pins 8 and 9 on the imp Shield     // They're both active low, so writing the pin a 1 will turn the LED off     hardware.pin8.configure(DIGITAL_OUT_OD_PULLUP);     hardware.pin9.configure(DIGITAL_OUT_OD_PULLUP);     hardware.pin8.write(1);     hardware.pin9.write(1); } // This function turns an LED on/off quickly on pin 9. // It first turns the LED on, then calls itself again in 50ms to turn the LED off function toggleTxLED() {     txLEDToggle = txLEDToggle?0:1;    // toggle the txLEDtoggle variable     if (!txLEDToggle)     {         imp.wakeup(0.05, toggleTxLED.bindenv(this)); // if we're turning the LED on, set a timer to call this function again (to turn the LED off)     }     hardware.pin9.write(txLEDToggle);  // TX LED is on pin 8 (active-low) } // This function turns an LED on/off quickly on pin 8. // It first turns the LED on, then calls itself again in 50ms to turn the LED off function toggleRxLED() {     rxLEDToggle = rxLEDToggle?0:1;    // toggle the rxLEDtoggle variable     if (!rxLEDToggle)     {         imp.wakeup(0.05, toggleRxLED.bindenv(this)); // if we're turning the LED on, set a timer to call this function again (to turn the LED off)     }     hardware.pin8.write(rxLEDToggle);   // RX LED is on pin 8 (active-low) } // This is our UART polling function. We'll call it once at the beginning of the program, // then it calls itself every 10us. If there is data in the UART57 buffer, this will read // as much of it as it can, and send it out of the impee's outputPort. function pollUart() {     imp.wakeup(0.00001, pollUart.bindenv(this));    // schedule the next poll in 10us         local byte = hardware.uart57.read();    // read the UART buffer     // This will return -1 if there is no data to be read.     while (byte != -1)  // otherwise, we keep reading until there is no data to be read.     {         //  server.log(format("%c", byte)); // send the character out to the server log. Optional, great for debugging         impeeOutput.set(byte);  // send the valid character out the impee's outputPort         byte = hardware.uart57.read();  // read from the UART buffer again (not sure if it's a valid character yet)         toggleTxLED();  // Toggle the TX LED     } } // This is where our program actually starts! Previous stuff was all function and variable declaration. // This'll configure our impee. It's name is "UartCrossAir", and it has both an input and output to be connected: imp.configure("UartCrossAir", [impeeInput], [impeeOutput]); initUart(); // Initialize the UART, called just once initLEDs(); // Initialize the LEDs, called just once pollUart(); // start the UART polling, this function continues to call itself // From here, two main functions are at play: //      1. We'll be calling pollUart every 10us. If data is sent from the UART, we'll send out out of the impee. //      2. If data is sent into the impee, we'll jump into the set function in the InputPort. // // The end It's not mine, but I modified it slightly t work with numbers instead of strings. I an then using this arduino code on a leonardo: ;int pin = 10; unsigned long final; unsigned long duration; unsigned long starttime; unsigned long sampletime_ms = 30000; unsigned long lowpulseoccupancy = 0; float ratio = 0; float concentration = 0; void setup() {   Serial1.begin(19200);    while (!Serial) {     ;    }   pinMode(10,INPUT);   starttime = millis(); } void loop() {   duration = pulseIn(pin, LOW);   lowpulseoccupancy = lowpulseoccupancy+duration;   if ((millis()-starttime) > sampletime_ms)   {     ratio = lowpulseoccupancy/(sampletime_ms*10.0);  // Integer percentage 0=>100     concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // using spec sheet curve     final = concentration*35     ;Serial.println(concentration);     lowpulseoccupancy = 0;     starttime = millis();   } };int pin = 10; unsigned long final; unsigned long duration; unsigned long starttime; unsigned long sampletime_ms = 30000; unsigned long lowpulseoccupancy = 0; float ratio = 0; float concentration = 0; void setup() {   Serial1.begin(19200);    while (!Serial) {     ;    }   pinMode(10,INPUT);   starttime = millis(); } void loop() {   duration = pulseIn(pin, LOW);   lowpulseoccupancy = lowpulseoccupancy+duration;   if ((millis()-starttime) > sampletime_ms)   {     ratio = lowpulseoccupancy/(sampletime_ms*10.0);  // Integer percentage 0=>100     concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // using spec sheet curve     final = concentration*35     ;Serial.println(concentration);     lowpulseoccupancy = 0;     starttime = millis();   } } I would really like some help, as this is my science fair project and I am the only person that I know that knows about Imp, and sadly we don't have any hackerspaces around where I live in alaska.

Posted by qquuiinn 5 years ago


Data updating on thingspeak (cloude) only once

 I am trying to update Thingspeak using Edison. It updates thingspeak but only at once. If I have to update again I have to run the code again. #include #include // ThingSpeak Settings char thingSpeakAddress[] = "api.thingspeak.com";  //TS String writeAPIKey = "**************";    //TS const int updateThingSpeakInterval = 20 * 1000;      // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval) char ssid[] = "*********";     //  your network SSID (name) char pass[] = "*********";  // your network password int status = WL_IDLE_STATUS;     // the Wifi radio's status // initialize the library instance: WiFiClient client; String stringVal = ""; // Variable Setup long lastConnectionTime = 0; boolean lastConnected = false; int failedCounter = 0; int a; float tempC; int B=3975; float resistance; void setup() {   //Initialize serial and wait for port to open:   Serial.begin(115200);    while (!Serial) {     } //  check for the presence of the shield: // if (WiFi.status() == WL_NO_SHIELD) {   //   Serial.println("WiFi shield not present");     // don't continue:     //while(true); //} // attempt to connect to Wifi network:   while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to WPA SSID: ");     Serial.println(ssid);     // Connect to WPA/WPA2 network:       status = WiFi.begin(ssid, pass);     // wait 10 seconds for connection:     delay(10000);      }     // you're connected now, so print out the data:   Serial.println("You're connected to the network");   // printCurrentNet();   // printWifiData(); }   void loop() { a = analogRead(0); resistance=(float)(1023-a)*10000/a; tempC=1/(log(resistance/10000)/B+1/298.15)-273.15; // converts temp  to string      stringVal += String(int(tempC))+ "."+String(getDecimal(tempC)); //char buf[16]; //String strTemp = floatToString(16 , cel , 5); //Serial.println(strTemp); // Print Update Response to Serial Monitor   while (client.available())   {     char c = client.read();     Serial.print(c);   }   // Disconnect from ThingSpeak   if (!client.connected() && lastConnected )   {     Serial.println("...disconnected");     Serial.println();        client.stop();     }   // Update ThingSpeak   if(client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))   {     updateThingSpeak("field1="+stringVal);      Serial.print( stringVal);          Serial.println("C");      delay(1000);      Serial.println();         }   lastConnected = client.connected(); } //function to extract decimal part of float long getDecimal(float val) { int intPart = int(val); long decPart = 100*(val-intPart); //I am multiplying by 100 assuming that the foat values will have a maximum of 3 decimal places                                    //Change to match the number of decimal places you need if(decPart>0)return(decPart);           //return the decimal part of float number if it is available else if(decPart else if(decPart=0)return(00);           //return 0 if decimal part of float number is not available } void updateThingSpeak(String  stringVal) {   if (client.connect(thingSpeakAddress, 80))   {            client.print("POST /update HTTP/1.1\n");     client.print("Host: api.thingspeak.com\n");     client.print("Connection: close\n");     client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");     client.print("Content-Type: application/x-www-form-urlencoded\n");     client.print("Content-Length: ");     client.print( stringVal.length());     client.print("\n\n");     client.print( stringVal);        lastConnectionTime = millis();        if (client.connected())     {       Serial.println("Connecting to ThingSpeak...");       Serial.println();            failedCounter = 0;     }     else     {       failedCounter++;       Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");        Serial.println();     }      }   else   {     failedCounter++;        Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");      Serial.println();        lastConnectionTime = millis();   } } after running this code I get this(image attached)

Asked by ANINDYAB5 2 years ago


how can i convert one 24v dc output into two 12v dc outputs? Answered

I am making a psu for my cctv system. i have a fairly new psu from a fire alarm panel which has battery terminals so it can still supply power even if the mains is out. my cameras can run on about 9-24v but my DVR needs exactly 12v 5a. The most logical thing to do i guess is convert the 24v output from the psu into 12v that i can then fuse off to go to different cameras and the dvr. trouble is i don't know how to. i thought of a voltage divider but it turns out they are bad if using more than a couple of Milli amps. would a voltage regulator do it? i'm abit stuck here so any help at all would be brilliant. thanks - luke

Asked by ljarrald 7 years ago


Arduino Countdown timer code problem?

I was using the Crazy Countdown Timer as a base for yet another project and I seem to have hit a dead end with the code. I have taken an input (A3) that used to speed up the countdown time and tried to change the function to add five minutes to the remaining time. I have tried various methods and the results have not been the best. From setting the total time to 5 minutes to it's current state of not doing anything at all, I have limited knowledge of the coding and would appreciate some help if you would be so kind. Thanks in advance :-) The code so far is /*   Arduino clock on a standard 4-digit clock display   Uses a Liteon LTC-617D1G clock display Connections: LTC - Arduino 1 - nc 2 - nc 3 - nc 4 - d7 5 - d3 6 - d2 7 - d11 8 - d10 9 - d4 10 - gnd 22 - d9 23 - d5 24 - d6 25 - A0  // because d13 already has a built-in LED getting in the way 26 - d8 27 - d12 28 - A1 29 - gnd button: 5v - button - A5 - 10k resistor - gnd crazy wires: 5v - red jumper wire - A4 - 10k resistor - gnd 5v - blue jumper wire - A3 - 10k resistor - gnd 5v - yellow jumper wire - A2 - 10k resistor - gnd Action: pin D13 is already hooked up to an LED */ #define DIGIT1 2 #define DIGIT2 3 #define DIGIT3 5 #define DIGIT4 6 #define SEGMENTA 7 #define SEGMENTB 8 #define SEGMENTC 9 #define SEGMENTD 10 #define SEGMENTE 11 #define SEGMENTF 12 #define SEGMENTG A0 #define COLON 4 #define AMPM A1 #define BUTTON A5 #define STOPWIRE  A2 #define PLUSFIVE A3 #define ZEROWIRE  A4 #define ACTION 13 #define ON  HIGH #define OFF LOW #define DELAYTIME 50 int FiveState;             // the current FiveRead from the input pin int lastFiveState = LOW;   // the previous FiveRead from the input pin long FivelastDebounceTime = 0;  // the last time the output pin was toggled long FiveDebounceDelay = 50;    // the debounce time; increase if the output flickers unsigned short hours, minutes, seconds; unsigned long lastTime; // keeps track of when the previous second happened int buttonState;             // the current reading from the button pin int lastButtonState = LOW;   // the previous reading from the button pin unsigned long button_down_start = 0; // how long the button was held down unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled unsigned long debounceDelay = 50;    // the debounce time byte flash;    // indicates when display should be flashing byte flash_on; // indicates that display is current in "on" part of a flash byte timer_stopped; // indicates that the timer is not counting down #define ONE_SECOND 1000 #define FLASH_TIME 100 // 10 times as fast unsigned long time_chunk; void setup() {   // Serial.begin(9600);     // initialize all the required pins as output.   pinMode(DIGIT1, OUTPUT);   pinMode(DIGIT2, OUTPUT);   pinMode(DIGIT3, OUTPUT);   pinMode(DIGIT4, OUTPUT);   pinMode(SEGMENTA, OUTPUT);   pinMode(SEGMENTB, OUTPUT);   pinMode(SEGMENTC, OUTPUT);   pinMode(SEGMENTD, OUTPUT);   pinMode(SEGMENTE, OUTPUT);   pinMode(SEGMENTF, OUTPUT);   pinMode(SEGMENTG, OUTPUT);   pinMode(COLON, OUTPUT);   pinMode(AMPM, OUTPUT);     // button is input   pinMode(BUTTON, INPUT);     // wires are inputs   pinMode(STOPWIRE, INPUT);   pinMode(PLUSFIVE, INPUT);   pinMode(ZEROWIRE, INPUT);     // the action is output   pinMode(ACTION, OUTPUT);     // set the initial time   hours = 0;   minutes = 25;   seconds = 00;   flash = 0;   flash_on = 0;   timer_stopped = 0;   time_chunk = ONE_SECOND;   lastTime = millis(); } void loop() {     // Keep showing the display while waiting for timer to expire    while (millis() - lastTime             if (!flash || flash_on) {             if (hours > 0) {         clock_show_time(hours, minutes);             // and blink the colon every even second         if (seconds % 2 == 0) {           clock_show_colon();         }       }       else {         clock_show_time(minutes, seconds);         clock_show_colon(); // show a steady colon       }           }         // check the crazy wires         if (digitalRead(STOPWIRE) == HIGH) {  // stops time       timer_stopped = true;     }     else {       timer_stopped = false;     }     /*     if (digitalRead(SPEEDWIRE) == HIGH) { // speeds up the time and flashes display       flash = 1;       time_chunk = FLASH_TIME;     }     */          // read the state of the switch into a local variable:   int FiveRead = digitalRead(PLUSFIVE);   // check to see if you just pressed the button   // (i.e. the input went from LOW to HIGH),  and you've waited   // long enough since the last press to ignore any noise:    // If the switch changed, due to noise or pressing:   if (FiveRead != lastFiveState) {     // reset the debouncing timer     FivelastDebounceTime = millis();   }     if ((millis() - FivelastDebounceTime) > FiveDebounceDelay) {     // whatever the FiveRead is at, it's been there for longer     // than the debounce delay, so take it as the actual current state:     // if the button state has changed:     if (FiveRead != FiveState) {       FiveState = FiveRead;       // only toggle the LED if the new button state is HIGH       if (FiveState == HIGH) {         minutes += 5;       if (minutes > 59) minutes = 59;           }                     // button has been pressed           incrementTime();         }     // save the FiveRead.  Next time through the loop,   // it'll be the lastFiveState:   lastFiveState = FiveRead;    }        if (digitalRead(ZEROWIRE) == HIGH) {  // sets time to zero       hours = 0;       minutes = 0;       seconds = 0;       time_chunk = FLASH_TIME;     }         // button presses increase minutes     int reading = digitalRead(BUTTON);      // If the switch changed, due to noise or pressing:     if (reading != lastButtonState) {       // reset the debouncing timer       lastDebounceTime = millis();     }         if ((millis() - lastDebounceTime) > debounceDelay) {       // whatever the reading is at, it's been there for longer       // than the debounce delay, so take it as the actual current state:             if (buttonState != reading) {         button_down_start = millis(); // record the start of the current button state       }             buttonState = reading;             // buttonState is now either on or off       if (buttonState == HIGH) {         flash = 0; // takes it out of panic mode         digitalWrite(ACTION, OFF); // turns the action OFF.         time_chunk = ONE_SECOND; // reset to regular time counting.                   // slow it down by only doing this every 10th millisecond         if ((millis() % 10) == 0) {           // if the button was held down more than 5 seconds, make it go faster           if ((millis() - button_down_start) > 5000) {             seconds += 10;             if (seconds > 59) seconds = 59;           }                     // button has been pressed           incrementTime();         }       }     }     lastButtonState = reading;   }   lastTime += time_chunk;     if (!timer_stopped) {     decrementTime();   }     if (flash) {     flash_on = !flash_on;   } } // // a call to decrementTime decreases time by one second. // void decrementTime() {       if (seconds == 0) {               if (minutes == 0) {                   if (hours == 0) {                      // time is at 00:00, flash the zeroes             flash = 1;             time_chunk = FLASH_TIME;                               // and do the action             do_action();           }           else {             minutes = 59;             hours--;           }         }         else {           seconds = 59;           minutes--;         }               }       else {         seconds--;        } } // // a call to incrementTime increases time by one second. // void incrementTime() {     if (seconds == 59) {     seconds = 0;         if (minutes == 59) {       minutes = 0;             if (hours == 12) {                  hours = 1;       }       else {         hours++;       }     }     else {       minutes++;     }   }   else {     seconds++;    } } // // clock_show_time - displays the given time on the clock display //   Note that instead of hr/min the user can also send min/sec //   Maximum hr is 99, Maximum min is 59, and minimum is 0 for both (it's unsigned, heh). // void clock_show_time(unsigned short hours, unsigned short minutes) {   unsigned short i;   unsigned short delaytime;   unsigned short num_leds[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };   unsigned short digit[4];   unsigned short hide_leading_hours_digit;       // convert minutes and seconds into the individual digits   // check the boundaries   if (hours > 99) hours = 99;   if (minutes > 59) minutes = 59;     // convert hr   if (hours 0) {     hide_leading_hours_digit = 1;   }   else {     hide_leading_hours_digit = 0;   }     digit[0] = hours / 10;   digit[1] = hours % 10; // remainder   digit[2] = minutes / 10;   digit[3] = minutes % 10; // remainder    for (i = hide_leading_hours_digit; i     clock_all_off();     clock_show_digit(i, digit[i]);     // fewer leds = brighter display, so delay depends on number of leds lit.     delaytime = num_leds[digit[i]] * DELAYTIME;       delayMicroseconds(delaytime);   }       clock_all_off(); } // // clock_all_off - turns off all the LEDs on the clock to give a blank display // void clock_all_off(void) {     // digits must be ON for any LEDs to be on   digitalWrite(DIGIT1, OFF);   digitalWrite(DIGIT2, OFF);   digitalWrite(DIGIT3, OFF);   digitalWrite(DIGIT4, OFF);     // segments must be OFF for any LEDs to be on   digitalWrite(SEGMENTA, ON);   digitalWrite(SEGMENTB, ON);   digitalWrite(SEGMENTC, ON);   digitalWrite(SEGMENTD, ON);   digitalWrite(SEGMENTE, ON);   digitalWrite(SEGMENTF, ON);   digitalWrite(SEGMENTG, ON);     // turn off colon and alarm too   digitalWrite(COLON, OFF);   digitalWrite(AMPM, OFF); } // // clock_show_digit - turns on the LEDs for the digit in the given position //      position can be from 0 through 3: 0 and 1 being the hour, 2 and 3 being the seconds //      value can be from 0 through 9, ie, a valid single digit. // //      (if value is out of range, it displays a 9. if digit is out of range display remains blank) // void clock_show_digit(unsigned short position, unsigned short value) {   byte a;   byte b;   byte c;   byte d;   byte e;   byte f;   byte g;   switch (position) {     case 0:       digitalWrite(DIGIT1, ON);       break;     case 1:       digitalWrite(DIGIT2, ON);       break;     case 2:       digitalWrite(DIGIT3, ON);       break;     case 3:       digitalWrite(DIGIT4, ON);       break;   }   a = !(value == 1 || value == 4);   b = !(value == 5 || value == 6);   c = !(value == 2);   d = !(value == 1 || value == 4 || value == 7);   e =  (value == 0 || value == 2 || value == 6 || value == 8);   f = !(value == 1 || value == 2 || value == 3 || value == 7);   g = !(value == 0 || value == 1 || value == 7);     if (a) digitalWrite(SEGMENTA, OFF);   if (b) digitalWrite(SEGMENTB, OFF);   if (c) digitalWrite(SEGMENTC, OFF);   if (d) digitalWrite(SEGMENTD, OFF);   if (e) digitalWrite(SEGMENTE, OFF);   if (f) digitalWrite(SEGMENTF, OFF);   if (g) digitalWrite(SEGMENTG, OFF); } // // clock_show_colon - shows the colon that separates minutes from seconds // void clock_show_colon(void) {   unsigned short delaytime;   digitalWrite(COLON, ON);                                // 2 leds = 2 delays needed   delaytime = DELAYTIME * 2;  // must use variable to have similar delay to rest of clock   delayMicroseconds(delaytime);   //   because use of variable slows it down slightly.   digitalWrite(COLON, OFF); } // // clock_show_alarm - shows the ampm dot (bottom right of clock display) // void clock_show_ampm(void) {   unsigned short delaytime;   digitalWrite(AMPM, ON);                         delaytime = DELAYTIME;  // must use variable to have similar delay to rest of clock   delayMicroseconds(delaytime);   //   because use of variable slows it down slightly.   digitalWrite(AMPM, OFF); } // // do_action - this function gets called when the timer completes. // static void do_action(void) {   // the exciting action here is just to turn on a LED   digitalWrite(ACTION, ON);   Serial.println("ACTION!"); }

Asked by Djandco 4 years ago


Analog to Digital not correct for set trigger value Answered

I am trying to remedy false hits. I have a remote operated light that uses a 38MHz 3 leg IR sensor and a  TV remote for on/off, but it can have false hits, IE light may come on when ever.  I decided it needed a  long button press or in this case a long IR input. Because the IR sensor doesn't go from 0 to 5 volts i have set a threshold of 600. IR voltage values are, low is 1.8v and high is 3.6v. So i decided 2.75V could be a reasonable threshold value. that ROUGHLY translated to 600 if going from 0 to 1023. This sketch works good for a button but trying to use the IR sensor does not. I have tried to map the sensor and put a trigger value but something is a miss with my work. Any suggestions?  /* *  Press & Hold Switch LED program */ // Parameters int HOLD_DELAY = 500;    // Sets the hold delay of switch for LED state change int ledPin     = 9;      // LED is connected to pin x int switchPin  = A0;      // Switch is connected to pin x int val = 0; int statePin = LOW; int THRESHOLD = 600; // In-Program Variables unsigned long start_hold; boolean allow = false; int sw_state; int sw_laststate = LOW; int led_state = LOW; // Setup void setup() {   Serial.begin(9600);   pinMode(ledPin, OUTPUT);      // Set the LED pin as output   pinMode(switchPin, INPUT);    // Set the switch pin as input } // Loop void loop(){   int val = analogRead(switchPin);    val = map(val, 0, 1023, 0, 255);    if (val >= THRESHOLD) {     statePin = !statePin;         digitalWrite(ledPin, statePin);     Serial.print(val);     Serial.println("Triggered!");     delay(80);   sw_state = digitalRead(switchPin);             // read input value     if (sw_state == HIGH && sw_laststate == LOW){  // for button pressing     start_hold = millis();                       // mark the time     allow = true;                                // allow LED state changes   }        if (allow == true && sw_state == HIGH && sw_laststate == HIGH){  // if button remains pressed       if ((millis() - start_hold) >= HOLD_DELAY){                   // for longer than x/1000 sec(s)          led_state = !led_state;                                   // change state of LED          allow = false;                                            // prevent multiple state changes       }   }   sw_laststate = sw_state;     digitalWrite(ledPin, led_state);    } }  

Asked by WWC 5 years ago


Hello guys, I'm doing a alarm system. But my push button doesn't stop the piezo and led when I pressed it.

This is my code. const int buzzerPin = 5; const int ledPin = 6; const int motionPin = 7; const int buttonPin = 12; boolean buzzer_mode = false; int ledState = LOW; unsigned long previousMillis = 0; const long interval = 100;  // Interval at which LED blinks int button_state=0; void setup() {   pinMode(ledPin,OUTPUT);   pinMode(buzzerPin,OUTPUT);     pinMode(buttonPin, INPUT);     delay(100); } void loop() {   if (digitalRead(motionPin))   {     buzzer_mode = true;   }   else   {     buzzer_mode = false;   }   if (buzzer_mode==HIGH)   {     unsigned long currentMillis = millis();     if(currentMillis - previousMillis >= interval)     {       previousMillis = currentMillis;             if (ledState == LOW)       {         ledState = HIGH;       }       else       {         ledState = LOW;       }     digitalWrite(ledPin, ledState);     }     tone(buzzerPin,1000);   }   else   {     noTone(buzzerPin);      digitalWrite(ledPin, LOW);   }    button_state = digitalRead(buttonPin);   if (button_state==HIGH)   {      buzzer_mode = false;     digitalWrite(ledPin, LOW);   }   else   {     buzzer_mode = true;   } }

Asked by DejunL 8 months ago


Need help with arduino code.?

Alright I asked this question on the arduino forums but nobody is giving me a straight answer, and it's getting annoying. I am using the capsense library on an attiny85, I want to count the number of times an even happens, in this case the capacitive censor exceeding a certain amount. Then based on that number I want it to turn on one led, or two, and so forth, to keep count. Can someone tell me how the f*****g get this to work? I try to use serial to debug and just get "Serial" not defined in this scope. Heres the code: #include #include CapacitiveSensor   cs_1_2 = CapacitiveSensor(1,2);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired int ledpin = 0; int countnumber = 0; void setup()                    {   cs_1_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example   pinMode (ledpin, OUTPUT); } void loop()                    {   long start = millis();   long total1 =  cs_1_2.capacitiveSensor(30);   if (total1    countnumber == 1;   }   if (countnumber = 1) {     digitalWrite(ledpin, HIGH);   } }

Asked by XOIIO 5 years ago


hii can you help me i dunno how or where i will input the codes to make 0-59 to this code 0 -99?

Int digit1 = 9; int digit2 = 10; int digit3 = 11; int digit4 = 12; int A = 2; int B = 3; int C = 4; int D = 5; int E = 6; int F = 7; int G = 8; void setup() {                  pinMode(A, OUTPUT);   pinMode(B, OUTPUT);   pinMode(C, OUTPUT);   pinMode(D, OUTPUT);   pinMode(E, OUTPUT);   pinMode(F, OUTPUT);   pinMode(G, OUTPUT);   pinMode(digit1, OUTPUT);   pinMode(digit2, OUTPUT);   pinMode(digit3, OUTPUT);   pinMode(digit4, OUTPUT);     pinMode(13, OUTPUT); } void loop() {   displayNumber(millis()/1000); } void displayNumber(int toDisplay) { #define DISPLAY_BRIGHTNESS  1000   long beginTime = millis();   for(int digit = 4 ; digit > 0 ; digit--) {      switch(digit) {     case 1:       digitalWrite(digit1, HIGH);       break;     case 2:       digitalWrite(digit2, HIGH);       break;     case 3:       digitalWrite(digit3, HIGH);       break;     case 4:       digitalWrite(digit4, HIGH);       break;     }     lightNumber(toDisplay % 10);     toDisplay /= 10;     delayMicroseconds(DISPLAY_BRIGHTNESS);           lightNumber(10);        digitalWrite(digit1, LOW);     digitalWrite(digit2, LOW);     digitalWrite(digit3, LOW);     digitalWrite(digit4, LOW);   }   while( (millis() - beginTime) } void lightNumber(int numberToDisplay) { #define SEGMENT_ON  LOW #define SEGMENT_OFF HIGH   switch (numberToDisplay){   case 0:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_ON);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_OFF);     break;   case 1:     digitalWrite(A, SEGMENT_OFF);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_OFF);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_OFF);     digitalWrite(G, SEGMENT_OFF);     break;   case 2:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_OFF);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_ON);     digitalWrite(F, SEGMENT_OFF);     digitalWrite(G, SEGMENT_ON);     break;   case 3:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_OFF);     digitalWrite(G, SEGMENT_ON);     break;   case 4:     digitalWrite(A, SEGMENT_OFF);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_OFF);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_ON);     break;   case 5:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_OFF);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_ON);     break;   case 6:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_OFF);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_ON);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_ON);     break;   case 7:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_OFF);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_OFF);     digitalWrite(G, SEGMENT_OFF);     break;   case 8:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_ON);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_ON);     break;   case 9:     digitalWrite(A, SEGMENT_ON);     digitalWrite(B, SEGMENT_ON);     digitalWrite(C, SEGMENT_ON);     digitalWrite(D, SEGMENT_ON);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_ON);     digitalWrite(G, SEGMENT_ON);     break;   case 10:     digitalWrite(A, SEGMENT_OFF);     digitalWrite(B, SEGMENT_OFF);     digitalWrite(C, SEGMENT_OFF);     digitalWrite(D, SEGMENT_OFF);     digitalWrite(E, SEGMENT_OFF);     digitalWrite(F, SEGMENT_OFF);     digitalWrite(G, SEGMENT_OFF);     break;   } }

Asked by MiguelV60 1 year ago


Virtualwire RF 433mhz Voltage problem mk2

Hi, I have this code and have modded it a bit, i was wondering if there was a way of making the pincode more than 1 digit long? Also i have got the code sending command and pin code when buton to pressed and stopping when released and the receiver end reading it and seeing it stop, sending a pin high when it reads it but i cant get i to go low when it stops receiving it. wen ever it looks like it will work It seems to make the pin go to 0.16 when low to 0.24 when high. can you help? tom Transmitter code #include int button = 2;   void setup() {     Serial.begin(9600);     vw_set_ptt_inverted(true);     vw_setup(2000);     vw_set_tx_pin(4);     pinMode(button,INPUT);     pinMode(button,LOW);   }   void loop() {     while     (digitalRead(button) == LOW);      sendMessage("1", "5");      //delay(10000);   }   void sendMessage(char* pinCode, char *data) {      if (strlen(data) > 0) {       double startTime = millis();       Serial.println("Sending...");       int msgSize = (strlen(data) + strlen(pinCode) + 1);       char packetData[msgSize];       strcat(packetData, pinCode);       strcat(packetData, ".");       strcat(packetData, data);       Serial.println("Debugging ");       Serial.print("Sending Command: ");       Serial.print(data);       Serial.print(" with Pin Code: ");       Serial.print(pinCode);       Serial.print("\n");       vw_send((uint8_t *)packetData, msgSize);       vw_wait_tx();       double endTime = millis();       double timeTaken = (endTime - startTime);       Serial.print("Time Taken: ");       Serial.print(timeTaken);       Serial.print(" ms\n");     }    } Receiver Code #include   #include   int relay = 8;   byte message[VW_MAX_MESSAGE_LEN];   byte messageLength = VW_MAX_MESSAGE_LEN;   void setup() {     Serial.begin(9600);     vw_set_ptt_inverted(true);     vw_setup(2000);     vw_set_rx_pin(2);     vw_rx_start();     pinMode(relay,INPUT);     pinMode(relay,LOW);   }   void loop() {     while     //(vw_have_message())    (vw_get_message(message, &messageLength))     {        int command = processResponse((char*)message, 1); //Byte Array Response and Pin Code.        if       // (vw_have_message());        (command) {          Serial.print("Received Command: ");          Serial.print(command);               Serial.print("\n");          digitalWrite (relay,HIGH);        }                   else //REMOVE          delay(100); //REMOVE          digitalWrite (relay,LOW); //REMOVE                 }    } int processResponse(char* message, int pinCode) {       char *p = message;       char *buf;       int o = 0;       int pin;       int command;       while ((buf = strtok_r(p, ".", &p)) != NULL)  {          if (o == 0) {            pin = atoi(buf);                    } else {            command = atoi(buf);            ;          }          o++;       }       if (pinCode == pin && command > 0) {           return command;                 } else {          return 0;                         }   } This code only sends pin 8 from 0.14 when low to 0.17 when high. unless you remove the three lines marked REMOVE then it goes from 0.14 when low to 4.47 when high but stays there and will not go low when buttton it released. Please help

Posted by Senken 3 years ago


Can't properly flash Attiny85, please help.

I have working proto of a bathroom exhaust fan controlled by methane sensor via arduino uno. I now wish to transfer this sketch to an ATtiny85 (cause i had extras). I have programmed ATtiny before, and can successfully get 'blink' going on this specific MCU. However I cannot get my sensor sketch to work properly... Perhaps I am asking too much of this little guy? I am including my code and video in hopes that someone can steer me in the right direction.  /*   AT85      Arduino    Circuit   0 (PB5)   A0             pin 3 of 50k pot   2 (PB7)   ~9             led or relay     Trim Pot        1              GND   2              GND   3              Arduino (attiny) & Sensor B1     Sensor   A1             +5VDC   H1             GND   GND            GND   B1             Trim Pot 3   */   const int numReadings = 10;    // average sensor reading used from 10 samples int ledPin = 1;                  // replaced ac/dc relay with led to debug int readings[numReadings];      // the readings from the analog input int index = 0;                  // the index of the current reading int total = 0;                  // the running total int average = 0;                // the average int inputPin = 0;    //reading from sensor unsigned long start_time; unsigned long current_time; unsigned long elapsed_time; void setup() {   // sets digital pin 1 to output   pinMode(ledPin, OUTPUT);     // sets analog 0 to input   pinMode(inputPin, INPUT);   // initialize all the readings to 0:   for (int thisReading = 0; thisReading     readings[thisReading] = 0;          } void loop() {         // 10 sample average used to prevent false positive from a bounce and/or spike         // subtract the last reading:   total= total - readings[index];           // read from the sensor:    readings[index] = analogRead(inputPin);   // add the reading to the total:   total= total + readings[index];         // advance to the next position in the array:    index = index + 1;                      // if we're at the end of the array...   if (index >= numReadings)                  // ...wrap around to the beginning:     index = 0;                             // calculate the average:   average = total / numReadings;           // send it to the computer as ASCII digits          delay(1000); // delay in between reads for stability                    int threshold = 300;                  // sets the threshold value   if(average > threshold){  // determines if the level of methane breaks threshold         start_time = millis();      // starts exhaust fan on 5 min timer     digitalWrite(ledPin, HIGH);      do  {       current_time = millis();      // defines the 5 minute timer       elapsed_time = current_time - start_time;     }     while(elapsed_time   }     if(average       digitalWrite(ledPin, LOW);  // fan turns off if sensor value below threshold     }                             // or stays on until it is below threshold     } http://youtu.be/cm_uuEXd8HM thanks in advance!

Asked by earthtown 5 years ago


Simple AM transmitter

I wish to make an extremely small (size and part count) AM transmitter using only a few transistors and passive components. I wish to transmit an audible tone on a set frequency.I am thinking along the lines of a transistor flip-flop circuit oscillator, perhaps routed through another. It really needs to have less that five/six small components. DIP components are too big. Small electrolytic and other capacitors, transistors, and resistors are acceptable. Transmission distance needs to be at least 1/4 of a meter, but further is better. It needs to run on between 1.5 and 6 volts, low to middle'in milli-ampage im thinking watch batteries for a few hours at least. I have read the following article but as stated before it needs to be very small. https://www.instructables.com/id/Make-a-simple-AM-transmitter/Can anyone help me out with a schematic, thoughts or advice?Thanks in advance,-AndyP.s. I can work out transistor loop timings and I understand how the Amplitude Modulation system works. Current thoughts/plans (if you can call them that) are an audible tone switching a secondary transistor loop from high (no resistor in series) to low (resistor in series) power and back. The secondry loop will be switching at the target frequency.

Posted by andy 10 years ago


How to Make a Constant Current Lithium Ion Charger

Hi Guys! I have a bunch of 18650 lithium ion batteries that can handle a charge rate of 5C. Each one is 3,000 milli-amp hours, and I would like to build a charger for them as my project. I understand the mechanics of charging lithium ion batteries, and that they need to be charged at a constant current up until that current reaches 4.2 volts, than switch over to constant voltage. The constant voltage charging makes up about 20% of the battery capacity, and I am willing to forgo that amount. What I am trying to build is a constant current charger for it that would  charge at a current of 1C, and shut off when it reaches 4.2 volts, and I would like some help as to how I would do this. I was thinking that I would have some sort of current source that supplied 3 amps and then have a relay that would shut off the current as soon as a voltage detector reached 4.2. I do not know much about current sources, so I am asking here for some help. Thank You for Your Help!

Posted by merlinj 1 year ago


I need help coding an arduino sketch to activate audio from an mp3 board when my PIR senses motion

My goal is to have a sound effect play when a person first walks into the field of view of my PIR. So far I can get it to work, but the sound "stutters" for about 4 seconds before it will play through all the way. The parts that I am using are:  https://www.parallax.com/product/555-28027 http://www.mdfly.com/products/microsd-tf-card-mp3-wav-player-module-ttl.html (this board doesn't have a datasheet, so i have been using the 'old version' datasheet: http://mdfly.net/Download/Module/AU5016.pdf ) and an arduino uno besides vcc and ground, my arduino's pins connect pin7 to my mp3 board's number 1 pin (which is active low) and also from my arduino's pin3 to the out/signal from my PIR sensor. I have tried a couple different example sketches and modified them to something that i thought would work, but they both have similar problems with "stuttering". Below are the sketches after modification. (note: I haven't finished changing some of the commenting yet.) I would be very thankful for any and all help. I can admit, I'm not very good at this kind of thing. This project is for halloween in 2016. I'm so bad (and I realize it) that I'm starting a year in advance. FIRST SKETCH: // Uses a PIR sensor to detect movement, buzzes a buzzer // more info here: http://blog.makezine.com/projects/pir-sensor-arduino-alarm/ // email me, John Park, at jp@jpixl.net // based upon: // PIR sensor tester by Limor Fried of Adafruit // tone code by michael@thegrebs.com int MP3Song1Pin = 7;                // choose the pin for the mp3 board int inputPin = 3;               // 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 void setup() {   pinMode(MP3Song1Pin, OUTPUT);      // declare mp3 board as output   pinMode(inputPin, INPUT);     // declare sensor as input   Serial.begin(9600); } void loop(){   val = digitalRead(inputPin);  // read input value   if (val == HIGH) {            // check if the input is HIGH     digitalWrite(MP3Song1Pin, LOW);  // turn mp3 board on     delay(10);     digitalWrite(MP3Song1Pin, HIGH);  // turn mp3 board         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(MP3Song1Pin, HIGH); // turn mp3 board OFF       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;     }   } } SECOND SKETCH: /* * ////////////////////////////////////////////////// * //making sense of the Parallax PIR sensor's output * ////////////////////////////////////////////////// * * Switches a LED according to the state of the sensors output pin. * Determines the beginning and end of continuous motion sequences. * * @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at * @date:   3. September 2006 * * kr1 (cleft) 2006 * released under a creative commons "Attribution-NonCommercial-ShareAlike 2.0" license * http://creativecommons.org/licenses/by-nc-sa/2.0/de/ * * * The Parallax PIR Sensor is an easy to use digital infrared motion sensor module. * (http://www.parallax.com/detail.asp?product_id=555-28027) * * The sensor's output pin goes to HIGH if motion is present. * However, even if motion is present it goes to LOW from time to time, * which might give the impression no motion is present. * This program deals with this issue by ignoring LOW-phases shorter than a given time, * assuming continuous motion is present during these phases. *  */ ///////////////////////////// //VARS //the time we give the sensor to calibrate (10-60 secs according to the datasheet) int calibrationTime = 30;        //the time when the sensor outputs a low impulse long unsigned int lowIn;         //the amount of milliseconds the sensor has to be low //before we assume all motion has stopped long unsigned int pause = 5000;  boolean lockLow = true; boolean takeLowTime;  int pirPin = 3;    //the digital pin connected to the PIR sensor's output int ledPin = 7; ///////////////////////////// //SETUP void setup(){   Serial.begin(9600);   pinMode(pirPin, INPUT);   pinMode(ledPin, OUTPUT);   digitalWrite(pirPin, LOW);   //give the sensor some time to calibrate   Serial.print("calibrating sensor ");     for(int i = 0; i       Serial.print(".");       delay(1000);       }     Serial.println(" done");     Serial.println("SENSOR ACTIVE");     delay(50);   } //////////////////////////// //LOOP void loop(){      if(digitalRead(pirPin) == HIGH){        digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state        delay(50);        digitalWrite(ledPin, HIGH);        if(lockLow){           //makes sure we wait for a transition to LOW before any further output is made:          lockLow = false;                     Serial.println("---");          Serial.print("motion detected at ");          Serial.print(millis()/1000);          Serial.println(" sec");          delay(50);          }                  takeLowTime = true;        }      if(digitalRead(pirPin) == LOW){              digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state        if(takeLowTime){         lowIn = millis();          //save the time of the transition from high to LOW         takeLowTime = false;       //make sure this is only done at the start of a LOW phase         }        //if the sensor is low for more than the given pause,        //we assume that no more motion is going to happen        if(!lockLow && millis() - lowIn > pause){             //makes sure this block of code is only executed again after            //a new motion sequence has been detected            lockLow = true;                                   Serial.print("motion ended at ");      //output            Serial.print((millis() - pause)/1000);            Serial.println(" sec");            delay(50);            }        }   }

Asked by Zukibeast 2 years ago


My code compiles, but doesn't work?? Answered

Hi, i'm doing a project based on the capacitive sensor method. the code will work fine as standard, but when its  with my added extras it doesnt work but it compiles. The other thing is that the its printing to the serial at 3.4 seconds, do you know why this might be. here's the code. #include #include Servo Mech; int pos = 0;   /*   * CapitiveSense Library Demo Sketc  * Paul Badger 2008 5.  * Uses a high value resistor e.g. 10M between send pin and receive pin 6  * Resistor effects sensitivity, experiment with values, 50K - 50M. Larger resistor values yield larger sensor values. 7.  * Receive pin is the sensor pin - try different amounts of foil/metal on this pin 8.  */     CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // dnt need this CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil int light = 13; int yellow = 12; //dnt need this int power = 11; int fans = 5; boolean status_light = LOW, status_light_prev = LOW; boolean status_yellow = LOW, status_yellow_prev = LOW; // dnt need this boolean status_power = LOW, status_power_prev = LOW;    void setup()                    {     cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example     Serial.begin(9600);     Mech.attach(9);     pinMode(light, OUTPUT);     pinMode(yellow, OUTPUT); // dnt need this     pinMode(power, OUTPUT);     pinMode(fans, OUTPUT); }   void loop()                    {      long start = millis();      long total1 =  cs_4_2.capacitiveSensor(30); // to power pin 11      long total2 =  cs_4_6.capacitiveSensor(30); // dnt need this      long total3 =  cs_4_8.capacitiveSensor(30); // to light        Serial.print(millis() - start);        // check on performance in milliseconds      Serial.print("\t");                    // tab character for debug windown spacing        Serial.print(total1);                  // print sensor output 1      Serial.print("\t\t\t");      Serial.print(total2);                  // print sensor output 2      Serial.print("\t\t\t");      Serial.println(total3);                // print sensor output 3        delay(100);                             // arbitrary delay to limit data to serial port          if (total1 > 200)        status_light = !status_light;      Serial.print("\tstatus_light = ");      Serial.print(status_light);      Serial.print("\t");          if (status_light)        Mech.write(20);     else     Mech.write(160);     delay(600);          if (status_light)        digitalWrite(light, HIGH);      else      digitalWrite(light, LOW);                if (total2 > 200)                // dnt need this        status_yellow = !status_yellow;      Serial.print("status_yellow = ");      Serial.print(status_yellow);           Serial.print("\t");      if (status_yellow)        digitalWrite(yellow, HIGH);        else        digitalWrite(yellow, LOW);     if (total3 > 200)       status_power = !status_power;      Serial.print("status_power = ");      Serial.println(status_power);      if (status_power)        digitalWrite(power, HIGH);      else        digitalWrite(power, LOW);        if (status_power)               if (status_power)        digitalWrite(fans, HIGH);        else        digitalWrite(fans, LOW);     } thank you for your help thank you.

Asked by icey.hood 2 years ago


Arduino: HELP: How to perform action if two rfid tag UIDs have been detected?

I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period. Essentially this: 1. First tag is read (print to serial: Tag 1 has been read) 2. Wait 2 seconds 3. Second tag is read (print to serial: Tag 2 has been read) 4. Print to serial: Tag 1 and Tag 2 has been read) 5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished) I know how to read the UID and print to the serial if one is read. Thank you so much for your help, it's greatly appreciated. Here is my code so far: #include     // Core graphics library #include // Hardware-specific library #include #include // For the breakout, you can use any 2 or 3 pins // These pins will also work for the 1.8" TFT shield #define sclk 4  // SainSmart: SCL #define mosi 5  // SainSmart: SDA #define cs   6  // SainSmart: CS #define dc   7  // SainSmart: RS/DC #define rst  8  // SainSmart: RES Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst); #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522(SS_PIN, RST_PIN); float p = 3.1415926; void setup(void) {   Serial.begin(9600);   SPI.begin();   Serial.print("Starting cornhole leaderboard...");   mfrc522.PCD_Init(); // Init MFRC522 card   Serial.println("Scan PICC to see UID and type...");   // Use this initializer if you're using a 1.8" TFT   tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab   // Use this initializer (uncomment) if you're using a 1.44" TFT   //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab   Serial.println("Initialized");   uint16_t time = millis();   tft.fillScreen(ST7735_BLACK);   time = millis() - time;   Serial.println(time, DEC);   // large block of text   tft.fillScreen(ST7735_BLACK); } void loop() {   // Look for new cards     if ( ! mfrc522.PICC_IsNewCardPresent()) {         return;     }     // Select one of the cards     if ( ! mfrc522.PICC_ReadCardSerial()) {         return;     }     if (mfrc522.uid.uidByte[0] == 0xA4 &&        mfrc522.uid.uidByte[1] == 0xB8 &&        mfrc522.uid.uidByte[2] == 0xB8 &&        mfrc522.uid.uidByte[3] == 0x96) {           Serial.println("Nate has checked in to the game.");           tft.fillScreen(ST7735_BLUE);           tft.setTextSize(2);           tft.setCursor(0, 0);           tft.setTextColor(ST7735_YELLOW);           tft.print("Nate ");           tft.setTextColor(ST7735_WHITE);           tft.println("has checked in ");           tft.setTextSize(2);           tft.println("to the game.");           delay(2000);           tft.fillScreen(ST7735_BLACK);     }     if (mfrc522.uid.uidByte[0] == 0x03 &&        mfrc522.uid.uidByte[1] == 0xFD &&        mfrc522.uid.uidByte[2] == 0xBC &&        mfrc522.uid.uidByte[3] == 0x02) {           Serial.println("Ted has checked in to the game.");           tft.fillScreen(ST7735_RED);           tft.setTextSize(2);           tft.setCursor(0, 0);           tft.setTextColor(ST7735_CYAN);           tft.print("Ted ");           tft.setTextColor(ST7735_WHITE);           tft.println("has checked in ");           tft.setTextSize(2);           tft.println("to the game.");           delay(2000);           tft.fillScreen(ST7735_BLACK);     } } Thank you!

Posted by djrage 2 years ago


attiny85 tilt switch dc motor

Hello my project consists of an attiny85 with an led a dc motor a tilt switch and  a button. the button changes the pwm values and the led goes to the same values to know the strength of pwm.  the tilt switch will activate the dc motor at the corresponding pwm speed based on how many times the button is pressed. here is my code const int inPin = 3;         // tilt switch or button to trigger dc motor const int outPin = 1;       // dc motor const int buttonPin = 2; //button to change pwm const int ledPin = 0; // led to know the state of pwm int pwmvalue = 255; int buttonPushCounter = 0; int buttonState = 0; int lastButtonState =0; int LEDstate = HIGH;      // the current state of the output pin int reading;           // the current reading from the input pin int previous = LOW;    // the previous reading from the input pin // the follow variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long time = 0;         // the last time the output pin was toggled long debounce = 50;   // the debounce time, increase if the output flickers void setup() {   pinMode(buttonPin, INPUT);   pinMode(ledPin, OUTPUT);   pinMode(inPin, INPUT);   digitalWrite(inPin, HIGH);   // turn on the built in pull-up resistor   pinMode(outPin, OUTPUT); } void loop() { buttonState = digitalRead(buttonPin); if (buttonPushCounter == 1) {   (pwmvalue == 255);}   if (buttonPushCounter == 2) {   (pwmvalue == 180);}   if (buttonPushCounter == 3) {   (pwmvalue == 110);}   if (buttonPushCounter == 4) {   (pwmvalue == 70);}   // compare the buttonState to its previous state   if (buttonState != lastButtonState) {     // if the state has changed, increment the counter     if (buttonState == HIGH) {       // if the current state is HIGH then the button       // wend from off to on:       buttonPushCounter++;           } else {       // if the current state is LOW then the button       // wend from on to off:           }     // Delay a little bit to avoid bouncing     delay(50);   }   // save the current state as the last state,   //for next time through the loop   lastButtonState = buttonState;   // turns on the LED every four button pushes by   // checking the modulo of the button push counter.   // the modulo function gives you the remainder of   // the division of two numbers:   if (buttonPushCounter % 0 == 0) {     analogWrite(ledPin,pwmvalue);   }   if (buttonPushCounter % 1 == 0) {       analogWrite(ledPin,pwmvalue);   }   if (buttonPushCounter % 2 == 0) {       analogWrite(ledPin,pwmvalue);   }   if (buttonPushCounter % 3 == 0) {       analogWrite(ledPin,pwmvalue);   }       int switchstate;   reading = digitalRead(inPin);   // If the switch changed, due to bounce or pressing...   if (reading != previous) {     // reset the debouncing timer     time = millis();   }   if ((millis() - time) > debounce) {      // whatever the switch is at, its been there for a long time      // so lets settle on it!      switchstate = reading;      // Now invert the output on the pin13 LED     if (switchstate == HIGH)       LEDstate = LOW;     else       LEDstate = HIGH;   } LEDstate = HIGH == pwmvalue;     digitalWrite(outPin, pwmvalue);   // Save the last reading so we keep a running tally   previous = reading;   } is my code written correctly for my purpose is there anything i could have written better? its compiling without any problems andni havn't been able to upload because i ust back into arduino and im waiting for my attinys to come in. thank you guys for reading.

Asked by wesm4 1 year ago


How hard can it be to use an Arduino to control two relays using two momentary switches?

This is a problem which I have been trying to solve for literally months now! I am using an Arduino Nano (V3.0) to operate two non latching relays by the push of a button. Switch A will turn on Relay A at the first push, it will then turn it off at the second push. Switch B does the same to Relay B, hopefully. So far, I have been using the 'debounce' example to control one set - Switch A and Relay A. This works perfectly, however I have issues when I try and make a sketch which will enable both A and B to work together at the same time but independently. After spending hours researching and looking through the Arduino forums, I know it can be done, but most likely not with this sketch due to the 'delay' in there? I read about the 'millis' command somewhere too, but I'm baffled by it! Obviously, I still have A LOT to learn about Arduinos.  The circuit is wired up and ready, I could just really do with a bit (*lot! ;) ) oh help with the programming, as it seems like it needs to be completely re-written :(  Last thing - this is part of my A-level Product Design project, and my deadline is next week, so if this approach cannot be resolved, I'll just have to buy a second Nano and use both, which seems a waste of two pretty powerful microelectronics!  Thanks guys!

Asked by lukestanmore 4 years ago


ATtiny85 Supported Commands? Answered

Lately i have had a problem with certain sketches not working correctly on an ATtiny85-20PU. The blink sketch works fine on the ATtiny85 but this sketch below will not, also this sketch below does work correctly on an Arduino board. The list of supported commands for ATtiny85 are pinMode() digitalWrite() digitalRead() analogRead() analogWrite() shiftOut() pulseIn() millis() micros() delay() delayMicroseconds() Also the Arduino reference page is  The one possible thing i can see as not being supported might be "  round  " on line 33 causing this sketch to not work properly. I do not know this for a fact as i can not actually find anything that is not supported. Do you know if " round " is a hang up for ATtiny85's? . //int IRSense = A0;  //For ATnega328 int IRSense = 2;  // For ATtiny85 //int IRTrans = 9;  // For ATnega328 int IRTrans = 3;  // For ATtiny85 //int LED1 = 10;    // For ATmega328 int LED1 = 4;     // For ATtiny85 int valueAmbient = 0; void setup() { pinMode(IRSense, INPUT); pinMode(IRTrans, OUTPUT); //Serial.begin(9600); digitalWrite(IRTrans,LOW); pinMode(LED1,OUTPUT); } void ambient() { digitalWrite(IRTrans,HIGH); delay(20); valueAmbient = analogRead(IRSense); delay(20); } void loop() { ambient(); digitalWrite(IRTrans,LOW); delay(20); int value = analogRead(IRSense); int value2 = round(value - valueAmbient); int dist = (((value2+15.0)/(value2*(value2+100.0)))*2000.0); if (dist   digitalWrite(LED1,HIGH); } else { digitalWrite(LED1,LOW); } //Serial.print(dist); //Serial.print("cm."); //Serial.println(""); delay(20); }

Asked by WWC 5 years ago


Arduino BUTTON_PIN?

I am having trouble with the BUTTON_PIN to work the servo. If i use the BUTTON_PIN sketch as a stand alone it will operate the servo. When i try to incorporate the button sketch into the keypad sketch i can not get the servo to operate. The button is supposed to bypass the keypad and operate the servo. How could i get this to operate correctly? I will post the library files if needed.   Thanks W #include #include #include //tells to use servo library Servo myservo; //declares servo Password password = Password( "4444" ); //password to unlock door, can be changed const byte ROWS = 4; // Four rows const byte COLS = 3; // columns // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3',}, {'4','5','6',}, {'7','8','9',}, {'*','0','#',}, }; byte rowPins[ROWS] = { 5, 4, 3, 2 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte colPins[COLS] = { 8, 7, 6,};// Connect keypad COL0, COL1 and COL2 to these Arduino pins. // Create the Keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); unsigned long offtime; boolean  helper_light_is_on = false; // helper light off #define BUTTON_PIN        A0  // Button #define DELAY            20  // Delay per loop in ms boolean handle_button() {   int button_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed   return button_pressed; } void setup() {   pinMode(BUTTON_PIN, INPUT);   digitalWrite(BUTTON_PIN, HIGH); // pull-up   Serial.begin(9600);   Serial.print(254, BYTE);   Serial.print(0x01, BYTE);   delay(200);   pinMode(10, OUTPUT);  //Helper light   pinMode(11, OUTPUT);  //green light   pinMode(12, OUTPUT);  //red light   myservo.attach(9); //servo on digital pin 9 //servo   keypad.addEventListener(keypadEvent); //add an event listener for this keypad } void loop() {   // handle button   boolean button_pressed = handle_button();   // do other things   Serial.print(button_pressed ? "^" : ".");   // add newline sometimes   static int counter = 0;   if ((++counter & 0x3f) == 0)     Serial.println();   delay(DELAY);   keypad.getKey();   myservo.write(0);   process_helper_light(); } //take care of some special events void keypadEvent(KeypadEvent eKey) {   switch (keypad.getState())   {     case PRESSED:       // a key is pressed so light the helper light       helper_light_is_on = true;       digitalWrite(10,HIGH);       offtime = millis() + 5000;  // set the offtime for 30 seconds in the future             Serial.print(" enter: ");       Serial.println(eKey);       delay(DELAY);       Serial.print(254, BYTE);       switch (eKey)       {         case '*':           checkPassword();           delay(1);           break;         case '#':           password.reset();           delay(1);           break;         default:           password.append(eKey);           delay(1);            }   } } void checkPassword() {   if (password.evaluate())  //if password is right unlock door   {      Serial.println(" Accepted");     Serial.print(254, BYTE);     delay(DELAY);     //Add code to run if it works     myservo.write(90); //160deg     digitalWrite(11, HIGH);//turn on     delay(2000); //wait 5 seconds     digitalWrite(11, LOW);// turn off   }   else   {     Serial.println(" Denied"); //if passwords wrong keep door locked     Serial.print(254, BYTE);     delay(DELAY);     //add code to run if it did not work     myservo.write(0);     digitalWrite(12, HIGH); //turn on     delay(2000); //wait 5 seconds     digitalWrite(12, LOW);//turn off   }    if (handle_button == LOW)   {     myservo.write(90); //160deg     delay(DELAY); //wait 5 seconds      }   else   {     myservo.write(0);     delay(DELAY); //wait 5 seconds    } } // this routine turns off the light when the timer expires void process_helper_light(void) {   if (helper_light_is_on)   {     if (millis() >= offtime)     {       digitalWrite(10,LOW);  //turn off the helper light       helper_light_is_on = false;     }   } }

Asked by WWC 5 years ago


Stepper Enable Answered

Seems my completed code is not completed yet. I need to enable the stepper. I added enable_pin = 13 so it will spin free. It works with the push button until the keypad is used the no more button pin, but will continue to work with the keypad properly.  Is there a correct way to use enable for 2 inputs, button and keypad? #include #include #include Password password = Password( "4444" ); //password to unlock door, can be changed const byte ROWS = 4; // Four rows const byte COLS = 3; // columns const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3',}, {'4','5','6',}, {'7','8','9',}, {'*','0','#',}, }; byte rowPins[ROWS] = { 5, 4, 3, 2 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte colPins[COLS] = { 8, 7, 6,};// Connect keypad COL0, COL1 and COL2 to these Arduino pins. Stepper myStepper(stepsPerRevolution, 9,10,11,12);            int enable_pin = 13; int button_pin = A0; int button_pinstate = 0; // variable to store current pir state //int lastpirstate = 0; // variable to store last pir state int lastbutton_pinstate = 0; int pos = 60; int pos2 = -60; // Create the Keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );   unsigned long offtime;   boolean  helper_light_is_on = false; // helper light off        void setup(){                                                              myStepper.setSpeed(60);  // set the speed at 60 rpm:   pinMode( button_pin, INPUT);   pinMode(enable_pin, OUTPUT);   digitalWrite(enable_pin, LOW);   digitalWrite(button_pin, HIGH); // pull-up   Serial.begin(9600);   Serial.write(254);   Serial.write(0x01);   delay(200);   pinMode(15, OUTPUT);  //Helper light   pinMode(16, OUTPUT);  //green light   pinMode(17, OUTPUT);  //red light     keypad.addEventListener(keypadEvent); //add an event listener for this keypad } void loop() { button_pinstate = digitalRead(button_pin);   if(button_pinstate != lastbutton_pinstate) {     if(button_pinstate == LOW) {       digitalWrite(enable_pin,HIGH);     myStepper.step(pos);      } else{        myStepper.step(pos);        delay(2000);        myStepper.step(pos2);         digitalWrite(enable_pin,LOW);     } }     static int counter = 0;     if ((++counter & 0x3f) == 0)     Serial.println();     delay(100);     keypad.getKey();     myStepper.step(0);     process_helper_light(); } void keypadEvent(KeypadEvent eKey) {   switch (keypad.getState())   {     case PRESSED:       // a key is pressed so light the helper light       helper_light_is_on = true;       digitalWrite(15,HIGH);       offtime = millis() + 5000;  // set the offtime for 30 seconds in the future             Serial.print(" enter: ");       Serial.println(eKey);       delay(10);       Serial.write(254);       switch (eKey)       {         case '*':           checkPassword();           delay(1);           break;         case '#':           password.reset();           delay(1);           break;         default:           password.append(eKey);           delay(1);           }   } } void checkPassword() {   if (password.evaluate())  //if password is right unlock door   {      Serial.println(" Accepted");     Serial.write(254);     delay(10);      digitalWrite(enable_pin,HIGH);     myStepper.step(pos);     Serial.print(" open ");     digitalWrite(16, HIGH);//turn on green led     delay(2000); //wait 5 seconds     digitalWrite(16, LOW);// turn offgreen led     myStepper.step(pos2);      digitalWrite(enable_pin,LOW);   }    else   {     Serial.println(" Denied"); //if passwords wrong keep door locked     Serial.write(254);     delay(10);     myStepper.step(0);     Serial.println(" locked ");         digitalWrite(17, HIGH); //turn on red led     delay(2000); //wait 5 seconds     digitalWrite(17, LOW);//turn off red led   digitalWrite(enable_pin,LOW);     }  //Closes first else }  //Closes Check password // this routine turns off the light when the timer expires void process_helper_light(void) {   if (helper_light_is_on)   {     if (millis() >= offtime)     {       digitalWrite(15,LOW);  //turn off the helper light       helper_light_is_on = false;     }   } }

Asked by WWC 5 years ago


static int counter = 0; if ((++counter & 0x3f) == 0) Answered

I have not been ablle to find a laymans discription of what this is counting. Looks like it is counting 63 times from the 0x3f ASCII charactor. I bleave it is counting for the helper light, but what for? #include #include #include Password password = Password( "7457" ); //password to unlock door, can be changed const byte ROWS = 4; // Four rows const byte COLS = 3; // columns const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3',}, {'4','5','6',}, {'7','8','9',}, {'*','0','#',}, }; byte rowPins[ROWS] = { 5, 4, 3, 2 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte colPins[COLS] = { 8, 7, 6,};// Connect keypad COL0, COL1 and COL2 to these Arduino pins. Stepper myStepper(stepsPerRevolution, 9,10,11,12); int enable_pin = 13; int button_pin = A0; int button_pinstate = 0; // variable to store current pir state //int lastpirstate = 0; // variable to store last pir state int lastbutton_pinstate = 0; int pos = 35; int pos2 = -35;  // Create the Keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); unsigned long offtime; boolean helper_light_is_on = false; // helper light off void setup(){ myStepper.setSpeed(60); // set the speed at 60 rpm: pinMode( button_pin, INPUT); digitalWrite(button_pin, HIGH); // pull-up Serial.begin(9600); Serial.write(254); Serial.write(0x01); delay(200); pinMode(15, OUTPUT); //Helper light pinMode(16, OUTPUT); //green light pinMode(17, OUTPUT); //red light pinMode(enable_pin, OUTPUT); digitalWrite(enable_pin,HIGH); keypad.addEventListener(keypadEvent); //add an event listener for this keypad } void loop() { button_pinstate = digitalRead(button_pin); if(button_pinstate != lastbutton_pinstate) { Serial.println(" Button Press"); if(button_pinstate == LOW)// { delay(10); digitalWrite(enable_pin,HIGH); myStepper.step(pos); Serial.print(" Open "); delay(2000); myStepper.step(pos2); Serial.print(" Close "); digitalWrite(enable_pin,LOW); delay(10); } static int counter = 0; if ((++counter & 0x3f) == 0) Serial.println(); delay(100); keypad.getKey(); myStepper.step(0); process_helper_light(); } void keypadEvent(KeypadEvent eKey) { switch (keypad.getState()) { case PRESSED: // a key is pressed so light the helper light helper_light_is_on = true; digitalWrite(15,HIGH); offtime = millis() + 5000; // set the offtime for 30 seconds in the future Serial.print(" enter: "); Serial.println(eKey); delay(10); Serial.write(254); switch (eKey) { case '*': checkPassword(); delay(1); break; case '#': password.reset(); delay(1); break; default: password.append(eKey); delay(1); } } } void checkPassword() { if (password.evaluate()) //if password is right unlock door { Serial.println(" Accepted"); Serial.write(254); delay(10); digitalWrite(enable_pin,HIGH); myStepper.step(pos); Serial.print(" open "); digitalWrite(16, HIGH);//turn on green led delay(2000); //wait 5 seconds digitalWrite(16, LOW);// turn offgreen led myStepper.step(pos2); digitalWrite(enable_pin,LOW); Serial.print(" Close "); } else { Serial.println(" Denied"); //if passwords wrong keep door locked Serial.write(254); delay(10); myStepper.step(0); Serial.println(" locked "); digitalWrite(17, HIGH); //turn on red led delay(2000); //wait 5 seconds digitalWrite(17, LOW);//turn off red led } }  void process_helper_light(void) { if (helper_light_is_on) { if (millis() >= offtime) { digitalWrite(15,LOW); //turn off the helper light helper_light_is_on = false; } } }

Asked by WWC 5 years ago


I want to build a temperature sensor, any idea?

I'm having problems connecting the wires together and my code is not compiling please help? #include #include SevSeg sevseg; LEDDisplay *led; int ledPin = 9; int inputPin = 13; int core = 0; int val; int tempPin = 0; int buttonState = 0; float celsius; int tempUnits = celsius; int refreshTime = 5000; unsigned long timer; float kelvin = 0; const int buttonPin[] = {2,3};     // the number of the pushbutton pins const int ledPin =  13;      // the number of the LED pin void setup(){   pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); Serial.begin(9600); sevseg.Begin(1,2,3,4,5,6,7,8,9,10,11,12,13); // initialize the LED pin as an output:   pinMode(ledPin, OUTPUT);     for(int x=0; x   {     pinMode(buttonPin[x], INPUT);   }  int digitFlagPins[] = {10, 11}; int segmentPins[] = {1, 3, 4, 5 ,6 ,7 ,8, 9, 10}; led = new LEDDisplay(2, digitFlagPins[2], segmentPins[9]); } void loop(){   // read the state of the pushbutton value:   for(int x=0; x   {     buttonState = digitalRead(buttonPin[x]);     // check if the pushbutton is pressed.     // if it is, the buttonState is HIGH:     if (buttonState == HIGH && buttonPin[x] == 2) {          // turn LED on:         digitalWrite(ledPin, HIGH);     }     if (buttonState == HIGH && buttonPin[x] == 3) {       // turn LED off:       digitalWrite(ledPin, LOW);       }   } val = analogRead(tempPin); float mv = ( val/1024.0)*5000; float cel = mv/10; sevseg.PrintOutput(); kelvin = analogRead(0) * 0.004882812 * 100; celsius = kelvin - 2.5 - 273.15; unsigned long mils=millis();   if (mils-timer>=refreshTime) {     timer=mils;     //Print teperature to the displays   sevseg.NewNum(tempUnits,(byte) 2);   } delay(1000); }

Asked by Houtarou- 2 years ago


Can Someone Modify an Arduino Sketch For Me? Answered

I recently got into Arduino, and my first long term project is an autonomous roaming robot. Now, I've been in electronics for a while, so the actual building of the thing was not a problem....but the programming is. I've found a couple examples of codes online, but they all use Sharp IR sensors, whereas I have a Ping))) Ultrasonic sensor. I was wondering if there were any Arduino experts out there that could modify a sketch that I found to only use the Ping))) instead of the IR sensor(s). This sketch actually uses both, and would be perfect if the Ping))) was used in place of the IR sensors, rather than with them. If anybody could modify the sketch below to do as I said, your help would be greatly appreciated. Thanks. Code: int micVal; int cdsVal; int irLval;  // Left IR int irCval;  // Center IR int irRval;  // Right IR int i;   // Generic Counter int x;  // Generic Counter int PLval;  // Pulse Width for Left Servo int PRval;  // Pulse Width for Right Servo int cntr;  // Generic Counter Used for Determining amt. of Object Detections int counter; // Generic Counter int clrpth;  // amt. of Milliseconds Of Unobstructed Path int objdet;  // Time an Object was Detected int task;  // Routine to Follow for Clearest Path int pwm;  // Pulse Width for Pan Servo boolean add;  // Whether to Increment or Decrement PW Value for Pan Servo int distance;  // Distance to Object Detected via Ultrasonic Ranger int oldDistance;  // Previous Distance Value Read from Ultrasonic Ranger float scale = 1.9866666666666666666666666666667;  // *Not Currently Used* int LeftPin = 6;  // Left Servo int RightPin = 9;  // Right Servo int PiezoPin = 11;  // Piezo int PingServoPin = 5;  // Pan Servo int irLPin = 0;            // Analog 0; Left IR int irCPin = 1;            // Analog 1; Center IR int irRPin = 2;            // Analog 2; Right IR int ultraSoundSignal = 7; // Ultrasound signal pin int val = 0;              // Used for Ultrasonic Ranger int ultrasoundValue = 0;  // Raw Distance Val int oldUltrasoundValue;  // *Not used* int pulseCount;        // Generic Counter int timecount = 0; // Echo counter int ledPin = 13; // LED connected to digital pin 13 #define BAUD 9600 #define CmConstant 1/29.034 void setup() {   Serial.begin(9600);   pinMode(PiezoPin, OUTPUT);   pinMode(ledPin, OUTPUT);   pinMode(LeftPin, OUTPUT);   pinMode(RightPin, OUTPUT);   pinMode(PingServoPin, OUTPUT);   pinMode(irLPin, INPUT);   pinMode(irCPin, INPUT);   pinMode(irRPin, INPUT);   for(i = 0; i     digitalWrite(PiezoPin, HIGH);     delayMicroseconds(1000);     digitalWrite(PiezoPin, LOW);     delayMicroseconds(1000);   }   for(i = 0; i   digitalWrite(PingServoPin, HIGH);   delayMicroseconds(655 * 2);   digitalWrite(PingServoPin, LOW);   delay(20);   }   ultrasoundValue = 600;   i = 0; } void loop() {   //Scan();   Look();   Go(); } void Look() {   irLval = analogRead(irLPin);   irCval = analogRead(irCPin);   irRval = analogRead(irRPin);   //if(counter > 10) {     //counter = 0;     //readPing();   //}   if(irLval > 200) {     PLval = 820;     PRval = 850;     x = 5;     cntr = cntr + 1;     clrpth = 0;     objdet = millis();   }   else if(irCval > 200) {     PLval = 820;     PRval = 850;     x = 10;     cntr = cntr + 1;     clrpth = 0;     objdet = millis();   }   else if(irRval > 200) {     PLval = 620;     PRval = 650;     x = 5;     cntr = cntr + 1;     clrpth = 0;     objdet = millis();   }   else {     x = 1;     PLval = 620;     PRval = 850;     counter = counter + 1;     clrpth = (millis() - objdet);     if(add == true) {       pwm = pwm + 50;     }     else if(add == false) {       pwm = pwm - 50;     }     if(pwm       pwm = 400;       add = true;     }     if(pwm > 950) {       pwm = 950;       add = false;     }     digitalWrite(PingServoPin, HIGH);     delayMicroseconds(pwm * 2);     digitalWrite(PingServoPin, LOW);     delay(20);     readPing();     if(ultrasoundValue       cntr = cntr + 1;       switch(pwm) {         case 400:           x = 7;           PLval = 650;           PRval = 650;           Go();           break;         case 500:           x = 10;           PLval = 650;           PRval = 650;           Go();           break;         case 600:           x = 14;           PLval = 850;           PRval = 850;           Go();           break;         case 700:           x = 10;           PLval = 850;           PRval = 850;           Go();           break;         case 950:           x = 7;           PLval = 850;           PRval = 850;           Go();           break;       }     }   }   //Serial.print("clrpth: ");   //Serial.println(clrpth);   //Serial.print("objdet: ");   //Serial.println(objdet);   //Serial.print("cntr: ");   //Serial.println(cntr);   if(cntr > 25 && clrpth     clrpth = 0;     cntr = 0;     Scan();   } } void Go() {   for(i = 0; i     digitalWrite(LeftPin, HIGH);     delayMicroseconds(PLval * 2);     digitalWrite(LeftPin, LOW);     digitalWrite(RightPin, HIGH);     delayMicroseconds(PRval * 2);     digitalWrite(RightPin, LOW);     delay(20);   } } void readPing() {  // Get Distance from Ultrasonic Ranger timecount = 0; val = 0; pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output /* Send low-high-low pulse to activate the trigger pulse of the sensor * ------------------------------------------------------------------- */ digitalWrite(ultraSoundSignal, LOW); // Send low pulse delayMicroseconds(2); // Wait for 2 microseconds digitalWrite(ultraSoundSignal, HIGH); // Send high pulse delayMicroseconds(5); // Wait for 5 microseconds digitalWrite(ultraSoundSignal, LOW); // Holdoff /* Listening for echo pulse * ------------------------------------------------------------------- */ pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input val = digitalRead(ultraSoundSignal); // Append signal value to val while(val == LOW) { // Loop until pin reads a high value   val = digitalRead(ultraSoundSignal); } while(val == HIGH) { // Loop until pin reads a high value   val = digitalRead(ultraSoundSignal);   timecount = timecount +1;            // Count echo pulse time } /* Writing out values to the serial port * ------------------------------------------------------------------- */ ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue //serialWrite('A'); // Example identifier for the sensor //printInteger(ultrasoundValue); //serialWrite(10); //serialWrite(13); /* Lite up LED if any value is passed by the echo pulse * ------------------------------------------------------------------- */ if(timecount > 0){   digitalWrite(ledPin, HIGH); } } void Scan() {   // Scan for the Clearest Path   oldDistance = 30;   task = 0;   for(i = 1; i     switch(i) {       case 1:         //Serial.println("Pos. 1");         pwm = 1125;    ///  incr. by 100 from 1085         break;       case 2:         //Serial.println("Pos. 2");         pwm = 850; //// increased by 100 from 850         break;       case 3:         //Serial.println("Pos. 3");         pwm = 400;         break;       case 4:         //Serial.println("Pos. 4");         pwm = 235;         break;     }     for(pulseCount = 0; pulseCount       digitalWrite(PingServoPin, HIGH);       delayMicroseconds(pwm * 2);       digitalWrite(PingServoPin, LOW);       readPing();       delay(20);     }     distance = ((float)ultrasoundValue * CmConstant);   // Calculate Distance in Cm     if(distance > oldDistance) {  // If the Newest distance is longer, replace previous reading with it       oldDistance = distance;       task = i;   // Set task equal to Pan Servo Position     }   }   //Serial.print("Task: ");   //Serial.println(task);   //Serial.print("distance: ");   //Serial.println(distance);   //Serial.print("oldDistance: ");   //Serial.println(oldDistance);   distance = 50;  // Prevents Scan from Looping   switch(task) {   // Determine which task should be carried out     case 0:  // Center was clearest       x = 28;       PLval = (850);       PRval = (850);       Go();       break;     case 1:  // 90 degrees Left was Clearest       x = 14;       PLval = (650);       PRval = (650);       Go();       break;     case 2:  // 45 degrees left       x = 7;       PLval = (650);       PRval = (650);       Go();       break;     case 3:  // 45 degrees right       x = 7;       PLval = (850);       PRval = (850);       Go();       break;     case 4:  // 90 degrees right       x = 14;       PLval = (850);       PRval = (850);       Go();       break;   } }    

Asked by punkhead58 8 years ago


Im will create the 4wdrobot with lcd that show the obstacle and the distance cm help please the code?

/* 2011-10-03 robot4wd_06.pde Eric Pavey - www.akeric.com This software is released to the wild, free to be used and modified. If you use it, I just ask for some credit ;) Program to drive the 4wd robot chasis using an arduino paired up with a ping))) sensor and a servo for collision detection. Hardware: Arduino Duemilanove (but I'm sure any others will work) http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove Arduino is powered off a 5xAA producing 7.5v, sitting in the belly of the chassis. Main chassis is the "4wd mobile platform" from DF Robot http://www.dfrobot.com/index.php?route=product/product&path=37&product_id=97 http://www.makershed.com/ProductDetails.asp?ProductCode=MKSEEED8 http://www.rugcommunity.org/page/dfrobot-4wd-arduino-mobile Motor control using the Adafruit motorshield: http://www.ladyada.net/make/mshield/index.html There doesn't seem to be API docs, but there is this header file: https://github.com/adafruit/Adafruit-Motor-Shield-library/blob/master/AFMotor.h Motor shield is powered off 4xC batteries (6v). Paralax ping))) : http://www.parallax.com/tabid/768/ProductID/92/Default.aspx http://www.arduino.cc/en/Tutorial/Ping Notes: I had to rewire the ribon connecting the ping to the motorshield: The ping's ribon is ground\+5v\signal, but the motorshield's input pins order are +5v\ground\signal. It works from 2cm to 3m. Paralax (Fubata) "standard servo": This is found in the "PING))) Mounting Bracket Kit": http://www.parallax.com/Store/Robots/RoboticAccessories/tabid/145/CategoryID/22/List/0/SortField/0/Level/a/ProductID/248/Default.aspx This is plugged into the 'servo2' port on the motorshield. It uses the servo library: http://arduino.cc/en/Reference/Servo Much of the ping code at the bottom is taken straight from the Arduino examples. */ //-------------------------------------------------------------------------- // Library include stuff: #include // needed for the motorshield. #include // motorshield needs this for running servos. #include LiquidCrystal lcd(3, 4, 5, 6, 11, 12); //-------------------------------------------------------------------------- // globals: // ping))) stuff: int g_pingPin = 19; // this is actually analog pin 5, pretending to be digital, on the motorshield. long g_collideDist = 50; // in cm, how far before collision mode kicks in? long g_cm = 300; // the current ping reading, just ana initial default. boolean g_checkLeft = false; // used for collision detection boolean g_checkRight = false; // used for collision detection boolean g_checkCenter = false; // used for collision detection int g_leftDist = 0; // used for collision detection int g_rightDist = 0; // used for collision detection // motor stuff: AF_DCMotor g_motor1(1, MOTOR12_8KHZ); // back left AF_DCMotor g_motor2(2, MOTOR12_8KHZ); // back right AF_DCMotor g_motor3(3, MOTOR12_8KHZ); // front right AF_DCMotor g_motor4(4, MOTOR12_8KHZ); // front left byte g_motorSpeed = 255; // max is 255 // Mode (state) stuff: byte g_mode = 1; // 1 = drive, 2 = proximity check, 3 = turning byte g_driveDir = -1; // 0 = stop, 1 = straight, 2 = right, 3 = left // servo stuff: Servo g_servo2; int g_servo2pin = 9; // servo2 uses digital pin 9, even though the docs say pin 10... int g_servoCenter = 98; // in degrees. 98 is straight ahead based on how I mounted the servo (it must be // a little inaccurate). full left is 180, full right is 0. // Servo is flipped upside down, fyi int g_servoRight = 135; // how far right? Max is 180, full right. int g_servoLeft = 45; // how far left? Min is 0, full left. // time stuff unsigned long g_time; // global time tracker unsigned long g_ptime; // global previous time tracker unsigned long g_elapsed = 0; // helps keeping track of framerate. unsigned long g_interval = 33; // in ms (about 30fps). This slows down the processing allowing the // multiple systems to play nicely together. Make this number smaller and it won't have enough // time for each state to run properly: The servo won't do a full sweep when scanning. unsigned long g_turnlength = 750; // in ms, how long to turn for. Since we don't know how far // it turns, we just guess on how long it should. The type of terrain turing on has a great // effect on what this should be. This value works well for my hardwood floors. unsigned long g_turnUntil; // used to track how long to turn. //-------------------------------------------------------------------------- // setup \ loop : void setup() { // Attach & center the servo: g_servo2.attach(g_servo2pin); g_servo2.write(g_servoCenter); // center it by default // Setup our framerate stuff g_time = millis(); g_ptime = g_time; } void loop() { // Main program entry point. // Need to keep the aiming and the piging at a fixed rate, or the closer the object gets // to the ping the faster it will aim, and do bad stuff. g_ptime = g_time; g_time = millis(); g_elapsed += g_time - g_ptime; // Wait for the proper amount of time to pass before we do anything: if(g_elapsed g_collideDist || g_cm == 0){ // If there is nothing in our way, drive! if(g_driveDir != 1){ g_driveDir = 1; move(g_driveDir); } } else{ // if we're too close to something, stop the motors and switch to 'proximity check' mode: if(g_driveDir != 0){ g_driveDir = 0; move(g_driveDir); } // initialize the proximity check stuff: g_checkLeft = false; g_checkRight = false; g_checkCenter = false; g_leftDist = 0; g_rightDist = 0; // switch to mode 2: g_mode = 2; } } else if(g_mode == 2){ // Do proximity check! boolean checked = proximityCheck(); if(checked){ // Define which direction to turn. // If the right distance is greater than the left distance, turn that direction, // otherwise go the other way: if(g_rightDist >= g_leftDist){ g_driveDir = 2; } else{ g_driveDir = 3; } // now that we've set which direction to turn, start timing how long the turn // has taken, and switch to mode 3. g_turnUntil = millis() + g_turnlength; g_mode = 3; } } else if(g_mode == 3){ // We must be turning! The logic for switching to other modes is in that function. turn(); } } //-------------------------------------------------------------------------- // Helper functions: void turn(){ // Executed when g_mode == 3 // Used to turn the robot. if (millis() g_collideDist || g_cm == 0){ // If there is nothing in our way go back to mode 1: g_mode = 1; } else{ // If stuff is still in our way, turn more in the same direction until // not blocked: g_turnUntil = millis() + g_turnlength; } } } boolean proximityCheck(){ // Used when mode == 2: Swing the ping left and right taking readings to // find which way is safe to go. Returns false when in the middle of the check // operation, returns true when entire check process is complete. // Current angle of the servo: float angle = g_servo2.read(); // check left first: ( full left is 0 deg) if(g_checkLeft == false){ if(angle > g_servoLeft){ g_servo2.write(angle-10) ; return false; } else{ g_checkLeft = true; g_leftDist = ping(); return false; } } // check right second: ( full right is 180 deg) if(g_checkLeft == true && g_checkRight == false){ if(angle 0){ //digitalWrite(ledPin, HIGH);}

Asked by pe2hlc 5 years ago