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 5 years ago

Please can you Rate?

Please can anyone rate and suggest for my new instructable:

Posted by Patel Darshil 1 year ago

ATTINY As A Clock?

Will using time library with an Attiny/45/85/84 ( ) 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 4 years ago

Arduino capacitive touch sensor help

So I have been messing around with the Arduino Capsense library with the immensely helpful guide;  (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

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 7 months 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 <300) //This robot moves on a white background           {           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 < 50) // this is how many tick i want it to move back with the encoder           {                     }           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, < 512 means button not pushed          return turnOnOff;                       // return the value of turnOnOff without changing it         contactTime=millis();                    // set contactTime = to the millis() clock value         while(valButton<=512)         {                   // 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<20)               // If the button is held for less than 20 ms          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 (;=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 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 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 5 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 <= bad)   {     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:

Posted by cnc5axiscut 4 years ago

Binary Arduino Alarm Clock HELP!

I am currently working on THIS INSTRUCTABLE: 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 < 23)       (*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 < 59)       (*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<50)       {         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:, 100);       }       else if(alarm_on==false) // if off, turn on       {         alarm_on = true;         // play tone so the user know the alarm turned off:, 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 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 =;    // 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 =;  // 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

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

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

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. 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

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

Ethernet.h causing problems with 7 segment display driver [Arduino]

Hey Instructables,  I have a really annoying issue with some Arduino code I am writing.  The code is for an ethernet controlled countdown timer.  In it's component parts the functions all work fine,  I can drive the 7 segment display fine. I can start/stop/set a count over Ethernet However as soon as I add the line  Ethernet.begin(mac, ip); in void setup()  The 7 segment display starts to show errors, specifically the first of the four digits. Even If I don't include any additional Ethernet related code in the loop, just calling the library on setup causes problems.  I'm not an especially experienced programmer so I'm really hoping someone can share a little of their wisdom here! #include #include          // needed for Arduino versions later than 0018 #include #include          // UDP library from: 12/30/2008 int digit1 = 11; //PWM Display pin 1 int digit2 = 10; //PWM Display pin 2 int digit3 = 9; //PWM Display pin 6 int digit4 = 6; //PWM Display pin 8 //Pin mapping from Arduino to the ATmega DIP28 if you need it // int segA = A1; //Display pin 14 int segB = 3; //Display pin 16 int segC = 4; //Display pin 13 int segD = 5; //Display pin 3 int segE = A0; //Display pin 5 int segF = 7; //Display pin 11 int segG = 8; //Display pin 15 // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192, 168, 1, 177); unsigned int localPort = 8888;      // local port to listen on // buffers for receiving and sending data char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, char ReplyBuffer[] = "acknowledged";       // a string to send back // An EthernetUDP instance to let us send and receive packets over UDP EthernetUDP Udp; elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs //  milliseconds in a second unsigned int interval = 1000; unsigned int seconds = 0; unsigned int state = 1; unsigned int timeSetting = 10; unsigned int oldSeconds = 0; char theCount[9] = "01:06:30"; int secs = 0; int mins = 0; int hours = 0; String isItTime = ""; String firstFour = ""; void setup() {                      Ethernet.begin(mac, ip);   Udp.begin(localPort);      pinMode(segA, OUTPUT);   pinMode(segB, OUTPUT);   pinMode(segC, OUTPUT);   pinMode(segD, OUTPUT);   pinMode(segE, OUTPUT);   pinMode(segF, OUTPUT);   pinMode(segG, 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  500 #define DIGIT_ON  HIGH #define DIGIT_OFF  LOW   long beginTime = millis();   for(int digit = 4 ; digit > 0 ; digit--) {     //Turn on a digit for a short amount of time     switch(digit) {     case 1:       digitalWrite(digit1, DIGIT_ON);       break;     case 2:       digitalWrite(digit2, DIGIT_ON);       break;     case 3:       digitalWrite(digit3, DIGIT_ON);       break;     case 4:       digitalWrite(digit4, DIGIT_ON);       break;     }     //Turn on the right segments for this digit     lightNumber(toDisplay % 10);     toDisplay /= 10;     delayMicroseconds(DISPLAY_BRIGHTNESS); //Display this digit for a fraction of a second (between 1us and 5000us, 500 is pretty good)     //Turn off all segments     lightNumber(10);     //Turn off all digits     digitalWrite(digit1, DIGIT_OFF);     digitalWrite(digit2, DIGIT_OFF);     digitalWrite(digit3, DIGIT_OFF);     digitalWrite(digit4, DIGIT_OFF);   }   while( (millis() - beginTime) < 10) ; //Wait for 20ms to pass before we paint the display again } //Given a number, turns on those segments //If number == 10, then turn off number void lightNumber(int numberToDisplay) { #define SEGMENT_ON  LOW #define SEGMENT_OFF HIGH   switch (numberToDisplay){   case 0:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_ON);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_OFF);     break;   case 1:     digitalWrite(segA, SEGMENT_OFF);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_OFF);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_OFF);     digitalWrite(segG, SEGMENT_OFF);     break;   case 2:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_OFF);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_ON);     digitalWrite(segF, SEGMENT_OFF);     digitalWrite(segG, SEGMENT_ON);     break;   case 3:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_OFF);     digitalWrite(segG, SEGMENT_ON);     break;   case 4:     digitalWrite(segA, SEGMENT_OFF);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_OFF);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_ON);     break;   case 5:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_OFF);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_ON);     break;   case 6:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_OFF);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_ON);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_ON);     break;   case 7:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_OFF);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_OFF);     digitalWrite(segG, SEGMENT_OFF);     break;   case 8:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_ON);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_ON);     break;   case 9:     digitalWrite(segA, SEGMENT_ON);     digitalWrite(segB, SEGMENT_ON);     digitalWrite(segC, SEGMENT_ON);     digitalWrite(segD, SEGMENT_ON);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_ON);     digitalWrite(segG, SEGMENT_ON);     break;   case 10:     digitalWrite(segA, SEGMENT_OFF);     digitalWrite(segB, SEGMENT_OFF);     digitalWrite(segC, SEGMENT_OFF);     digitalWrite(segD, SEGMENT_OFF);     digitalWrite(segE, SEGMENT_OFF);     digitalWrite(segF, SEGMENT_OFF);     digitalWrite(segG, SEGMENT_OFF);     break;   } }

Posted by drkovorkian 3 years ago

security system (not responding after combining ultrasonic sensor code and esp8266 code )

The base of this project is &http;:// I changed according to my uses from above links I tryed by dividing into two parts one for ultrasonic sensor and other for esp8266 they worked fine while separating ultrasonic and buzzer are working in (Tools and wifi module is working in onlt(Tools when i mix ultrasonic and buzzer nothing happening) any idea here is the code #include #include #include #include #define USE_SERIAL Serial #define trigPin 9 #define echoPin 10 #define piezoPin 8 ESP8266WiFiMulti WiFiMulti; int normalDistance; boolean triggered = false; long duration, distance; void setup() {   USE_SERIAL.begin(115200);   pinMode(trigPin, OUTPUT);   pinMode(echoPin, INPUT);   pinMode(piezoPin, OUTPUT);   long duration, distance; while (millis() < 5000) {   digitalWrite(piezoPin, HIGH);       digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance= duration*0.034/2;         normalDistance = distance;       USE_SERIAL.print("Distance: "); USE_SERIAL.println(distance);         digitalWrite(piezoPin, LOW);    for(uint8_t t = 4; t > 0; t--) {         USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);         USE_SERIAL.flush();         delay(1000); } WiFiMulti.addAP("username", "pass"); } } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance= duration*0.034/2; USE_SERIAL.print("Distance: "); USE_SERIAL.println(distance); if (distance < normalDistance-5) {       triggered = true;     }     else {         triggered = false;     }     if (triggered) {     tone(piezoPin, 635);     delay(500);     tone(piezoPin, 912);     delay(250);     if(( == WL_CONNECTED)) {         HTTPClient http;         USE_SERIAL.print("[HTTP] begin...\n");                 http.begin("iftt link.........................."); //HTTP         USE_SERIAL.print("[HTTP] GET...\n");         // start connection and send HTTP header         int httpCode = http.GET();         // httpCode will be negative on error         if(httpCode > 0) {             // HTTP header has been send and Server response header has been handled             USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);             // file found at server             if(httpCode == HTTP_CODE_OK) {                 String payload = http.getString();                 USE_SERIAL.println(payload);             }         } else {             USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());         }         http.end();     }     } } any idea about whats going on Thanks Hemanth

Posted by hemanth kumar reddy 1 year ago

sensitivity of servo that is controlled via android phone

Good day everyone! just like to ask for an assistance on how to make the motion of the servo motor more sensitive with the tilt of the android phone... our program was to control the tilt of the ball maze board via android phone... our code was also given... we are just wondering if this is just the limitation of the Bluetooth connection... we are using amarino application also for the connection between android phone and bluesmirf... here's the code... #include #include float data[3] = {0}; int intdata[3] = {0}; int i = 1; Servo myservo; Servo myservo2; int pos = 0; // MeetAndroid meetAndroid(); // you can define your own error function to catch messages // where not fuction has been attached for MeetAndroid meetAndroid(error); float previousdata = 0; int elapsedtime = 0; void error(uint8_t flag, uint8_t values) {   Serial.print("ERROR: ");   Serial.print(flag); } void setup() {   Serial.begin(115200); //begin serial link @ 9600bps   // register callback functions, which will be called when an associated event occurs.   // - the first parameter is the name of your function (see below)   // - match the second parameter ('A', 'B', 'a', etc...) with the flag on your Android application   meetAndroid.registerFunction(floatValues, 'A');    myservo.attach(9); //Attach the servo to pin eleven   myservo2.attach(10); } void StopCar() {   myservo.write(90);   myservo2.write(90); } void loop() {   myservo.write(90);   myservo2.write(90);   meetAndroid.receive(); // you need to keep this in your loop() to receive events } void floatValues(byte flag, byte numOfValues) {   // create an array where all event values should be stored   // the number of values attached to this event is given by   // a parameter(numOfValues)     // call the library function to fill the array with values (floats)   meetAndroid.getFloatValues(data);     for (int i=0; i<3;i++)   {     meetAndroid.send(data[i]);//Used for debug purposes   }   if (-10<=data[1]<=10)   {      intdata[1] = int(data[1]); //Cast the X axis float value to int      intdata[1] = intdata[1]+10;      pos = intdata[1]*9;      myservo.write(pos);   }   if (-10<=data[0]<=10)   {     intdata[0] = int(data[0]);     intdata[0] = intdata[0]+10;     pos = intdata[0]*9;     myservo.write(pos);   }   if (previousdata == data[0]) { //If the data's still the same (It should have been changed by the meetAndroid.getFloatValues(data) function)      if ((elapsedtime-millis())>=1000) { //If the car has lost the signal more than 1sec, then stop the car         StopCar();      }    }             }

Posted by maevalen 6 years ago


Hello, I'm using ESP8266 WIFI module and GPS module. I have connected to ARDUINO UNO R3 board to read the GPS coordinates and transmit them to webpage using ESP8266 WiFi module connected to router. In my code the page change only when I press F5 (refresh) , and so I can see the change of Coordinates. I want to see the changing results dynamically with out refreshing the webpage. what to I need to do /change in order that it will change automatically? please check my code here or in the attachment  and suggest me the changes. Thanks in advance. CODE: // code starts #include #include SoftwareSerial Serial1(2,3);     //   ESP8266 RX pin 2, TX pin 3. SoftwareSerial gps(11, 10);       //   GPS RX pin 10, TX pin 11.   boolean No_IP=false; String IP=""; String webpage=""; int i=0,k=0; int  gps_status=0; String name=" Name: XXXXXXXX ";   //22 String date="DATE: DD MM YYYY";     //21 String number=" Vehicle No.: ABC 0000";//29 String cordinat="Coordinates:";          //17 String latitude=""; String logitude="";                       String gpsString=""; char *test="$GPGGA"; void check4IP(int t1) {   int t2=millis();   while(t2+t1>millis())   {     while(Serial1.available()>0)     {       if(Serial1.find("WIFI GOT IP"))       {         No_IP=true;       }     }   } } void get_ip() {   IP="";   char ch=0;   while(1)   {     Serial1.println("AT+CIFSR");     while(Serial1.available()>0)     {       if(Serial1.find("STAIP,"))       {         delay(1000);         Serial.print("IP Address:");         while(Serial1.available()>0)         { ;           if(ch=='+')           break;           IP+=ch;         }       }       if(ch=='+')       break;     }     if(ch=='+')     break;     delay(1000);   }   Serial.print(IP);   Serial.print("Port:");   Serial.println(80);   delay(1000); } void connect_wifi(String cmd, int t) {   int temp=0,i=0;   while(1)   {     Serial.println(cmd);     Serial1.println(cmd);     while(Serial1.available()>0)     {       if(Serial1.find("OK"))       {       i=8;       }     }     delay(t);     if(i>5)     break;     i++;   }   if(i==8)   {     Serial.println("OK");   }   else   {   Serial.println("Error");   }   delay(1000); } void setup() {   Serial1.begin(9600);   Serial.begin(9600);   delay(1000);   connect_wifi("AT",1000);   connect_wifi("AT+CWMODE=3",1000);   connect_wifi("AT+CWQAP",1000);    connect_wifi("AT+RST",5000);   check4IP(5000);   if(!No_IP)       {         Serial.println("Connecting Wifi....");         connect_wifi("AT+CWJAP=\"MountPointTech\",\"MpTl2013\"",7000);   //AT+CWJAP="wifi_username","wifi_password"       }       else         {         }       Serial.println("Wifi Connected");       get_ip();       delay(2000);       connect_wifi("AT+CIPMUX=1",100);       connect_wifi("AT+CIPSERVER=1,80",100);       Serial1.end();       Serial.println("Waiting For GPS");       Serial.println("     Signal    ");       delay(2000);       gps.begin(9600);       get_gps();       show_coordinate();       gps.end();       Serial1.begin(9600);       delay(2000);      Serial.println("GPS is Ready");       delay(1000);       Serial.println("System Ready.."); } void loop() {   k=0;   Serial.println("Please Refresh Ur Page");   while(k<1000)   {     k++;    while(Serial1.available())    {     if(Serial1.find("0,CONNECT"))     {       Serial1.end();         gps.begin(9600);       get_gps();       gps.end();       Serial1.begin(9600);       Serial1.flush();       Serial.println("Start Printing");       Send();       show_coordinate();       Serial.println("Done Printing");       delay(5000);       //delay(1000);       k=1200;       break;     }   }   delay(1); } } void gpsEvent() {   gpsString="";   while(1)   {    while (gps.available()>0)                //Serial incoming data from GPS    {     char inChar = (char);      gpsString+= inChar;                    //store incoming data from GPS to temporary string str[]      i++;      if (i < 7)                           {       if(gpsString[i-1] != test[i-1])       //check for right string       {         i=0;         gpsString="";       }      }     if(inChar=='\r')     {      if(i>65)      {        gps_status=1;        break;      }      else      {        i=0;      }     }   }    if(gps_status)     break;   } } void get_gps() {    gps_status=0;    int x=0;    while(gps_status==0)    {     gpsEvent();     int str_lenth=i;     latitude="";     logitude="";     coordinate2dec();         i=0;x=0;     str_lenth=0;    } } void show_coordinate() {         Serial.print("Latitude:");     Serial.println(latitude);     Serial.print("Longitude:");     Serial.println(logitude); } void coordinate2dec() {         //j=0;     String lat_degree="";     for(i=18;i<20;i++)          //extract latitude from string       lat_degree+=gpsString;         String lat_minut="";     for(i=20;i<28;i++)       lat_minut+=gpsString;         String long_degree="";     for(i=30;i<33;i++)          //extract longitude from string       long_degree+=gpsString;           String long_minut="";     for(i=33;i<41;i++)       long_minut+=gpsString;            float minut= lat_minut.toFloat();      minut=minut/60;      float degree=lat_degree.toFloat();      latitude=degree+minut;           minut= long_minut.toFloat();      minut=minut/60;      degree=long_degree.toFloat();      logitude=degree+minut; } void Send() {            webpage = "Welcome to MountPoint Technologies Pvt Ltd";       webpage+=name;       webpage+=date;       webpage+=number;       webpage+=cordinat;       webpage+="Latitude:";       webpage+=latitude;       webpage+="";       webpage+="Longitude:";       webpage+=logitude;       webpage+="";       webpage+= "       webpage+=latitude;       webpage+='+';              //28.612953, 77.231545   //28.612953,77.2293563       webpage+=logitude;       webpage+="\">Click Here for google map ";       sendwebdata();       webpage="";        while(1)          {       Serial.println("AT+CIPCLOSE=0");       Serial1.println("AT+CIPCLOSE=0");       while(Serial1.available())       {         //Serial.print(;         if(Serial1.find("0,CLOSE"))         {           return;         }       }       delay(500);       i++;       if(i>5)       {         i=0;       }       if(i==0)       break;      } } void sendwebdata() {      i=0;      while(1)      {       unsigned int l=webpage.length();       Serial1.print("AT+CIPSEND=0,");       Serial1.println(l+2);       Serial.println(l+2);       Serial.println(webpage);       Serial1.println(webpage);       while(Serial1.available())       {         if(Serial1.find("OK"))         {          return;         }       }             i++;       if(i>5)         i=0;         if(i==0)         break;       delay(200);      } } // end of code.

Posted by shivendrareddy 1 year ago

Super Complicated Code (playing music and moving servos at the same time)

Hey all! I'm trying to make a present for a friend and it's not working out at all :( (due this tuesday). So I ripped up a teddy bear, put some servos in it's arm, and a speaker in it's stomach. I'm trying to use my arduino uno to play tunes over the speaker while make it's arms wobble. My problem is that the song contains delays for getting the notes on beat, which means that I can't have other things going on at once. Is there anything else I can do? I'm stuck with just making it's arms move, then having the tunes play while the arms are still, then having them move again.  Now I did figure out a method to get the servos to move without using a delay function. That's at the very bottom void move(); I know it's probably about the worst way to make servos move slowly without delay but it works. I'm not worried about that. I'm just wondering how am I going to play music and have the servos move at the same time? Thanks! Here's my code.  int speakerPin = 5; int buttonPin = 6; int buttonPress; int buttonCount;  int leds = 13; #include int servospeed(100); Servo servoleft; Servo servoright; int val = 20; int val2; boolean state = true; unsigned long currentMillis; unsigned long previousMillis; int songLength1 = 7000; int songLength2; /*****************************************************************************************************/ /* Smaller value -> all tunes play faster; bigger -> slower. Recommend you don't change this, but instead use playTune() to pass different beatLength values to parseTune() for different songs */ const int beatLength = 50; // Generate a tone by passing a square wave of a certain period to the piezo void playTone(int tone, int duration) {   for (long i = 0; i < duration * 1000L; i += tone * 2) {     digitalWrite(speakerPin, HIGH);     delayMicroseconds(tone);     digitalWrite(speakerPin, LOW);     delayMicroseconds(tone);   } } /* This works out what period, in microseconds, to use for the square wave for a given note. To calculate these, p = ((1 / freq) * 1,000,000) / 2. We divide by 2 because the signal will be HIGH for p microseconds and then LOW for p microseconds. Frequencies for the notes obtained from The range defined below covers 2 octaves from C4 (middle C, or 261.63Hz) to B5 (987.77Hz). Feel free to modify. */ void playNote(char note, int duration, boolean sharp) {   char names[] = {     'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B'         };   int tones[] = {     1915, 1700, 1519, 1432, 1275, 1136, 1014, 956, 851, 758, 716, 636, 568, 506         };   // these are the "sharp" versions of each note e.g. the first value is for "c#"   char names_sharp[] = {     'c', 'd', 'f', 'g', 'a', 'C', 'D', 'F', 'G', 'A'         };   int tones_sharp[] = {     1804, 1607, 1351, 1204, 1073, 902, 804, 676, 602, 536         };   // play the tone corresponding to the note name   if (sharp == false) {     for (int i = 0; i < 14; i++) {       if (names[i] == note) {         playTone(tones[i], duration);       }     }   }   else {     for (int i = 0; i < 10; i++) {       if (names_sharp[i] == note) {         playTone(tones_sharp[i], duration);       }     }   } } /* Take a string representing a tune and parse it to play the notes through the piezo. Parameters: char notes[]: a string that represents the notes of the song. The grammar for parsing the string is described at the top of this file. int beatLength: changes the tempo. Smaller value -> quicker; bigger -> slower boolean loopSong: if true, the song will loop indefinitely (until you press the microswitch) */ void parseTune(char notes[], int beatLength, boolean loopSong) {   boolean play = true;   // 1 iteration of this loop == 1 note played   for (int i = 0; notes[i] != '.' && play == true; i++) { // stop iteration if '.' is the next char       if (notes[i] == ',') { // ',' signifies a rest       // Look at the number (max. 2 digits) following from the ',' to work out the duration of the rest       char len[3];       int count = 0;       while (notes[i+1] >= '0' && notes[i+1] <= '9' && count < 2) {         len[count] = notes[i+1];         count++;         i++;       }       len[count] = '\0';       int duration = atoi(len);       delay(duration * beatLength); // rest duration     }     else { // play the next note, represented by a series of characters e.g. 'c4', 'a#12'       char note = notes[i];       boolean sharp;       // if the next character is a '#' then we must make the note a sharp       if (notes[i+1] == '#') {         i++;         sharp = true;       }       else {         sharp = false;       }       // Look at the number (max. 2 digits) following from the note name to work out the note duration       char len[3];       int count = 0;       while (notes[i+1] >= '0' && notes[i+1] <= '9' && count < 2) {         len[count] = notes[i+1];         count++;         i++;       }       len[count] = '\0';       int duration = atoi(len);       playNote(note, duration * beatLength, sharp);     }     delay(beatLength / 2); // pause between notes   } } // Write your tunes in here using the grammar described at the top of this file. Can have up to 4 tunes. void song1() {   char notes[] = "d4g4g2a2g2f#2e4c4e4a4a2b2a2g2f#4d4f#4b4b2C2b2a2g4e4d2d2e4a4f#4g8,8.";   parseTune(notes, beatLength * 1.25, false); } void song2() {   char notes[] = "b4b4b8b4b4b8b4D4g6a2b12,4C4C4C6C2C4b4b4b2b2b4a4a4b4a8D8b4b4b8b4b4b8b4D4g6a2b12,4,C4C4C6C2C4b4b4b2b2D4D4C4a4g12,8.";   parseTune(notes, beatLength, false); } /**********************************************************************************************************/ void setup() {   pinMode(speakerPin, OUTPUT);   pinMode(buttonPin, INPUT);   pinMode(leds, OUTPUT);   servoleft.attach(8);   servoright.attach(7);   servoleft.write(30);   servoright.write(120);   Serial.begin(9600); } void loop() {   currentMillis = millis();   move();   song1(); } /**************************************/ void move() {   if (currentMillis - previousMillis > 50)   {     if ( val <= 60 && state == true)     {       val++;       servoleft.write(val);       val2 = map(val, 20, 60, 80, 120);       servoright.write(val2);       if (val >= 60)       {         state = false;       }     } //     if (val >= 20 && state == false)     {       val--;       servoleft.write(val);       val2 = map(val, 60, 20, 120, 80);       servoright.write(val2);       if (val <= 20)       {         state = true;       }     }//     previousMillis = currentMillis;     Serial.println(val);   } // if millis }

Posted by HavocRC 3 years ago

Electrolytic vs supercap for CD spotwelder?

I need to make a cheap spotwelder to rebuild some battery packs(e.g,. welding thin nickel strips).My options are:(a) Try to find most of a farad at up to 25V or so on eBay. This could take a while. (Buying new electrolytics in the 0.1F range and above at these voltages is pretty expensive.)(b) Go for supercaps from Digikey (e.g). They've got some 5V 1F models for only a few bucks, and some "fast-discharge" ones for 10x more. Of course, if I go for more than 10V or so, I'll have to build some sort of charge-balancing circuit around the series caps, and I'd rather not unless it's really the best way to go--- though it might be as simple as a resistor in parallel to each cap.(c) Try one of these weirdo "digital supercapacitors" that are all over eBay for the crowd who fill their entire trunk with stereo amps. These look like they're rated at 1-5F at 13.8V and (I would hope) include some sort of charge balancer. Dunno if they're suitable for the sort of instant-discharge I want for a welder, though.I'm having difficulty figuring out:(a) How fast a discharge I need for a spotwelder anyway; I'm going to be using an SCR to trigger it and presumably want the lowest-inductance arrangement I can get, but are we talking milliseconds or microseconds?(b) What can I get out of a supercap? Milliseconds or microseconds? I haven't worked with supercaps before, and most people who seem to be designing circuits with them are using them as batteries.Other random questions:My reference design had 0.5 to 1F at 0-25V through a 600V 50A TO-65 SCR; whatworries me are things like,whose page 3 shows that non-ultra-low-ESR supercaps (e.g., theaffordable ones) seem to have virtually no capacitance for pulsewidths of 10ms or less. (The BestCaps in that datasheet claimsomething like 60% of nominal instead, which is pretty good!)I dunno how narrow the pulse width needs to be to get good welds,but I'm guessing pretty narrow---for example, one guy claimed in that just the difference inputting the SCR on the low side and not the high side (so the triggerfor it didn't have to go through the wires, electrodes, and workpiece)worked a whole lot better, which implies to me that he might betalking microseconds. But I just don't know.]Of course, I also don't know whether I need 0.5 F at 10V or 1F at25V for the things I'm considering.Not to mention---the 50F caps at of which claim ESR's of 0.025 ohm at 1kHz) have these skinny little0.5mm leads on them. How in hell would these leads not be vaporized if Icharged up the cap and then shorted it, as a spot-welder would be doing?(And sure, I could try to attach #4 copper wire to them---somehow---andsend that to the sharpened tips on my welding electrodes, but boy I feelsilly doing that---seems like whatever part of the cap's leads aren'tattached to the heavy wire will just evaporate when shorted, if they canreally dump that kind of current, even if it -is- just for milli-to-microseconds.)The Instructables site has some rambling about using supercaps for CDspotwelders, but it's just rambling---nobody who's actually built oneusing them, for example, or who seems to talk about discharge rates,etc.

Posted by HilaryGage 11 years ago

I need help with this code

Hello, I'm creating a PIR Sensor Alarm with Arduino. I'm using Arduino Uno, PIR Sensor, Breadboard, LED, Piezo Buzzer, TTL JPEG Camera, SD Card and SD Card Module (Breakout Board) I tested my code and it didn't give me any errors. However, the LED and the Buzzer are on all the time, my idea is to have them on once the PIR Sensor detects motions. I know that I'm having problem with the code. Therefore, I'd appreciate it so much if someone could find out which parts of my code should I change. ---------------------------- #include #include #include int pirPin = 7; int ledPin = 8;                // choose the pin for the LED int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11) int minSecsBetweenEmails = 60; // 1 min long lastSend = -minSecsBetweenEmails * 1000l; byte ZERO = 0x00; byte incomingbyte; SoftwareSerial mySerial(2,3);          // Set Arduino pin 2 and 3 as softserial long int a=0x0000,j=0,k=0,count=0,i=0; uint8_t MH,ML; boolean EndFlag=0; File  myFile; void SendResetCmd(); void SetBaudRateCmd(); void SetImageSizeCmd(); void SendTakePhotoCmd(); void SendReadDataCmd(); void StopTakePhotoCmd(); void setup() {   pinMode(pirPin, INPUT);   pinMode(ledPin, OUTPUT);      // declare LED as output   pinMode(pinSpeaker, OUTPUT);   Serial.begin(9600);   Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } mySerial.begin(38400); Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. pinMode(10, OUTPUT); if (!SD.begin(10)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); } void loop() {   long now = millis();   if (digitalRead(pirPin) == HIGH)   {     digitalWrite(ledPin, HIGH);  // turn LED ON     playTone(300, 160);     delay(150);     if (now > (lastSend + minSecsBetweenEmails * 1000l))     {       Serial.println("MOVEMENT");       lastSend = now;     }     else     {       digitalWrite(ledPin, LOW); // turn LED OFF       playTone(0, 0);       delay(300);         Serial.println("Too soon");     }   }   delay(300); } // duration in mSecs, frequency in hertz void playTone(long duration, int freq) {     duration *= 1000;     int period = (1.0 / freq) * 1000000;     long elapsed_time = 0;     while (elapsed_time < duration) {         digitalWrite(pinSpeaker,HIGH);         delayMicroseconds(period / 2);         digitalWrite(pinSpeaker, LOW);         delayMicroseconds(period / 2);         elapsed_time += (period);     } byte a[32]; int ii; SendResetCmd(); delay(4000);                            //Wait 2-3 second to send take picture command SendTakePhotoCmd(); while(mySerial.available()>0) {; } myFile ="pic.jpg", FILE_WRITE); //The file name should not be too long while(!EndFlag) {   j=0;   k=0;   count=0;   SendReadDataCmd();   delay(200); //250 for regular   while(mySerial.available()>0)   {;     k++;     if((k>5)&&(j<32)&&(!EndFlag))     {      a[j]=incomingbyte;      if((a[j-1]==0xFF)&&(a[j]==0xD9))     //tell if the picture is finished      EndFlag=1;      j++;     count++;     }   } for(j=0;j { if(a[j]<0x10) Serial.print("0"); Serial.print(a[j],HEX);           // observe the image through serial port Serial.print(" "); } for(ii=0; ii myFile.write(a[ii]); Serial.println(); i++; } myFile.close(); Serial.print("Finished writing data to file"); while(1); } void SendResetCmd() { mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x26); mySerial.write(ZERO); } void SetImageSizeCmd() { mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x31); mySerial.write(0x05); mySerial.write(0x04); mySerial.write(0x01); mySerial.write(ZERO); mySerial.write(0x19); mySerial.write(0x11); } void SetBaudRateCmd() { mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x24); mySerial.write(0x03); mySerial.write(0x01); mySerial.write(0x2A); mySerial.write(0xC8); } void SendTakePhotoCmd() { mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x36); mySerial.write(0x01); mySerial.write(ZERO); } void SendReadDataCmd() { MH=a/0x100; ML=a%0x100; mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x32); mySerial.write(0x0c); mySerial.write(ZERO); mySerial.write(0x0a); mySerial.write(ZERO); mySerial.write(ZERO); mySerial.write(MH); mySerial.write(ML); mySerial.write(ZERO); mySerial.write(ZERO); mySerial.write(ZERO); mySerial.write(0x20); mySerial.write(ZERO); mySerial.write(0x0a); a+=0x20; } void StopTakePhotoCmd() { mySerial.write(0x56); mySerial.write(ZERO); mySerial.write(0x36); mySerial.write(0x01); mySerial.write(0x03); } --------------------------- Thanks a lot!

Posted by fhussein1 4 years ago

: Arduino + Adafruit wave sheild + IR + Keypad sound board

Hi , was wondering if you could point me in the right direction I'm very new to Arduino I built last year a simple board with adafruit wave shield and added a simple 12 digit key pad to play 12 sounds + power up I have got the codes for the KEYES IR receiver so know the IR is correctly connected and library loaded im trying to integrate the IR code so can change the sounds by IR remote ideally with option of the buttons (if have to loose the buttons and just use remote that's fine) have copied the code below for how it works now just buttons   I found some code for Cylon Pumpkin that works great with just the remote but would also like to integrate the 12 digit keypad Thank you in advance for any help or pointers you can suggest Richard CODE FOR 12 DIGIT BUTTON PRESS /* ADAVOICE is an Arduino-based voice pitch changer plus WAV playback. Fun for Halloween costumes, comic convention getups and other shenanigans! Hardware requirements: - Arduino Uno, Duemilanove or Diecimila (not Mega or Leonardo compatible). - Adafruit Wave Shield - Speaker attached to Wave Shield output - Battery for portable use If using the voice pitch changer, you will also need: - Adafruit Microphone Breakout - 10K potentiometer for setting pitch (or hardcode in sketch) If using the WAV playback, you will also need: - SD card - Keypad, buttons or other sensor(s) for triggering sounds Software requirements: - WaveHC library for Arduino - Demo WAV files on FAT-formatted SD card This example sketch uses a 3x4 keypad for triggering sounds...but with some changes could be adapted to use several discrete buttons, Hall effect sensors, force-sensing resistors (FSRs), I2C keypads, etc. (or if you just want the voice effect, no buttons at all). Connections: - 3.3V to mic amp+, 1 leg of potentiometer and Arduino AREF pin - GND to mic amp-, opposite leg of potentiometer - Analog pin 0 to mic amp output - Analog pin 1 to center tap of potentiometer - Wave Shield output to speaker or amplifier - Matrix is wired to pins A2, A3, A4, A5 (rows) and 6, 7, 8 (columns) - Wave shield is assumed wired as in product tutorial Potentiometer sets playback pitch. Pitch adjustment does NOT work in realtime -- audio sampling requires 100% of the ADC. Pitch setting is read at startup (or reset) and after a WAV finishes playing. POINT SPEAKER AWAY FROM MIC to avoid feedback. Written by Adafruit industries, with portions adapted from the 'PiSpeakHC' sketch included with WaveHC library. */ #include #include SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory FatReader file; // This object represent the WAV file for a pi digit or period WaveHC wave; // This is the only wave (audio) object, -- we only play one at a time #define error(msg) error_P(PSTR(msg)) // Macro allows error messages in flash memory #define ADC_CHANNEL 0 // Microphone on Analog pin 0 // Wave shield DAC: digital pins 2, 3, 4, 5 #define DAC_CS_PORT PORTD #define DAC_CS PORTD2 #define DAC_CLK_PORT PORTD #define DAC_CLK PORTD3 #define DAC_DI_PORT PORTD #define DAC_DI PORTD4 #define DAC_LATCH_PORT PORTD #define DAC_LATCH PORTD5 uint16_t in = 0, out = 0, xf = 0, nSamples; // Audio sample counters uint8_t adc_save; // Default ADC mode // WaveHC didn't declare it's working buffers private or static, // so we can be sneaky and borrow the same RAM for audio sampling! extern uint8_t buffer1[PLAYBUFFLEN], // Audio sample LSB buffer2[PLAYBUFFLEN]; // Audio sample MSB #define XFADE 16 // Number of samples for cross-fade #define MAX_SAMPLES (PLAYBUFFLEN - XFADE) // Remaining available audio samples // Keypad information: uint8_t rows[] = { A2, A3, A4, A5 }, // Keypad rows connect to these pins cols[] = { 6, 7, 8, 9 }, // Keypad columns connect to these pins r = 0, // Current row being examined prev = 255, // Previous key reading (or 255 if none) count = 0; // Counter for button debouncing #define DEBOUNCE 10 // Number of iterations before button 'takes' // Keypad/WAV information. Number of elements here should match the // number of keypad rows times the number of columns, plus one: const char *sound[] = { "Crashing" , "Damaged", "InFlight" , "PowerUp" , // Row 1 = Darth Vader sounds "Brkdown3" , "Brkdown2" , "Brkdown" , "PowerUp" , // Row 2 = Godzilla sounds "Landing", "drain" , "Shutdown" , "PowerUp" , // Row 3 = Dug the dog sounds "Silent", "TakeOff", "Vortex" , "PowerUp" , // Row 4 = Cartoon/SFX sound "PowerUp" }; // Extra item = boot sound //////////////////////////////////// SETUP void setup() { uint8_t i; Serial.begin(9600); // The WaveHC library normally initializes the DAC pins...but only after // an SD card is detected and a valid file is passed. Need to init the // pins manually here so that voice FX works even without a card. pinMode(2, OUTPUT); // Chip select pinMode(3, OUTPUT); // Serial clock pinMode(4, OUTPUT); // Serial data pinMode(5, OUTPUT); // Latch digitalWrite(2, HIGH); // Set chip select high // Init SD library, show root directory. Note that errors are displayed // but NOT regarded as fatal -- the program will continue with voice FX! if(!card.init()) SerialPrint_P("Card init. failed!"); else if(!vol.init(card)) SerialPrint_P("No partition!"); else if(!root.openRoot(vol)) SerialPrint_P("Couldn't open dir"); else { PgmPrintln("Files found:");; // Play startup sound (last file in array). playfile(sizeof(sound) / sizeof(sound[0]) - 1); } // Optional, but may make sampling and playback a little smoother: // Disable Timer0 interrupt. This means delay(), millis() etc. won't // work. Comment this out if you really, really need those functions. TIMSK0 = 0; // Set up Analog-to-Digital converter: analogReference(EXTERNAL); // 3.3V to AREF adc_save = ADCSRA; // Save ADC setting for restore later // Set keypad rows to outputs, set to HIGH logic level: for(i=0; i pinMode(rows[i], OUTPUT); digitalWrite(rows[i], HIGH); } // Set keypad columns to inputs, enable pull-up resistors: for(i=0; i pinMode(cols[i], INPUT); digitalWrite(cols[i], HIGH); } while(wave.isplaying); // Wait for startup sound to finish... startPitchShift(); // and start the pitch-shift mode by default. } //////////////////////////////////// LOOP // As written here, the loop function scans a keypad to triggers sounds // (stopping and restarting the voice effect as needed). If all you need // is a couple of buttons, it may be easier to tear this out and start // over with some simple digitalRead() calls. void loop() { uint8_t c, button; // Set current row to LOW logic state... digitalWrite(rows[r], LOW); // ...then examine column buttons for a match... for(c=0; c if(digitalRead(cols[c]) == LOW) { // First match. button = r * sizeof(cols) + c; // Get button index. if(button == prev) { // Same button as before? if(++count >= DEBOUNCE) { // Yes. Held beyond debounce threshold? if(wave.isplaying) wave.stop(); // Stop current WAV (if any) else stopPitchShift(); // or stop voice effect playfile(button); // and play new sound. while(digitalRead(cols[c]) == LOW); // Wait for button release. prev = 255; // Reset debounce values. count = 0; } } else { // Not same button as prior pass. prev = button; // Record new button and count = 0; // restart debounce counter. } } } // Restore current row to HIGH logic state and advance row counter... digitalWrite(rows[r], HIGH); if(++r >= sizeof(rows)) { // If last row scanned... r = 0; // Reset row counter // If no new sounds have been triggered at this point, and if the // pitch-shifter is not running, re-start it... if(!wave.isplaying && !(TIMSK2 & _BV(TOIE2))) startPitchShift(); } } //////////////////////////////////// HELPERS // Open and start playing a WAV file void playfile(int idx) { char filename[13]; (void)sprintf(filename,"%s.wav", sound[idx]); Serial.print("File: "); Serial.println(filename); if(!, filename)) { PgmPrint("Couldn't open file "); Serial.print(filename); return; } if(!wave.create(file)) { PgmPrintln("Not a valid WAV"); return; }; } //////////////////////////////////// PITCH-SHIFT CODE void startPitchShift() { // Read analog pitch setting before starting audio sampling: int pitch = analogRead(1); Serial.print("Pitch: "); Serial.println(pitch); // Right now the sketch just uses a fixed sound buffer length of // 128 samples. It may be the case that the buffer length should // vary with pitch for better results...further experimentation // is required here. nSamples = 128; //nSamples = F_CPU / 3200 / OCR2A; // ??? //if(nSamples > MAX_SAMPLES) nSamples = MAX_SAMPLES; //else if(nSamples < (XFADE * 2)) nSamples = XFADE * 2; memset(buffer1, 0, nSamples + XFADE); // Clear sample buffers memset(buffer2, 2, nSamples + XFADE); // (set all samples to 512) // WaveHC library already defines a Timer1 interrupt handler. Since we // want to use the stock library and not require a special fork, Timer2 // is used for a sample-playing interrupt here. As it's only an 8-bit // timer, a sizeable prescaler is used (32:1) to generate intervals // spanning the desired range (~4.8 KHz to ~19 KHz, or +/- 1 octave // from the sampling frequency). This does limit the available number // of speed 'steps' in between (about 79 total), but seems enough. TCCR2A = _BV(WGM21) | _BV(WGM20); // Mode 7 (fast PWM), OC2 disconnected TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS20); // 32:1 prescale OCR2A = map(pitch, 0, 1023, F_CPU / 32 / (9615 / 2), // Lowest pitch = -1 octave F_CPU / 32 / (9615 * 2)); // Highest pitch = +1 octave // Start up ADC in free-run mode for audio sampling: DIDR0 |= _BV(ADC0D); // Disable digital input buffer on ADC0 ADMUX = ADC_CHANNEL; // Channel sel, right-adj, AREF to 3.3V regulator ADCSRB = 0; // Free-run mode ADCSRA = _BV(ADEN) | // Enable ADC _BV(ADSC) | // Start conversions _BV(ADATE) | // Auto-trigger enable _BV(ADIE) | // Interrupt enable _BV(ADPS2) | // 128:1 prescale... _BV(ADPS1) | // ...yields 125 KHz ADC clock... _BV(ADPS0); // ...13 cycles/conversion = ~9615 Hz TIMSK2 |= _BV(TOIE2); // Enable Timer2 overflow interrupt sei(); // Enable interrupts } void stopPitchShift() { ADCSRA = adc_save; // Disable ADC interrupt and allow normal use TIMSK2 = 0; // Disable Timer2 Interrupt } ISR(ADC_vect, ISR_BLOCK) { // ADC conversion complete // Save old sample from 'in' position to xfade buffer: buffer1[nSamples + xf] = buffer1[in]; buffer2[nSamples + xf] = buffer2[in]; if(++xf >= XFADE) xf = 0; // Store new value in sample buffers: buffer1[in] = ADCL; // MUST read ADCL first! buffer2[in] = ADCH; if(++in >= nSamples) in = 0; } ISR(TIMER2_OVF_vect) { // Playback interrupt uint16_t s; uint8_t w, inv, hi, lo, bit; int o2, i2, pos; // Cross fade around circular buffer 'seam'. if((o2 = (int)out) == (i2 = (int)in)) { // Sample positions coincide. Use cross-fade buffer data directly. pos = nSamples + xf; hi = (buffer2[pos] << 2) | (buffer1[pos] >> 6); // Expand 10-bit data lo = (buffer1[pos] << 2) | buffer2[pos]; // to 12 bits } if((o2 < i2) && (o2 > (i2 - XFADE))) { // Output sample is close to end of input samples. Cross-fade to // avoid click. The shift operations here assume that XFADE is 16; // will need adjustment if that changes. w = in - out; // Weight of sample (1-n) inv = XFADE - w; // Weight of xfade pos = nSamples + ((inv + xf) % XFADE); s = ((buffer2[out] << 8) | buffer1[out]) * w + ((buffer2[pos] << 8) | buffer1[pos]) * inv; hi = s >> 10; // Shift 14 bit result lo = s >> 2; // down to 12 bits } else if (o2 > (i2 + nSamples - XFADE)) { // More cross-fade condition w = in + nSamples - out; inv = XFADE - w; pos = nSamples + ((inv + xf) % XFADE); s = ((buffer2[out] << 8) | buffer1[out]) * w + ((buffer2[pos] << 8) | buffer1[pos]) * inv; hi = s >> 10; // Shift 14 bit result lo = s >> 2; // down to 12 bits } else { // Input and output counters don't coincide -- just use sample directly. hi = (buffer2[out] << 2) | (buffer1[out] >> 6); // Expand 10-bit data lo = (buffer1[out] << 2) | buffer2[out]; // to 12 bits } // Might be possible to tweak 'hi' and 'lo' at this point to achieve // different voice modulations -- robot effect, etc.? DAC_CS_PORT &= ~_BV(DAC_CS); // Select DAC // Clock out 4 bits DAC config (not in loop because it's constant) DAC_DI_PORT &= ~_BV(DAC_DI); // 0 = Select DAC A, unbuffered DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_DI_PORT |= _BV(DAC_DI); // 1X gain, enable = 1 DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); for(bit=0x08; bit; bit>>=1) { // Clock out first 4 bits of data if(hi & bit) DAC_DI_PORT |= _BV(DAC_DI); else DAC_DI_PORT &= ~_BV(DAC_DI); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); } for(bit=0x80; bit; bit>>=1) { // Clock out last 8 bits of data if(lo & bit) DAC_DI_PORT |= _BV(DAC_DI); else DAC_DI_PORT &= ~_BV(DAC_DI); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); } DAC_CS_PORT |= _BV(DAC_CS); // Unselect DAC if(++out >= nSamples) out = 0; } CODE I FOUND FOR IR  ClyonPumpkin That I want to integrate in above   /* * Text-to-speech example to speak the first n digits of pi. * The number is stored in flash, each digit is spoken one at a time. */ #include #include #include SdReader card;    // This object holds the information for the card FatVolume vol;    // This holds the information for the partition on the card FatReader root;   // This holds the information for the volumes root directory FatReader file;   // This object represent the WAV file for a pi digit or period WaveHC wave;      // This is the only wave (audio) object, since we will only play one at a time char eyesound[13]="eye2.wav"; int mute = 0; /* * Define macro to put error messages in flash memory */ #define error(msg) error_P(PSTR(msg)) // IR Remote code int RECV_PIN = 9;  // pin 11 used by SD card interface so select pin 9 for IR IRrecv irrecv(RECV_PIN); decode_results results; long lasttime=0, lastcode=0, timediff=0; //////////////////////////////////// SETUP void setup() {   // set up Serial library at 9600 bps   Serial.begin(9600);               if (!card.init()) {     error("Card init. failed!");   }   if (!vol.init(card)) {     error("No partition!");   }   if (!root.openRoot(vol)) {     error("Couldn't open dir");   }   irrecv.enableIRIn(); // Start the IR receiver } /////////////////////////////////// LOOP void loop() {   if(mute == 0) playcomplete(eyesound);   // check for keypress happened   if (irrecv.decode(&results;)) {      Serial.println(results.value, HEX);      switch (results.value) {        case 0x83228B74:    // 1          playcomplete("command.wav");          break;        case 0x83228F70:    // 2          playcomplete("entertan.wav");          break;        case 0x8322906F:    // 3          playcomplete("extermin.wav");          break;        case 0x83228A75:    // 4          playcomplete("leader.wav");          break;        case 0x8322847B:    // 5          playcomplete("survivor.wav");          break;         case 0x83227887:    // 6          playcomplete("atention.wav");          break;        case 0x8322629D:    // vol up          mute = 0;         // mute off          break;         case 0x83226E91:    // mute          { Serial.println("mute detected");            timediff=millis()-lasttime;            Serial.println(timediff);            if(lastcode!=results.value || (lastcode==results.value && (timediff>1600)) ) {               if( mute == 0 ) { // is mute off?                  Serial.println("toggle off to on");                  mute = 1;      // turn on                  // delay(1000);    // wait a bit for debounce                  break;                 }               if( mute == 1 ) { // is mute on?                  mute = 0;      // turn off                  Serial.println("toggle on to off");                  break;                 }              } // end if             break;           } // end case        } // end switch      lastcode = results.value;      lasttime = millis();      irrecv.resume();   // Receive the next value   } } /////////////////////////////////// HELPERS /* * print error message and halt */ void error_P(const char *str) {   PgmPrint("Error: ");   SerialPrint_P(str);   sdErrorCheck();   while(1); } /* * print error message and halt if SD I/O error */ void sdErrorCheck(void) {   if (!card.errorCode()) return;   PgmPrint("\r\nSD I/O error: ");   Serial.print(card.errorCode(), HEX);   PgmPrint(", ");   Serial.println(card.errorData(), HEX);   while(1); } /* * Play a file and wait for it to complete */ void playcomplete(char *name) {   playfile(name);   while (wave.isplaying);     // see if an error occurred while playing   sdErrorCheck(); } /* * Open and start playing a WAV file */ void playfile(char *name) {   if (wave.isplaying) {// already playing something, so stop it!     wave.stop(); // stop it   }   if (!, name)) {     PgmPrintln("Couldn't open file ");     Serial.print(name);     return;   }   if (!wave.create(file)) {     PgmPrintln("Not a valid WAV");     return;   }   // ok time to play!; }

Posted by SithLordIII 4 years ago