Does anyone know a way to do a debounce (sketch) without a delay? Answered

I've been trying to mod an xbox 360 controller with an arduino. Unfortunately the switch I have bounces allot and has really been screwing with my sketch. Long story short I've tried allot of different debounces but as soon as i put a delay (); in anywhere in the sketch the controller just shuts down. I don't know why but i think the people who make the game may have some ant-hacking built into the game. Any help is appreciated. Thanks in advance.   

Question by Zaphod Beetlebrox 7 years ago  |  last reply 7 years ago


Debounce arduino push button sketch

Hi, I have done the following sketch and wiring, i have tried all sorts of Debounce code in the sketch but can't get it to stop. Most of the sketches i have read and tried switch the led on with one push and off with the second. i just want it to stay on while being pushed and go off while not being pushed, i am working towards RF or Bluetooth but not until i stop this bounce!

Topic by Senken 4 years ago  |  last reply 4 years ago


How well can you debounce a switch with a cap?

Question by sotsirh194 10 years ago  |  last reply 9 years ago


Does a hall sensor need debouncing with arduino? Answered

Hi, I am trying to measure the time it takes for a wheel to rotate using a hall sensor that was pulled out of a old computer fan. Does this sensor need any debounceing to give accurate readings? http://www.alldatasheet.com/datasheet-pdf/pdf/178883/ANACHIP/AH284.html

Question by David97 5 years ago  |  last reply 5 years 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;   } }

Question by moonwa 6 years ago  |  last reply 6 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.

Topic by dudes 4 years ago  |  last reply 3 years ago


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!

Topic by HavocRC 5 years ago  |  last reply 5 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.

Question by wesm4 2 years ago  |  last reply 2 years ago


how to write a program to control switch and LED

This program is based on How to Program Switch and LED Connected with PIC16F877A. http://www.kynix.com/BlogImage/9.4.7.png    The following code demonstrate, how to write a program that scan the switch status and turn on and off LED. The switch is connected at PORTE bit-0 and LED connected on PORTB bit-0. When switch is read as high state, the LED is turn-on and when switch state is low, LED is turn-off. The switch debouncing rate is 5msec. The code is written in “mikroC PRO for PIC v.5.6.1” IDE and simulation is done with Proteus 8.0 SP0.  PIC16F877A-I/L Datasheet Code in mikroC [code] // switch connected on porte #define SW_AT_PORT PORTE // debounce rate 5msec #define DBOUNCE_RATE 5 // direction signal sbit LED_dir at TRISB.B0; sbit SW_dir at TRISE.B0; // bit labels portb sbit LED at PORTB.B0; sbit SW at PORTE.B0; // old state save flag bit oldstate_one_to_zero; bit oldstate_zero_to_one; void main(void) { // set porta and porte as digital ADCON1 = 0x06; // set direction as output LED_dir = 0; // set direction as input SW_dir = 1; // init LED LED = 0; // init old state flag oldstate_one_to_zero = 0; oldstate_zero_to_one = 0; while(1) { // Detect logical one if(Button(&SW;_AT_PORT, 0, DBOUNCE_RATE, 1)) { // Update flag oldstate_one_to_zero = 1; } // Detect one-to-zero transition if (oldstate_one_to_zero && Button(&SW;_AT_PORT, 0, DBOUNCE_RATE, 0)) { // Update flag oldstate_one_to_zero = 0; // LED ON LED = SW; } // Detect logical zero if(Button(&SW;_AT_PORT, 0, DBOUNCE_RATE, 0)) { // Update flag oldstate_zero_to_one = 1; } // Detect zero-to-one transition if (oldstate_zero_to_one && Button(&SW;_AT_PORT, 0, DBOUNCE_RATE, 1)) { // Update flag oldstate_zero_to_one = 0; // LED OFF LED = SW; } }} [/code]

Topic by narne 1 year ago  |  last reply 1 year ago


Trouble with compiling Arduino program to control two servos with 10 set postions any pointers where I am going wrong?

I am having trouble getting this program to compile I have rewriting from the top but i cant get it to work Code: const int btnRearuppin = 2; const int btnReardownpin = 3; const int btnfrontuppin = 4; const int btnfrontdownpin = 5; const int maxreargear = 10; int btnRearupmode = 0 ,btnReardownmode = 0 ,btnfrontupmode = 0 ,btnfrontdownmode = 0 #include Servo frontGearservo; // create servo object to control a servo int frontgear = 0; // variable to store the servo position Servo reargearservo; int rearGear = 10; const int maxRearGears = 10; const int minRearGears = 1; const int frontgearmax = 2; const int frontgearmin = 1; int btnRearupState; // the current reading from the input pin int lastbtnRearupState = LOW; int btnReardownstate; int lastbtnReardownState = LOW; int btnfrontupstate; int lastbtnfrontupState = LOW; int btnfrontdownstate; int lastbtnfrontdownState = LOW; long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(btnRearuppin,INPUT); pinMode(btnReardownpin,INPUT); pinMode(btnfrontuppin,INPUT); pinMode(btnfrontdownpin,INPUT); frontGearservo.attach(9); reargearservo.attach(10); } //Possible positions of the front derailleur for gears 1 - 8 when on small front sprocket int frontGear1[] = {121, 121, 120, 119, 119, 118, 117, 116, 116, 116}; //Possible positions of the front derailleur for gears 1 - 8 when on large front sprocket int frontGear2[] = { 97, 97, 96, 95, 94, 93, 92, 92, 92, 92}; //Positions of the rear derailleur for gears 1 through 8 int rearGears[] = {132, 125, 116, 105, 96, 84, 73, 62, 55, 49}; void loop() { int reading = digitalRead(btnRearuppin); if(btnRearupState = HIGH) {//you clicked a button // 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 (reading != lastbtnRearupState) { // reset the debouncing timer lastDebounceTime = millis(); if(rearGear < maxRearGears){ //if we still have gears left to shift to rearGear++; //increment to the next gear moveServos(frontGearservo, reargearservo); //tell the servos to move } } } else { btnRearUpPressed = false; //confirm that the button is no longer pressed btnRearUpDebounceCnt = 0; //reset debounce } {boolean moveServos(int front, int rear) //get the new position of the rear servo rearServoPos = rearGears[rear - 1]; //get the new position of the front servo if(front == 1) frontServoPos = frontGear1[rear - 1]; else frontServoPos = frontGear2[rear - 1]; //move the front and rear servos frontServo.write(frontServoPos); rearServo.write(rearServoPos); //wait for the servos to reach their position. delay(100); return true;} Thanks in advance

Question by Talkingriver 7 years ago  |  last reply 2 years ago


Wireless Ping Pong Scoreboard

I want to make a scoreboard for our ping pong table. I currently have a "prototype" loaded on my arduino. It consists of an LED matrix and two momentary button switches. One button adds a point, one button subtracts a point (just in case) and displays the current score on the LED matrix. The plan is to add another LED matrix and two more push buttons, so that each player will have the buttons mounted on their side of the table, to keep their own score, with the LED matrix mounted on the wall. My question is, does anyone know anyway to make the buttons connect to the arduino wirelessly so I don't have to run a ton of wire? I also currently have implemented debouncing on the input buttons and would like to keep that to ensure that when you add or subtract one point, it really is only one point.Thanks!

Question by texpert 8 months ago


Can someone lase help?why does it say ROW0 was not declared in this scope in void setup? Answered

Int keyscan() { const int led2pin = 10; const int led3pin = 9; const int led4pin = 8; const int buzzer = 12; const int LidSw =  13; const int ROW0 = 7; const int ROW1 = 6; const int ROW2 = 5; const int ROW3 = 4; const int COL0 = 3; const int COL1 = 2; const int COL2 = 1;     const int keys[12]={     1,2,3,4,5,6,7,8,9,10,11,12                  };   int r=0;   int c=0;   int keypress=99;   int ColState = 0;    //variable to store column state, 0 = low } void setup() {   pinMode(ROW0, OUTPUT); }   while(keypress=99)   {               for(r=0; r<4; r++)                          //loop for 4 rows     {       digitalWrite(rows[r], HIGH);       for(c=0;c<3;c++)                          //loop for 3 columns       {         ColState =  digitalRead(cols[c]);         if(ColState==1)         {           digitalWrite(rows[r], LOW);  //reset row           tone(BZR, 450, 500);           ColState = 0;                //reset ColState variable           keypress = keys[(r*3)+c];    //identify key pressed           delay(500);                  //debounce           return keypress;         }       }       digitalWrite(rows[r], LOW);     }   } }

Question by endara 6 years ago  |  last reply 6 years ago


Can someone please help?why does it say ROW0 was not declared in this scope in void setup?

Can someone lase help?why does it say ROW0 was not declared in this scope in void setup? int keyscan() { const int led2pin = 10; const int led3pin = 9; const int led4pin = 8; const int buzzer = 12; const int LidSw =  13; const int ROW0 = 7; const int ROW1 = 6; const int ROW2 = 5; const int ROW3 = 4; const int COL0 = 3; const int COL1 = 2; const int COL2 = 1;   const int keys[12]={     1,2,3,4,5,6,7,8,9,10,11,12                  };   int r=0;   int c=0;   int keypress=99;   int ColState = 0;    //variable to store column state, 0 = low } void setup() {   pinMode(ROW0, OUTPUT); }   while(keypress=99)   {              for(r=0; r<4; r++)                          //loop for 4 rows     {       digitalWrite(rows[r], HIGH);       for(c=0;c<3;c++)                          //loop for 3 columns       {         ColState =  digitalRead(cols[c]);         if(ColState==1)         {           digitalWrite(rows[r], LOW);  //reset row           tone(BZR, 450, 500);           ColState = 0;                //reset ColState variable           keypress = keys[(r*3)+c];    //identify key pressed           delay(500);                  //debounce           return keypress;         }       }       digitalWrite(rows[r], LOW);     }   } }

Topic by endara 6 years ago  |  last reply 6 years ago


I need help with coding a car cruisecontrol and Arduino Leonardo (HID)? Answered

Hi all, I have a challenge I cant solve, I need your help! I have a car cruise control lever I want to connect to an Arduino Leonardo and have it act like a keyboard (HID). It has only two wires, 3 push buttons and one toggle switch. I do know the input voltage is 5 volt and every button has its own resistor causing different voltages to come out when used. This way the car computer knows what has been pressed. I have 3 switches: 1: Acc (Cruise Control Accelerate speed) 2: Ret (Cruise Control Retrieve speed) 3: Res (Cruise Control Resume from last speed) I have one toggle Switch: Cruisecontrol ON/OFF I want the ON/OFF to toggle a keyboard character "C" when used. I want button 1 to send a "7" I want button 2 to send an "8" I want button 3 to send a "9" The code should pause after each change (no loop). The 10k Restistor is a pull-up resistor for debounce. Anyone? Project: https://hackaday.io/project/8448-real-dashboard-truck-simulator

Question by Jeroenv26 3 years ago  |  last reply 3 months ago


can anybody tell me why my return command in void loop isnt working?

Int keyscan() {     const int keys[12]={     1,2,3,4,5,6,7,8,9,10,11,12                  };       int r=0;   int c=0;   int keypress=99;   int ColState = 0;    //variable to store column state, 0 = low } const int led2pin = 10; const int led3pin = 9; const int led4pin = 8; const int buzzer = 12; const int LidSw =  13; const int ROW0 = 7; const int ROW1 = 6; const int ROW2 = 5; const int ROW3 = 4; const int COL0 = 3; const int COL1 = 2; const int COL2 = 1;   int keypress=99;    int r=0;   int c=0;   int ColState = 0; void setup() {   pinMode(ROW0, OUTPUT);   pinMode(ROW1, OUTPUT);   pinMode(ROW2, OUTPUT);   pinMode(ROW3, OUTPUT);   pinMode(COL0, INPUT); pinMode(COL1, INPUT);   pinMode(COL2, INPUT);   }   void loop()   {while(keypress=99)   {               for(r=0; r<4; r++)                          //loop for 4 rows     {       digitalWrite(ROW0, HIGH);       for(c=0;c<3;c++)                          //loop for 3 columns       {         ColState =  digitalRead(COL0);         if(ColState==1)         {           digitalWrite(ROW0, LOW);  //reset row           tone(buzzer, 450, 500);           ColState = 0;                //reset ColState variable           keypress = ROW0+COL0;    //identify key pressed           delay(500);                  //debounce         return keypress;         }       }       digitalWrite(ROW0, LOW);     }   } }

Topic by endara 6 years ago  |  last reply 6 years 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!

Question by lukestanmore 5 years ago  |  last reply 3 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 < time_chunk) {             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 < 10 && 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 < 4; 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!"); }

Question by Djandco 4 years ago  |  last reply 4 years ago


1 Button & 6 Neopixel Strips for an Explorers Map

Here is what I am attempting to make.... An interactive display where a user pushes a single button and 1 of the 6 strips lights in a slow sequence, showing the path an explorer took from point a to point b. There are 6 paths, each path will be its own neopixel strip. When the button is pressed a second time, the first strip goes off and the second strip sequentially lights, all the way through the 6 strips, ending at all strips off. I'd like to make the code work so I can use 6 PMW pins as wiring these as one large array is not practical, possible, just not practical. I am using the following: - 1 Arduino Mega 2560, - 1 momentary push button, and - 6 5v neopixel strips (currently with 19 pixels each, end product will be 60 each. - Windows PC and USB to power for testing I am attaching a code that works great with the button pushes for a single strip, and have a different color applied to each "case" so I'd know which one was active. Is a variable for the output pin number IE 3,4,5,6,7,8 the best way, or do I require a different type of condition? Thank you for any help here! Gary // This is a demonstration on how to use an input device to trigger changes on your neo pixels. // You should wire a momentary push button to connect from ground to a digital IO pin.  When you // press the button it will change to a new pixel animation.  Note that you need to press the // button once to start the first animation! #include #define BUTTON_PIN   3    // Digital IO pin connected to the button.  This will be                           // driven with a pull-up resistor so the switch should                           // pull the pin to ground momentarily.  On a high -> low                           // transition the button press logic will execute. #define PIXEL_PIN    6    // Digital IO pin connected to the NeoPixels. #define PIXEL_COUNT 19 // Parameter 1 = number of pixels in strip,  neopixel stick has 8 // Parameter 2 = pin number (most are valid) // Parameter 3 = pixel type flags, add together as needed: //   NEO_RGB     Pixels are wired for RGB bitstream //   NEO_GRB     Pixels are wired for GRB bitstream, correct for neopixel stick //   NEO_KHZ400  400 KHz bitstream (e.g. FLORA pixels) //   NEO_KHZ800  800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); bool oldState = HIGH; int showType = 0; void setup() {   pinMode(BUTTON_PIN, INPUT_PULLUP);   strip.begin();   strip.show(); // Initialize all pixels to 'off' } void loop() {   // Get current button state.   bool newState = digitalRead(BUTTON_PIN);     // Check if state changed from high to low (button press).   if (newState == LOW && oldState == HIGH) {     // Short delay to debounce button.     delay(20);     // Check if button is still low after debounce.     newState = digitalRead(BUTTON_PIN);     if (newState == LOW) {       showType++;       if (showType > 6)         showType=0;       startShow(showType);     }   }   // Set the last button state to the old state.   oldState = newState; } void startShow(int i) {   switch(i){     case 0: colorWipe(strip.Color(0, 0, 0), 0);    // Black/off             break;     case 1: colorWipe(strip.Color(255, 0, 0), 100);  // Red             break;     case 2: colorWipe(strip.Color(0, 255, 0), 100);  // Green             break;     case 3: colorWipe(strip.Color(0, 0, 255), 100);  // Blue             break;     case 4: colorWipe(strip.Color(127,127,127), 100);  // White             break;     case 5: colorWipe(strip.Color(255, 0, 0), 100);  // Red             break;     case 6: colorWipe(strip.Color(0, 0, 255), 100);  // Blue             break;   } } // Fill the dots one after the other with a color void colorWipe(uint32_t c, uint8_t wait) {   for(uint16_t i=0; i       strip.setPixelColor(i, c);       strip.show();       delay(wait);   } }

Topic by grroane123 1 year ago  |  last reply 1 year ago


PINB register on ATtiny45 not working? Answered

I've been programming a pretty simple led driver in Atmel Studio 6 with the attiny45. The idea is that hitting a push button will advance through three different modes of the LEDs, solid, strobe, and fade. When you reach the last mode hitting the button again should reset to the first mode. For some reason the PINB register doesn't seem to be working. Here is the code: #define F_CPU 1000000 #include #include int main(void) { //  Setup PWM TCCR0A |= (1 << COM0A1) | (1 << WGM00) | (1 << WGM01); TCCR0B |= (1 << CS01); DDRB |= (1 << PB0)|(0< PORTB = 0b00010000;   //enable internal pull up int state = 2;  //initialize some variables while(1) {   //int val = PINB3;       if(PINB == 0)   //if button is pressed, increment state variable   {    _delay_ms(100);   //primitive debouncing...     state = state + 1;   }       if(state > 2){  //if we exceed the number of modes, reset state variable       state = 0;   }else   {    state = state;  //probably not necessary, but has solved problems in the past.   } while(state == 0){   //first mode just turns on LEDs at full brightness     OCR0A = 255; } while(state == 1){  //second mode strobes the LEDs     OCR0A = 255;   _delay_ms(35);   OCR0A = 0;   _delay_ms(35); } while(state == 2){    //Third mode fades LEDs      //  Fade LED on    for(i = 0; i < 255; i++)    {     //  Load new value onto OCR0A register to change duty cycle     OCR0A = i;     _delay_ms(5);    }       //  Fade LED off    for(i = 255; i >= 0; i--)    {     OCR0A = i;     _delay_ms(5);    } } } } All of the independent modes work fine, and even the state variable itself is doing what it is supposed to (I know because initializing it to different values gets me the correct mode) but for some reason the PINB register is not getting any kind of response. I am enabling the internal pull up, and then the button connects the I/0 (in this case PB4) to ground which should make the state zero and satisfy the argument of the if statement, but for some reason this is not doing anything. Any ideas? thanks in advanced!

Question by Higgs Boson 5 years ago  |  last reply 5 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:"); root.ls(); // 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(!file.open(root, filename)) { PgmPrint("Couldn't open file "); Serial.print(filename); return; } if(!wave.create(file)) { PgmPrintln("Not a valid WAV"); return; } wave.play(); } //////////////////////////////////// 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 (!file.open(root, name)) {     PgmPrintln("Couldn't open file ");     Serial.print(name);     return;   }   if (!wave.create(file)) {     PgmPrintln("Not a valid WAV");     return;   }   // ok time to play!   wave.play(); }

Topic by SithLordIII 4 years ago


Im repurposing my atx power supply to be a bench Psu. I need help with code please?

In this project. I want to use an arduino mega, 2 lcds, and 6 acs712 current sensing modules and 2 Lm2596 dc step up/down module The set up I have in mind is like so; arduino is powered by ATX stand by power (IF possible) there is a push button which turns on the programing to start the monitoring and also grounds the ATX and GReen wire to supply power to all the rails. This set up will calculate Voltage and current printting them on the lcd's. The constant voltages will be printed on on lcd and the variable voltages on the other lcd. Ive written most of the code. I just want it to make sense. I've added a picture, which my project is based on.. the difference are, im not using I2c bus for lcd, im measuring current, and im printing info on two different lcds. thanks for the help. here is the code #include #define PWROK_PIN 4 // change to w.e pin i end up using connected to green? investigate #define PWRBTN 2 // closing push buttom connection makes it high #define PWRTRANS 6 /*-----( Declare objects )-----*/ // Variables will change: int PWRSTATE = HIGH;         // the current state of the output pin int buttonState;             // the current reading from the input pin int lastButtonState = LOW;   // the previous reading from the input pin // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long lastDebounceTime = 0;  // the last time the output pin was toggled long debounceDelay = 50;    // the debounce time; increase if the output flickers // initialize the libr with the number of the intface pins double sensePinVthree = A0; double sensePinVfive = A1; double sensePinVfivesb = A2; double sensePinVtw = A3; double sensePinVrone = A4; double sensePinvrtwo = A5; //The current double sensePinIthree   = A6; double sensePinIfive   = A7; double sensePinIfivesb = A8; double sensePinItw  = A9; double sensePinIVrone = A10; double sensePinIVrtwo = A11; //setting up default or naming variables. double Voltsthree; double Voltsfive; double Voltsfivesb; double Voltstw; double VoltsVrone; double VoltsVrtwo; double Currentthree; double Currentfive; double Currentfivesb; double Currenttw; double CurrentVrone; double CurrentVrtwo; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); LiquidCrystal lcd2(12, 10, 5, 4, 3, 2); //remove this if not working or glitchy void checkPowerOK(){   // when green is grounded   if (digitalRead(PWROK_PIN) == HIGH) {     lcd.setCursor(4, 1);     lcd.print("ON ");     lcd.setCursor(9, 3);     lcd.print("hello");   }   else if (digitalRead(PWROK_PIN) == LOW) {     lcd.setCursor(8,1);     lcd.print("OFF");   } } void togglePower(){ static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); // If interrupts come faster than 200ms, assume it's a bounce and ignore if (interrupt_time - last_interrupt_time > 500) {    // set the power:   digitalWrite(PWRTRANS, PWRSTATE); //trans is pin 6 } PWRSTATE = !PWRSTATE; last_interrupt_time = interrupt_time;  } void setup() { analogReference (DEFAULT); pinMode(PWRBTN, INPUT); pinMode(PWRTRANS, OUTPUT); attachInterrupt(0, togglePower, RISING); digitalWrite(PWRTRANS, PWRSTATE);     lcd.begin(16, 4);   lcd2.begin(16, 2); // Print a message to the LCD. lcd.setCursor(0,0); //take this out if monitor buggy lcd.print("Bench PSU");// this code be fine lcd.setCursor(0,1); lcd.print("Monitor  V1.0"); lcd.setCursor(0,2); lcd.print("ICE"); lcd.setCursor(4,3); lcd.print("ROBOTICS"); lcd2.begin(16, 2); // replace with the date_time function lcd2.setCursor(0,0); lcd2.print("Hope 4 the best"); lcd2.setCursor(0, 1); lcd2.print("prep 4 the worst"); delay(3000); lcd.clear(); // wipes old message lcd.setCursor(5,0);  lcd.print("Building the Future"); lcd.setCursor(0,1); lcd.print("since   2014"); //Inset the time function somewhere in here lcd.clear(); lcd2.clear(); //lcd.createChar(0, blockChar);     Voltsthree=0; //setting my variables to Zero   Voltsfive=0;   Voltsfivesb=0;   Voltstw=0;   Currentthree=0; //Setting current to Zero on this Lcd   Currentfive=0;   Currentfivesb=0;   Currenttw=0;       VoltsVrone=0; // doing the same but for second lcd   VoltsVrtwo=0;     CurrentVrone=0;// same for current   CurrentVrtwo=0; } void loop () {checkPowerOK(); // check to see if power ok   Voltsthree = ((analogRead(sensePinVthree)) /218.0) *5; // or 7 aalso the 218.0 value will chaange to mine specific   if(Voltsthree <0){     Voltsthree=0;   }   Currentthree =(((analogRead(sensePinIthree)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentthree <0) {     Currentthree=0;   }   Voltsfive = ((analogRead(sensePinVfive)) /218.0) *5;   if(Voltsfive <0){     Voltsfive=0);   }   Currentfive =(((analogRead(sensePinIfive)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentfive <0) {     Currentfive=0;   }   Voltsfivesb =((analogRead(sensePinVfivesb)) /218.0) *5;   if(Voltsfivesb <0){     Voltsfivesb=0;   }   Currentfivesb =(((analogRead(sensePinIfivesb)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentfivesb <0) {     Currentfivesb=0;   }   Voltstw =((analogRead(sensePinVtw)) /218.0) *5;   if(Voltstw <0){     Voltstw= 0;   }   Currenttw =((analogRead(sensePinItw)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currenttw <0){     Currenttw=0;   }     VoltsVrone =((analogRead(sensePinVrone)) /218.0) *5;   if(VoltsVrone <0){     VoltsVrone=0;   }   CurrentVrone =(((analogRead(sensePinIVrone)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(CurrentVrone <0) {     CurrentVrone=0;   }     VoltsVrtwo =((analogRead(sensePinVrtwo)) /218.0) *5;   if(VoltsVrtwo <0){     VoltsVrtwo = 0;   }   CurrentVrtwo =(((analogRead(sensePinIVrtwo)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(CurrentVrtwo <0) {     CurrentVrtwo=0;   }   //1st line   lcd.setCursor(0,0);   lcd.print("                "); //clear the line 1st line   lcd.setCursor(0,0);   lcd.print(Voltsthree);   lcd.setCursor(5,0):   lcd.print("V");   lcd.setCursor(7,0);   lcd.print(Currentthree);   lcd.setCursor(14,0);   lcd.print("A");     //2nd line   lcd.setCursor(0,1);                  // clear and print second line   lcd.print("                ");   lcd.setCursor(0,1);   lcd.print(Voltsfive);     lcd.setCursor(5,1);   lcd.print("V");   lcd.setCursor(7,1);   lcd.print(Currentfive);   lcd.setCursor(14,1);   lcd.print("A");     //3rd line   lcd.setCursor(0,2);           // clear line 3   lcd.print("                ");   lcd.setCursor(0,2);   lcd.print(Voltsfivesb);     lcd.setCursor(5,2);   lcd.print("V");   lcd.setCursor(7,2);   lcd.print(Currentfivesb);   lcd.setCursor(14,2);   lcd.print("A");     //4th line   lcd.setCursor(0,3);           // clear line 4   lcd.print("                ");   lcd.setCursor(0,3);   lcd.print(Voltstw);     lcd.setCursor(5,3);   lcd.print("V");   lcd.setCursor(7,3);   lcd.print(Currenttw);   lcd.setCursor(14,3);   lcd.print("A");     //1st line   lcd.setCursor(0,0);   lcd.print("                "); //clear the line 1st line   lcd.setCursor(0,0);   lcd.print(VoltsVrone.);   lcd.setCursor(5,0);   lcd.print("V");   lcd.setCursor(7,0);   lcd.print(CurrentVrone);   lcd.setCursor(14,0);   lcd.print("A");     //2nd line   lcd2.setCursor(0,1);                   // clear and print second line   lcd.print("                ");   lcd.setCursor(0,1);   lcd.print(VoltsVrtwo);     lcd.setCursor(5,1);   lcd.print("V");   lcd.setCursor(7,1);   lcd.print(CurrentVrtwo);   lcd.setCursor(14,1);   lcd.print("A");   }

Question by icey.hood 3 years ago  |  last reply 3 years ago


Combing Arduino Sketches

Hello, I have a question. I need to combine my code for my Arduino Webserver with the code for my Parallax card reader. When I combine them only the RFID card part works? Can someone help me debunk this. I orginally wanted it to be when someone swiped a valid RFID card, that it would launch the webserver? I don't think that's possible though. Here's my code: #define RFID_ENABLE 2   //to RFID ENABLE #define CODE_LEN 10      //Max length of RFID tag #define VALIDATE_TAG 1  //should we validate tag? #define VALIDATE_LENGTH  200 //maximum reads b/w tag read and validate #define ITERATION_LENGTH 200 //time, in ms, given to the user to move hand away #define START_BYTE 0x0A #define STOP_BYTE 0x0D #include #include char ssid[] = "*******";      //  your network SSID (name) char pass[] = "*********";   // your network password char tag[CODE_LEN];  int readLed = 4; int invalidCardled = 5; int validCardled = 6; int ipCam = 7; int doorLock = 8; int alarm    = 9; int status = WL_IDLE_STATUS; WiFiServer server(1025); void setup() {   Serial.begin(2400);    Serial.println("Please Swipe Your Card.");   pinMode(RFID_ENABLE,OUTPUT);    pinMode(readLed, OUTPUT);   pinMode(validCardled , OUTPUT);   pinMode(invalidCardled, OUTPUT);   pinMode(ipCam, OUTPUT);   pinMode(doorLock, OUTPUT);   pinMode(alarm, OUTPUT);       if (WiFi.status() == WL_NO_SHIELD) {// check for the presence of the shield:     Serial.println("WiFi shield not present");     while(true);        // don't continue    // attempt to connect to Wifi network:   while ( status != WL_CONNECTED) {     Serial.print("Attempting to connect to Network named: ");     Serial.println(ssid);                   // print the network name (SSID);     // Connect to WPA/WPA2 network. Change this line if using open or WEP network:        status = WiFi.begin(ssid, pass);     // wait 10 seconds for connection:     delay(10000);   }   server.begin();                           // start the web server on port 80   printWifiStatus();                        // you're connected now, so print out the status   } }   void loop() {   //Start our main Arduino Loop   enableRFID();   //Enable the RFID card   getRFIDTag();   //Reads the tag   if(isCodeValid()) {  //Validates that the tag is good     disableRFID();  //Puts the RFID reader in to low power mode     sendCode();     //Sends the code read to the serial port     delay(ITERATION_LENGTH);  //Debounce?   } else {     disableRFID();  //Got a incomplete code..   }   Serial.flush();   clearCode();       WiFiClient client = server.available();   // listen for incoming clients   if (client) {                             // if you get a client,     Serial.println("new client");           // print a message out the serial port     String currentLine = "";                // make a String to hold incoming data from the client     while (client.connected()) {            // loop while the client's connected       if (client.available()) {             // if there's bytes to read from the client,         char c = client.read();             // read a byte, then         Serial.write(c);                    // print it out the serial monitor         if (c == '\n') {                    // if the byte is a newline character           // if the current line is blank, you got two newline characters in a row.           // that's the end of the client HTTP request, so send a response:           if (currentLine.length() == 0) {              // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)             // and a content-type so the client knows what's coming, then a blank line:                client.println("HTTP/1.1 200 OK");             client.println("Content-type:text/html");             client.println();                         client.println("");             client.println("");             client.println("Remote Security Solutions");             client.println("");                                     client.println("");             client.println("");                         client.println("");             client.println("");             client.println("Remote Door Control");             client.println("");             client.println("ATTENTION!!! SOMEONE IS TRYING TO ACCESS A SECURED DOOR!!!");                                                             // the content of the HTTP response follows the header:             client.println("");             client.print("PLEASE CHOOSE FROM ONE OF THE FOLLOWING OPTIONS BELOW.");             client.print("Unlock The Door:");             client.print("");             client.print("");             client.print("");             client.print("Lock The Door:");             client.print("");             client.print("");             client.print("");             client.print("Sound The Alarm:");             client.print("");             client.print("");             client.print("");                                               // The HTTP response ends with another blank line:             client.println();             // break out of the while loop:             break;                   }           else {      // if you got a newline, then clear currentLine:             currentLine = "";           }         }             else if (c != '\r') {    // if you got anything else but a carriage return character,           currentLine += c;      // add it to the end of the currentLine         }                 if (currentLine.endsWith("GET /1")) {           digitalWrite(ipCam, HIGH);                       }         if (currentLine.endsWith("GET /2")) {           digitalWrite(ipCam, LOW);                        }          if (currentLine.endsWith("GET /3")) {           digitalWrite(doorLock, HIGH);                       }         if (currentLine.endsWith("GET /4")) {           digitalWrite(doorLock, LOW);                       }          if (currentLine.endsWith("GET /5")) {           digitalWrite(alarm, HIGH);                       }         if (currentLine.endsWith("GET /6")) {           digitalWrite(alarm, LOW);                        }                        }     }     // close the connection:     client.stop();     Serial.println("client disonnected");   } }   /**  * Clears out the memory space for the tag to 0s.  */ void clearCode() {   for(int i=0; i     tag[i] = 0;   } }   /**  * Sends the tag to the computer.  */ void sendCode() {   //This is where I would add a return value (the code) to "validiate" or whatever at.     Serial.print("Valid Card ID Scanned:");      char full_tag[10];     for(int i=0; i       if (i == 9)  //Edits by riley porter         Serial.println(tag[i]);  //This checks to see if its the last byte       else                       //If it is it will print a "new line" so that the codes to jumble together         Serial.print(tag[i]);         } }   /**************************************************************/ /********************   RFID Functions  ***********************/ /**************************************************************/   void enableRFID() {    digitalWrite(RFID_ENABLE, LOW);    digitalWrite(validCardled, HIGH); }   void disableRFID() {    digitalWrite(RFID_ENABLE, HIGH); }   /**  * Blocking function, waits for and gets the RFID tag.  */ void getRFIDTag() {      byte next_byte;   while(Serial.available() <= 0) {}   if((next_byte = Serial.read()) == START_BYTE) {          byte bytesread = 0;     while(bytesread < CODE_LEN) {       if(Serial.available() > 0) { //wait for the next byte           if((next_byte = Serial.read()) == STOP_BYTE) break;                 tag[bytesread++] = next_byte;       digitalWrite(readLed, HIGH);       delay(25);       digitalWrite(validCardled, HIGH);       delay(25);       digitalWrite(invalidCardled, HIGH);       delay(25);       digitalWrite(readLed, LOW);       delay(25);       digitalWrite(validCardled, LOW);       delay(25);       digitalWrite(invalidCardled, LOW);       delay(25);       digitalWrite(validCardled, HIGH);       delay(25);       digitalWrite(validCardled, LOW);       delay(25);       digitalWrite(readLed, HIGH);           }     }                  }    }   /**  * Waits for the next incoming tag to see if it matches  * the current tag.  */ boolean isCodeValid() {   byte next_byte;   int count = 0;   while (Serial.available() < 2) {  //there is already a STOP_BYTE in buffer     delay(1); //probably not a very pure millisecond     if(count++ > VALIDATE_LENGTH) return false;   }   Serial.read(); //throw away extra STOP_BYTE   if ((next_byte = Serial.read()) == START_BYTE) {      byte bytes_read = 0;     while (bytes_read < CODE_LEN) {       if (Serial.available() > 0) { //wait for the next byte                if ((next_byte = Serial.read()) == STOP_BYTE) break;           if (tag[bytes_read++] != next_byte) return false;          digitalWrite(invalidCardled, HIGH);          delay(10);          digitalWrite(invalidCardled, LOW);                       }     }                  }   return true;     }   void printWifiStatus() {   // print the SSID of the network you're attached to:   Serial.print("SSID: ");   Serial.println(WiFi.SSID());   // print your WiFi shield's IP address:   IPAddress ip = WiFi.localIP();   Serial.print("IP Address: ");   Serial.println(ip);   // print the received signal strength:   long rssi = WiFi.RSSI();   Serial.print("signal strength (RSSI):");   Serial.print(rssi);   Serial.println(" dBm");   // print where to go in a browser:   Serial.print("To see this page in action, open a browser to http://");   Serial.println(ip); }

Topic by lonto81 6 years ago  |  last reply 6 years ago


Analog and Digital Inputs for Teensy 3.2 MIDI Programming within Arduino

Been having some trouble with programming my custom potentiometers for my midi controller. I have 12 buttons and 6 knobs. I have it wired correctly and have the sanwa arcade buttons working fine. I'm just having a huge problem adding analog code to my digital code. I'm not sure where to go from here, I have tried over 20 different types of analog code and I'm not sure what I'm doing wrong. Just need a basic potentiometer for reading MIDI. I have the first 1-12 digital inputs on my teensy soldered in for my arcade buttons. For the analog potentiometers I have them soldered on inputs 18-23 or (A4 thru A9) on the Teensy 3.2. I am using Arduino software along with the Teensy loader. Any help would be greatly appreciated, thank you. Here is the code I have thus far. I only have the 19 and 23 analog inputs written in this one at the very end, because I removed the others.  ******** /* Buttons to USB MIDI Example    You must select MIDI from the "Tools > USB Type" menu    To view the raw MIDI data on Linux: aseqdump -p "Teensy MIDI"    This example code is in the public domain. */ #include // the MIDI channel number to send messages const int channel = 1; // Create Bounce objects for each button.  The Bounce object // automatically deals with contact chatter or "bounce", and // it makes detecting changes very simple. Bounce button1 = Bounce(1, 5);  // 5 = 5 ms debounce time Bounce button2 = Bounce(2, 5);  // which is appropriate for good Bounce button3 = Bounce(3, 5);  // quality mechanical pushbuttons Bounce button4 = Bounce(4, 5); Bounce button5 = Bounce(5, 5);  // if a button is too "sensitive" Bounce button6 = Bounce(6, 5);  // to rapid touch, you can Bounce button7 = Bounce(7, 5);  // increase this time. Bounce button8 = Bounce(8, 5); Bounce button9 = Bounce(9, 5); Bounce button10 = Bounce(10, 5); Bounce button11 = Bounce(11, 5); Bounce button12 = Bounce(12, 5); void setup() {   // Configure the pins for input mode with pullup resistors.   // The pushbuttons connect from each pin to ground.  When   // the button is pressed, the pin reads LOW because the button   // shorts it to ground.  When released, the pin reads HIGH   // because the pullup resistor connects to +5 volts inside   // the chip.  LOW for "on", and HIGH for "off" may seem   // backwards, but using the on-chip pullup resistors is very   // convenient.  The scheme is called "active low", and it's   // very commonly used in electronics... so much that the chip   // has built-in pullup resistors!   pinMode(1, INPUT_PULLUP);   pinMode(2, INPUT_PULLUP);   pinMode(3, INPUT_PULLUP);   pinMode(4, INPUT_PULLUP);   pinMode(5, INPUT_PULLUP);   pinMode(6, INPUT_PULLUP);  // Teensy++ 2.0 LED, may need 1k resistor pullup   pinMode(7, INPUT_PULLUP);   pinMode(8, INPUT_PULLUP);   pinMode(9, INPUT_PULLUP);   pinMode(10, INPUT_PULLUP);   pinMode(11, INPUT_PULLUP);   pinMode(12, INPUT_PULLUP);// Teensy 2.0 LED, may need 1k resistor pullup } void loop() {   // Update all the buttons.  There should not be any long   // delays in loop(), so this runs repetitively at a rate   // faster than the buttons could be pressed and released.   button1.update();   button2.update();   button3.update();   button4.update();   button5.update();   button6.update();   button7.update();   button8.update();   button9.update();   button10.update();   button11.update();   button12.update();   // Check each button for "falling" edge.   // Send a MIDI Note On message when each button presses   // Update the Joystick buttons only upon changes.   // falling = high (not pressed - voltage from pullup resistor)   //           to low (pressed - button connects pin to ground)   if (button1.fallingEdge()) {     usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4   }   if (button2.fallingEdge()) {     usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4   }   if (button3.fallingEdge()) {     usbMIDI.sendNoteOn(63, 99, channel);  // 63 = D#4   }   if (button4.fallingEdge()) {     usbMIDI.sendNoteOn(64, 99, channel);  // 64 = E4   }   if (button5.fallingEdge()) {     usbMIDI.sendNoteOn(65, 99, channel);  // 65 = F4   }   if (button6.fallingEdge()) {     usbMIDI.sendNoteOn(66, 99, channel);  // 66 = F#4   }   if (button7.fallingEdge()) {     usbMIDI.sendNoteOn(67, 99, channel);  // 67 = G4   }   if (button8.fallingEdge()) {     usbMIDI.sendNoteOn(68, 99, channel);  // 68 = G#4   }   if (button9.fallingEdge()) {     usbMIDI.sendNoteOn(69, 99, channel);  // 69 = A5   }   if (button10.fallingEdge()) {     usbMIDI.sendNoteOn(70, 99, channel);  // 70 = A#5   }   if (button11.fallingEdge()) {     usbMIDI.sendNoteOn(71, 99, channel);  // 71 = B5   }   if (button12.fallingEdge()) {     usbMIDI.sendNoteOn(72, 99, channel);  // 72 = C4   // Check each button for "rising" edge   // Send a MIDI Note Off message when each button releases   // For many types of projects, you only care when the button   // is pressed and the release isn't needed.   // rising = low (pressed - button connects pin to ground)   //          to high (not pressed - voltage from pullup resistor)    }   if (button1.risingEdge()) {     usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4   }   if (button2.risingEdge()) {     usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4   }   if (button3.risingEdge()) {     usbMIDI.sendNoteOff(63, 0, channel);  // 63 = D#4   }   if (button4.risingEdge()) {     usbMIDI.sendNoteOff(64, 0, channel);  // 64 = E4   }   if (button5.risingEdge()) {     usbMIDI.sendNoteOff(65, 0, channel);  // 65 = F4   }   if (button6.risingEdge()) {     usbMIDI.sendNoteOff(66, 0, channel);  // 66 = F#4   }   if (button7.risingEdge()) {     usbMIDI.sendNoteOff(67, 0, channel);  // 67 = G4   }   if (button8.risingEdge()) {     usbMIDI.sendNoteOff(68, 0, channel);  // 68 = G#4   }   if (button9.risingEdge()) {     usbMIDI.sendNoteOff(69, 0, channel);  // 69 = A5   }   if (button10.risingEdge()) {     usbMIDI.sendNoteOff(70, 0, channel);  // 70 = A#5   }   if (button11.risingEdge()) {     usbMIDI.sendNoteOff(71, 0, channel);  // 71 = B5   }   if (button12.risingEdge()) {     usbMIDI.sendNoteOff(72, 0, channel);  // 72 = C4   // MIDI Controllers should discard incoming MIDI messages.   // http://forum.pjrc.com/threads/24179-Teensy-3-Ableton-Analog-CC-causes-midi-crash   while (usbMIDI.read()) {     // ignore incoming messages   } } // read the input on analog pin 19:   int sensorValue = analogRead(A5);   // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):   float voltage = sensorValue * (5.0 / 1023.0);   // print out the value you read:   Serial.println(voltage); } // read the input on analog pin 23:   int sensorValue = analogRead(A9);   // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):   float voltage = sensorValue * (5.0 / 1023.0);   // print out the value you read:

Topic by abissmusic 1 year ago  |  last reply 1 year ago


Is there anyway that someone could make me a .hex file from this .asm, or at least tell me how?

Hey, I have a .asm file. I have tried MPLAB, but I am not doing it right. ;-----------------------------------------------------------------------; ; BINCLOCK.ASM A clock that displays in bcd numbers ; ;-----------------------------------------------------------------------;         LIST P=16F84 ; tells which processor is used         INCLUDE "p16f84.inc" ; defines various registers etc. Look it over.         ERRORLEVEL -224 ; supress annoying message because of tris         __CONFIG _PWRTE_ON & _LP_OSC & _WDT_OFF ; configuration switches             CBLOCK 0CH                 sec ; seconds digit                 sec10 ; 10's of second digit                 mins ; minutes digit                 min10 ; 10's of minutes digit                 hr ; hours digit                 hr10 ; 10's of hours digit                 w_temp ; holds W during interrupt                 status_temp ; holds STATUS during interrupt                 fsr_temp ; holds FSR during interrupt                 button ; holds mask for pushbuttons               ENDC ;-----------------------------------------------------------------------; ; Here are some DEFINEs which give 'names' to pushbutton port bits ; ;-----------------------------------------------------------------------;             #DEFINE SETPB PORTB, 4             #DEFINE SELECTPB PORTB, 5             #DEFINE SHOWPB PORTB, 6             ORG 0 ; start at location 0             goto main ; jump over to main routine ORG 4 goto isr ; jump to interrupt routine ;-----------------------------------------------------------------------; ; High limit + 1 of digits at position W ; ;-----------------------------------------------------------------------; sethi: addwf PCL, f dt H'A',H'6',H'A',H'6',H'A',H'3' ;-----------------------------------------------------------------------; ; Delay routines ; ;-----------------------------------------------------------------------; msec250: ; enter here to delay for 250 milliseconds movlw D'250' nmsec: ; delay for # msec in W on entry nop ; each nop is 0.122 milliseconds nop nop ; each total loop is 8 X 0.122 = 0.976 msec nop addlw H'FF' ; same as subtracting 1 from W btfss STATUS, Z ; skip if result is zero goto nmsec ; this is 2 X 0.122 msec return ; back to calling point ;-----------------------------------------------------------------------; ; Delay for one second ; ;-----------------------------------------------------------------------; onesecond: ; a subroutine that delays for 1 seconds call msec250 call msec250 call msec250 call msec250 return ;-----------------------------------------------------------------------; ; Put value in W on LEDs for 1 second ; ;-----------------------------------------------------------------------; sendnbr: movwf PORTB ; light LEDs call onesecond ; wait 1 second clrf PORTB ; clear the LEDs movlw D'100' ; pause for 0.1 sec call nmsec return ;-----------------------------------------------------------------------; ; Send the current time out LEDs ; ;-----------------------------------------------------------------------; disptime: movf hr10, W call sendnbr movf hr, W call sendnbr movf min10, W call sendnbr movf mins, W call sendnbr return ;-----------------------------------------------------------------------; ; Wait until selected button is released ; ;-----------------------------------------------------------------------; waitup6: ; wait for show pushbutton up movlw B'01000000' ; RB6 mask movwf button goto wait waitup5: ; wait for select pushbutton up movlw B'00100000' ; RB5 mask movwf button goto wait waitup4: ; wait for set pushbutton up movlw B'00010000' ; RB4 mask movwf button wait: movf button, W ; mask into W andwf PORTB, W btfsc STATUS, Z ; skip if not zero (released) goto wait movlw D'10' call nmsec ; wait 10 msec for debounce movf button, W ; check for release again andwf PORTB, W btfsc STATUS, Z ; skip if selected button released goto wait return ; yes, finished ;-----------------------------------------------------------------------; ; Initilization Subroutine ; ;-----------------------------------------------------------------------; init: movlw B'0000000' ; all outputs port A tris PORTA movlw B'01110000' ; RB4 - RB6 inputs, others outputs tris PORTB ; on port B movlw H'0' ; all low (off) movlw PORTB movlw B'00000100' ; pull-ups enabled ; prescaler assigned to TMR0 ; prescaler set to 1:32 ; rolls over each second option movlw 0 movwf hr10 movlw H'9' ; initialize hrs, mins and secs movwf hr ; Do this before interrupts are movlw H'5' ; turned on because isr also acts movwf min10 ; on these registers movlw H'0' movwf mins movwf sec10 movwf sec movlw B'10100000' ; GIE & T0IE set, T0IF cleared movwf INTCON return ;-----------------------------------------------------------------------; ; Interrupt routine, increments time by one second (BCD) ; ;-----------------------------------------------------------------------; isr: movwf w_temp ; save W swapf STATUS,W ; save status movwf status_temp ; without changing flags swapf FSR,W ; save FSR movwf fsr_temp ; without changing flags movlw sec ; point at sec register movwf FSR newdigit: incf INDF, f ; current digit up one movlw sec ; get difference between sec and FSR subwf FSR, W call sethi ; use to get high limit + 1 subwf INDF, W ; reached that number yet? btfss STATUS, Z ; skip over if yes goto restore ; else exit isr clrf INDF ; set current digit to 0 incf FSR, f ; point at next digit btfss hr10, 1 ; has hr10 reached 2? goto newdigit ; no, increment the next digit btfss hr, 2 ; has hr reached 4? goto newdigit ; no clrf hr ; yes, set hour to 00 clrf hr10 ; and hour 10 restore: swapf status_temp,W ; get original status back movwf STATUS ; into status register swapf fsr_temp,W ; get original fsr back movwf FSR ; into status register swapf w_temp,f ; old no flags trick again swapf w_temp,W ; to restore W bcf INTCON,T0IF ; clear the TMR0 interrupt flag retfie ; finished reset GIE ;-----------------------------------------------------------------------; ; Increment and display digit pointed to by FSR ; ;-----------------------------------------------------------------------; updigit: incf INDF, f ; selected digit up one movlw mins ; set up to subtract mins address subwf FSR, W ; from address of current digit call sethi ; get maximum of digit + 1 into W subwf INDF, W ; is it = to current digit value? btfsc STATUS, Z ; gives zero if yes, skip if no clrf INDF ; reset value of digit to zero movf INDF, W ; get current value and .. movwf PORTB ; display it call onesecond ; pause for 1 second return ;-----------------------------------------------------------------------; ; increment selected digit until select pressed ; ;-----------------------------------------------------------------------; setdigit: movwf PORTB btfss SETPB ; set pressed? call updigit ; yes btfsc SELECTPB ; check if select pressed goto $ -3 ; repeat till select pressed again call waitup5 ; make sure select released incf FSR, f return ;-----------------------------------------------------------------------; ; Select and increment digits ; ;-----------------------------------------------------------------------; select: bcf INTCON, GIE ; no interrupts while setting time movlw mins ; point at minutes register movwf FSR call waitup5 ; wait on select pushbutton up movlw B'00000001' ; light right LED (mins) call setdigit movlw B'00000010' ; light min10 LED call setdigit movlw B'00000100' ; light hr LED call setdigit movlw B'00001000' ; hr10 LED on call setdigit clrf PORTB ; clear LEDs bsf INTCON, GIE ; enable interrupts again return ;-----------------------------------------------------------------------; ; The main routine ; ;-----------------------------------------------------------------------; main: call init ; set up initial conditions loop: btfss SHOWPB ; check for show pushbutton call disptime ; display the time btfss SELECTPB ; check for select call select goto loop ; do forever end     

Question by 16zzundel5 7 years ago  |  last reply 7 years ago