What is wrong with the program...? Answered

I am trying to make a quizbowl(jepoardy) buzzer system, and I am using an arduino.  I have a program that does a few buttons, and I can add more buttons by just adding more if else, but when I clear it( pin0 and pin3) you have to wait about a second to buzz in, otherwise it doesn't register.  Just a note: the buttons are set up so that I can use 6 pins and control 9 buttons.  It is hard to explain but the pins are setup so that two of the pins sense the current to correspond to the button pressed.  I don't know what else to add, I think it is that is doesn't register that the clear button is no longer pressed, but that might not be it.  Here is the program: const int pin0 = 14; const int pin1 = 15; const int pin2 = 16; const int pin3 = 17; const int pin4 = 18; const int pin5 = 19; const int led1 = 13; const int led2 = 12; const int led3 = 11; int pin0s = 0; int pin1s = 0; int pin2s = 0; int pin3s = 0; int pin4s = 0; int pin5s = 0; void setup() { pinMode(pin0, INPUT); pinMode(pin1, INPUT); pinMode(pin2, INPUT); pinMode(pin3, INPUT); pinMode(pin4, INPUT); pinMode(pin5, INPUT); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); } void loop () {   pin0s = digitalRead(pin0);   pin1s = digitalRead(pin1);   pin2s = digitalRead(pin2);   pin3s = digitalRead(pin3);   pin4s = digitalRead(pin4);   pin5s = digitalRead(pin5);     if (pin1s == HIGH && pin3s == HIGH)   {     digitalWrite(led1, HIGH);     while(pin0s == LOW || pin3s == LOW)     {       pin0s = digitalRead(pin0);       pin3s = digitalRead(pin3);     }     digitalWrite(led1,LOW);     while(pin0s == HIGH || pin3s == HIGH)     {       pin0s = digitalRead(pin0);       pin1s = digitalRead(pin1);       pin2s = digitalRead(pin2);       pin3s = digitalRead(pin3);       pin4s = digitalRead(pin4);       pin5s = digitalRead(pin5);     }       pin0s = digitalRead(pin0);   pin1s = digitalRead(pin1);   pin2s = digitalRead(pin2);   pin3s = digitalRead(pin3);   pin4s = digitalRead(pin4);   pin5s = digitalRead(pin5);     }  else if(pin3s == HIGH && pin2s == HIGH)  {     digitalWrite(led2, HIGH);     while(pin0s == LOW || pin3s == LOW)     {       pin0s = digitalRead(pin0);       pin3s = digitalRead(pin3);     }     digitalWrite(led2,LOW);     while(pin0s == HIGH || pin3s == HIGH)     {       pin0s = digitalRead(pin0);       pin1s = digitalRead(pin1);       pin2s = digitalRead(pin2);       pin3s = digitalRead(pin3);       pin4s = digitalRead(pin4);       pin5s = digitalRead(pin5);     }       pin0s = digitalRead(pin0);   pin1s = digitalRead(pin1);   pin2s = digitalRead(pin2);   pin3s = digitalRead(pin3);   pin4s = digitalRead(pin4);   pin5s = digitalRead(pin5); } else if (pin0s == HIGH && pin4s == HIGH) {     digitalWrite(led3, HIGH);     while(pin0s == LOW || pin3s == LOW)     {       pin0s = digitalRead(pin0);       pin3s = digitalRead(pin3);     }     digitalWrite(led3,LOW);     while(pin0s == HIGH || pin3s == HIGH)     {       pin0s = digitalRead(pin0);       pin1s = digitalRead(pin1);       pin2s = digitalRead(pin2);       pin3s = digitalRead(pin3);       pin4s = digitalRead(pin4);       pin5s = digitalRead(pin5);     }       pin0s = digitalRead(pin0);   pin1s = digitalRead(pin1);   pin2s = digitalRead(pin2);   pin3s = digitalRead(pin3);   pin4s = digitalRead(pin4);   pin5s = digitalRead(pin5); }} Please help! Thanks in Advance!

Question by JaredsProjects   |  last reply


Arduino dimmer code

I am creating a 6 channel light dimmer system using an arduino duemilanove. I want to control it using push buttons to  dim and brighten. I want to setup 6 buttons to corresponding to the 6 channels. Then I want an up, down, and on/off button. When you hold down a channel button, it activates to up and down button to control that channel. I want the on/off button to turn all channels to full brightness or completely off. I am basing the dimming part of the circuit off of this instructable: https://www.instructables.com/id/Arduino-Powered-Musical-Christmas-Lights/. Anyway, I have ordered an arduino but want someone to check out my code before I build this. I have made many things but am new to writing my own code so I would appreciate any improvements and friendly advice. Here is the code: int light1pin=3; int light2pin=5; int light3pin=6; int light4pin=9; int light5pin=10; int light6pin=11; int button1pin=0; int button2pin=1; int button3pin=2; int button4pin=4; int button5pin=7; int button6pin=8; int uppin=12; int downpin=13; int onoffpin=14; int onoff=0; int light1=255; int light2=255; int light3=255; int light4=255; int light5=255; int light6=255; int interval=1; void setup() {   pinMode(light1pin, OUTPUT);   pinMode(light2pin, OUTPUT);   pinMode(light3pin, OUTPUT);   pinMode(light4pin, OUTPUT);   pinMode(light5pin, OUTPUT);   pinMode(light6pin, OUTPUT);   pinMode(button1pin, INPUT);   pinMode(button2pin, INPUT);   pinMode(button3pin, INPUT);   pinMode(button4pin, INPUT);   pinMode(button5pin, INPUT);   pinMode(button6pin, INPUT);   pinMode(uppin, INPUT);   pinMode(downpin, INPUT);   pinMode(onoffpin, INPUT); } void loop() {   analogWrite(light1pin, light1);   analogWrite(light2pin, light2);   analogWrite(light3pin, light3);   analogWrite(light4pin, light4);   analogWrite(light5pin, light5);   analogWrite(light6pin, light6);   if (digitalRead(onoffpin) == HIGH && onoff == 0){     light1=255;     light2=255;     light3=255;     light4=255;     light5=255;     light6=255;     onoff=1;   }   if (digitalRead(onoffpin) ==  HIGH && onoff == 1) {     light1=0;     light2=0;     light3=0;     light4=0;     light5=0;     light6=0;     onoff=0;   }   if (digitalRead(button1pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light1 < 255){       light1 = light1 + interval;     }     if (digitalRead(downpin) == HIGH && light1 > 0){       light1 = light1 - interval;     }   }   if (digitalRead(button2pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light2 < 255){       light2 = light2 + interval;     }     if (digitalRead(downpin) == HIGH && light2 > 0){       light2 = light2 - interval;     }   }   if (digitalRead(button3pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light3 < 255){       light3 = light3 + interval;     }     if (digitalRead(downpin) == HIGH && light3 > 0){       light3 = light3 - interval;     }   }   if (digitalRead(button4pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light4 < 255){       light4 = light4 + interval;     }     if (digitalRead(downpin) == HIGH && light4 > 0){       light4 = light4 - interval;     }   }   if (digitalRead(button5pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light5 < 255){       light5 = light5 + interval;     }     if (digitalRead(downpin) == HIGH && light5 > 0){       light5 = light5 - interval;     }   }   if (digitalRead(button6pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light6 < 255){       light6 = light6 + interval;     }     if (digitalRead(downpin) == HIGH && light6 > 0){       light6 = light6 - interval;     }   } }

Topic by bmrodgers3365   |  last reply


Arduino light dimmer code? Answered

I am creating a 6 channel light dimmer system using an arduino duemilanove. I want to control it using push buttons to  dim and brighten. I want to setup 6 buttons to corresponding to the 6 channels. Then I want an up, down, and on/off button. When you hold down a channel button, it activates to up and down button to control that channel. I want the on/off button to turn all channels to full brightness or completely off. I am basing the dimming part of the circuit off of this instructable: https://www.instructables.com/id/Arduino-Powered-Musical-Christmas-Lights/. Anyway, I have ordered an arduino but want someone to check out my code before I build this. I have made many things but am new to writing my own code so I would appreciate any improvements and friendly advice.  Here is the code: int light1pin=3; int light2pin=5; int light3pin=6; int light4pin=9; int light5pin=10; int light6pin=11; int button1pin=0; int button2pin=1; int button3pin=2; int button4pin=4; int button5pin=7; int button6pin=8; int uppin=12; int downpin=13; int onoffpin=14; int onoff=0; int light1=255; int light2=255; int light3=255; int light4=255; int light5=255; int light6=255; int interval=1; void setup() {   pinMode(light1pin, OUTPUT);   pinMode(light2pin, OUTPUT);   pinMode(light3pin, OUTPUT);   pinMode(light4pin, OUTPUT);   pinMode(light5pin, OUTPUT);   pinMode(light6pin, OUTPUT);   pinMode(button1pin, INPUT);   pinMode(button2pin, INPUT);   pinMode(button3pin, INPUT);   pinMode(button4pin, INPUT);   pinMode(button5pin, INPUT);   pinMode(button6pin, INPUT);   pinMode(uppin, INPUT);   pinMode(downpin, INPUT);   pinMode(onoffpin, INPUT); } void loop() {   analogWrite(light1pin, light1);   analogWrite(light2pin, light2);   analogWrite(light3pin, light3);   analogWrite(light4pin, light4);   analogWrite(light5pin, light5);   analogWrite(light6pin, light6);   if (digitalRead(onoffpin) == HIGH && onoff == 0){     light1=255;     light2=255;     light3=255;     light4=255;     light5=255;     light6=255;     onoff=1;   }   if (digitalRead(onoffpin) ==  HIGH && onoff == 1) {     light1=0;     light2=0;     light3=0;     light4=0;     light5=0;     light6=0;     onoff=0;   }   if (digitalRead(button1pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light1 < 255){       light1 = light1 + interval;     }     if (digitalRead(downpin) == HIGH && light1 > 0){       light1 = light1 - interval;     }   }   if (digitalRead(button2pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light2 < 255){       light2 = light2 + interval;     }     if (digitalRead(downpin) == HIGH && light2 > 0){       light2 = light2 - interval;     }   }   if (digitalRead(button3pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light3 < 255){       light3 = light3 + interval;     }     if (digitalRead(downpin) == HIGH && light3 > 0){       light3 = light3 - interval;     }   }   if (digitalRead(button4pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light4 < 255){       light4 = light4 + interval;     }     if (digitalRead(downpin) == HIGH && light4 > 0){       light4 = light4 - interval;     }   }   if (digitalRead(button5pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light5 < 255){       light5 = light5 + interval;     }     if (digitalRead(downpin) == HIGH && light5 > 0){       light5 = light5 - interval;     }   }   if (digitalRead(button6pin) == HIGH) {     if (digitalRead(uppin) == HIGH && light6 < 255){       light6 = light6 + interval;     }     if (digitalRead(downpin) == HIGH && light6 > 0){       light6 = light6 - interval;     }   } }

Question by bmrodgers3365   |  last reply


arduino code stalls in mid program?

I'm using a rotary encoder, and to test it, I wrote a program with an interrupt on pin two that counts (with a state machine for the direction and two parts per cycle), but whenever I spin the encoder too fast, the program simple stops sending values.  Its running on an uno with a FTDI friend (becaust the serial chip on the board itself is fried), with a 32 cycle per revolution encoder on pins two and seven.  The encoder is standard quadrature, with an optical pickup and slotted disk.  It works fine normally, the problem only occours when it's spun too fast.  I will need it to spin quickly for my application.   I tried closing and reopening serial communications, and it didn't help, I have to reset it to make it work again. here's the code: #define ENCA 2 #define ENCB 7 int r = 0; float pos = 0; void setup(){   Serial.begin(9600);    pinMode(ENCA, INPUT);    pinMode(ENCB, INPUT);    digitalWrite(ENCA, HIGH);    digitalWrite(ENCB, HIGH);      attachInterrupt(0, epos, CHANGE); } void loop(){ delay(1); } void epos(void){   r = 1;   if(digitalRead(2) == HIGH){    if(digitalRead(7) == LOW){      while(r == 1){        delay(0.1);        if(digitalRead(2) == LOW){          r = 0;        } else {          if(digitalRead(7) == HIGH){            pos = pos + 0.015625;            r = 0;          }}}                                     }    else {      while(r == 1){        delay(0.1);        if(digitalRead(2) == LOW){          r = 0;        } else {          if(digitalRead(7) == LOW){            pos = pos - 0.015625;            r = 0;          }}}    }    Serial.println(pos); }else{   r = 1;    if(digitalRead(7) == HIGH){      while(r == 1){        delay(0.1);        if(digitalRead(2) == HIGH){          r = 0;        } else {          if(digitalRead(7) == LOW){            pos = pos + 0.015625;            r = 0;          }}}                                     }    else {      while(r == 1){        delay(0.1);        if(digitalRead(2) == HIGH){          r = 0;        } else {          if(digitalRead(7) == HIGH){            pos = pos - 0.015625;            r = 0;          }}}    }    Serial.println(pos); }}

Question by jduffy54   |  last reply


This arduino code does not work as expected, any help? there seems to be an issue with the digitalWrite function. Answered

Recently, I wanted to make a laboratory grade linear semi-precision power supply using an Arduino, LCD, some comparators, and MOSFETs. Idealistically, I want measurements to be 3 significant figures of precision (0.1% accuracy @ 30V), voltages as high as 30V, and max current of 10A. The power supply is most likely going to be just a single regulated output, maybe if I feel lucky I will make 2 regulated outputs once I get the darn Arduino code to work. The Arduino's job is to simply set and read the output voltage, and is not part of the control loop. That is what the comparators are for. (I learned the hard way that using the Arduino within the control loop just results in parasitic oscillations because the Arduino is a clocked device and can only self correct at timed intervals.) Anyway, below is the code. I made explanations of all portions of it as clear as possible, and I also give the wiring used for the LCD, 4 buttons, and analog inputs used to set and read the voltage and current. However, the issue arises when I upload the code, the setVI button does not work unless I press both it and the RS button at same time. I made the many of the integers display in the serial output to diagnosing easier hopefully. I can see the setVI integer and my dudd integer only goes HIGH when  either it and the RS buttons are pressed simultaneously, or when the RS butten is held down for a long enough time. However, as far as I am aware, nowhere in the code do I manipulate that code so setVI goes HIGH dependant on other buttons, so I am bewildered by this parasitic phenomenon. Is my Arduino MEGA broken? I had a similar problem in the past, where I had multiple analogRead statements It strangely seemed to factor in the outputs of other input pins. Anyway, here is the code. Maybe someone could upload it and tell me if it functions properly on their arduino? That would help me determine if it is indeed a software issue. (p.s. I use an Arduino ripoff called the Funduino, but it is not broken in any way, I don't think?) Any and all help would be greatly appreciated, thank you in advance, -Max-. p.s. To make the code below legible, please copy/paste it in an IDE or in notepad and convert it into a monospaced font, it will make it very easy to follow. //---------------------------------------------------------------------------------------------------------------// /* Arduino Software for lab power supply. Wireing guide:        **Wiring for 16x2 LCD:**       * LCD RS pin to digital pin 12       * LCD Enable pin to digital pin 11       * LCD D4 pin to digital pin 5       * LCD D5 pin to digital pin 4       * LCD D6 pin to digital pin 3       * LCD D7 pin to digital pin 2       * LCD R/W pin to ground       * 10K resistor:       * ends to +5V and ground       * wiper to LCD VO pin (pin 3)    **Wiring for buttons:**       * RS       button to pin 6  (as a digital input) -- Switches from reading read current/voltage values to setting those values, and Vice Versa.       * VIselect button to pin 7 (as a digital input) -- Switches to the 'set' mode and flips from setting the voltage to setting the current.       * UP       button to pin 8  (as a digital input) -- Increments the voltage or current up when in the 'set' mode.       * DOWN     button to pin 9  (as a digital input) -- Increments the voltage or current up when in the 'set' mode.    **Analog inputs/outputs:**       *A0   -- Measures a potential of a resistor divider that can output a voltage of 0-5V based on the 0-30V output this PSW capable of.       *A1   -- Measures the current flow through a resistor to measure current. (Some reason there seems to be a pulldown resistor on this pin, so the voltage does not float.)       *Vout -- This will be later implemented if I get a DAC, for the increased resolution. (1024 is just not enough in my opinion. At least 12 bits)       *Aout -- This will be later implemented if I get a DAC, for the increased resolution. (1024 is just not enough in my opinion. At least 12 bits) */ int UP    = 0;      // These are the 2 buttons used to incrementally int DOWN  = 0;      // step up or down the voltage on the output int RS = 0;         // These 2 buttons tell the LCD to either read out the voltage on the analog pins. (I plan to change this so it reads from a 14 bit ADC and writes int setVI = 0;      // the voltage output through a 14 (or 16 bit) bit ADC. I need 3 significant digits, or at least 0.1% accuracy. int dudd = 0;       // this dudd (dummy variable) is just here to prove that digitaslreading pin 7 works very weird! Any help on this? int preRS = 1;      // Anything with a "Pre" before it is simply what said integer/variable on the last loop. I use these to prevent a parasitic int presetVI = 1;   // oscillation of states that they control, so when a button is pressed, it will not jump between 2 states every cycle. int preUP    = 0; int preDOWN  = 0; float Aset = 0.00;  // I need these to be "floated" so I can set the exact value of these to 3 significant digits. float Vset = 0.00;  // Aset and Vset define what the output voltage *should* be, and are defined with the UP/DOWN buttons. int VIselection = 1;// this variable will invert when Aset button is pressed. Similar to the IVselect, this number will also invert int READorSET = 1;  // Bset button is pressed. This allows the mode to be changed from SET mode or the READ output mode, thus allowing                     // one to compare the output voltage and current to the set value, as well as set the output voltage and current. #include LiquidCrystal lcd(12, 11, 5, 4, 3, 2);// initialize the library with the numbers of the interface pins void setup() { //-------------------------// I tried making diagnosting this thing easier by making all the important data availible in the serial monitor.   lcd.begin(16, 2);   Serial.begin(9600);   Serial.print("INPUTS         RS:           READorSET:       setVI & dudd:        VIselection:");   Serial.println(""); } void loop() {   float V = (30.00*analogRead(A0))/1024.00;   //These are what I use to read the voltage output of my power supply. I will have a voltage divider on the output,   float A = (15.000*analogRead(A1))/1024.000; //to limit the voltage range from 0-30V to 0-5V. Same concept goes for the current measurement.   int dudd  = digitalRead(7);//   RS    = digitalRead(6);//RS stands for "Read/set"   setVI = digitalRead(7);//VI is stands for "Current/Voltage set"   UP    = digitalRead(8);//UP is simply a button used to set voltage & current   DOWN  = digitalRead(9);//DOWN is simply a button used to set voltage & current     if(presetVI == LOW && setVI == HIGH){VIselection = -VIselection;}   if(preRS    == LOW && RS    == HIGH){READorSET   =   -READorSET;}     Serial.print("\t        ");  // prints an inital space.     Serial.print(RS);            // prints the RS reading. It should be '1' when pin 7 is HIGH.     Serial.print("\t        ");     Serial.print(READorSET);     // prints the READorSET reading. This should only change when the RS button is pressed.     Serial.print("\t        ");     Serial.print(setVI);         // prints the setVI reading. It should be '1' when pin 7 is HIGH.     Serial.print("\t");     Serial.print(dudd);         // prints the setVI reading. It should be '1' when pin 7 is HIGH.     Serial.print("\t        ");     Serial.println(VIselection); // prints the VIselection reading. This should only change when the setVI button is pressed.         //if(presetVI == LOW && setVI == HIGH && READorSET == 1) {READorSET = -READorSET; VIselect = -VIselect;}      // This line of code just makes so that when I need to go from the voltage read screen to      // the set mode, I can just press the VIselect button. It just makes things more intuitive, but could be      // causeing the error, so I nulled it. I also nulled it out another portion that will keep the voltage or      // current setting the same when using the VI buttton to select the set mode. (otherwise it has to be      // double pressed to return to, say, the current setting, if that is where you left off.)   if(UP == HIGH && DOWN == LOW && VIselection == -1){if(Aset <= 10.00) {Aset += 0.05;}}   if(DOWN == HIGH && UP == LOW && VIselection == -1){if(Aset >= 0.10) {Aset -= 0.05;}}     if(UP == HIGH && DOWN == LOW && VIselection == 1) {if(Vset <= 30.00) {Vset += 0.05;}}   if(DOWN == HIGH && UP == LOW && VIselection == 1) {if(Vset >= 0.05) {Vset -= 0.05;}}     if (RS == HIGH){digitalWrite(13, 1);}   if (RS == LOW){digitalWrite(13, 0);} //============================================================================================================//   if (READorSET == 1){      //this is the defualt screen, and shows the output voltage and current.     lcd.clear();              lcd.setCursor(0, 0);     lcd.print("VOLTAGE:");     lcd.setCursor(0, 1);     lcd.print("CURRENT:");     lcd.setCursor(10, 0);     lcd.print(V);     lcd.setCursor(15, 0);     lcd.print("V");     lcd.setCursor(10, 1);     lcd.print(A);     lcd.setCursor(15, 1);     lcd.print("A");   }   if (READorSET == -1){   // This is the portion of the code allowing me to set the current and voltage     lcd.clear();          // using the up/down buttons.       if (VIselection == -1){         lcd.setCursor(0, 0);         lcd.print("  SET CURRENT:");         lcd.setCursor(5, 1);         lcd.print(Aset);         lcd.print("A ");       }       if(VIselection == 1){         lcd.setCursor(0, 0);         lcd.print("  SET VOLTAGE:");         lcd.setCursor(5, 1);         lcd.print(Vset);         lcd.print("V ");       }   } //============================================================================================================//   presetVI = setVI; // At the end of each loop, the current variable settings that were used are set equal   preRS = RS;       // to the 'pre' versions of the code. This allows me to basically measure the when                     // the button is initially pressed, and/or released. Using this method with the delay()                     // function, however, is a bit buggy, but I did have it working well enough before. If you                     // tap the button too quickly. You almost have to hold it for a split second. If you                     // know a better, simpler way of doing this, please tell me, thank you.                       delay(80);        // The delay helps stabilize the reading on the LCD, but if it is too large, than the                     // refresh rate suffers, and the buttons respond slower. However, setting too low will                     // cause the reading on the display to change so rapidly, it is illegible. }

Question by -max-   |  last reply


tv out arduino code stops?

I recently wrote some code for an arduinio to read an encoder and display it via RCA.  Problem is, it sometimes freezes on a blank screen when I'm turning the encoder.  Any ideas why? the code is below.  And yes, I know that the interrupts mess with the signal and it flickers, I want to know why it will stay off whenever the encoder is halfway through a cycle.  #include float anaval = 0; float value01 = 0; int val = 1; float value; float value10; float value100; int out; int r = 0; float pos = 0; int rd = 4; float incr = 0.00078125; TVout TV; unsigned char x,y; char i = 48; void setup()  {    pinMode(2, INPUT);    pinMode(7, INPUT);    digitalWrite(7, HIGH);    digitalWrite(2, HIGH);    attachInterrupt(0, encoderPos, CHANGE);   x=0;   y=0;   TV.begin(_NTSC,128,56); //for devices with only 1k sram(m168) use TV.begin(_NTSC,128,56) } void loop() {    disp(); // TV.clear_screen();   //  TV.print_char(4,4,char(value100)+48); //   TV.print_char(10,4,char(value10)+48); //   TV.print_char(16,4,char(value)+48);   //  TV.print_char(22,4,char(value01)+48); } void stringer(){      value01 = val; value = val / 10; value10 = val / 100; value100 = val / 1000; value = int(value);//rounds the variables value10 = int(value10); value100 = int(value100); value01 = int(value01); value01 = value01 - (value * 10);//removes all but the tenths-place digit value = value - (value10 * 10); value10 = value10 - (value100 * 10); } void encoderPos(void){ //this is a state machine to determine the direction of the encoder.  //every half-cycle it counts, effectively doubling the encoder resolution.    r = 1;    disp();   if(digitalRead(2) == HIGH){    if(digitalRead(7) == LOW){      while(r == 1){       disp();        if(digitalRead(2) == LOW){          r = 0;        } else {          if(digitalRead(7) == HIGH){            pos = pos + incr;            r = 0;          }}}                                     }    else {      while(r == 1){           disp();        if(digitalRead(2) == LOW){          r = 0;        } else {          if(digitalRead(7) == LOW){            pos = pos - incr;            r = 0;          }}}    }    }else{//same as the above code, but with High-Low reversed.    r = 1;    if(digitalRead(7) == HIGH){      while(r == 1){       disp();        if(digitalRead(2) == HIGH){          r = 0;        } else {          if(digitalRead(7) == LOW){            pos = pos + incr;            r = 0;          }}}                                     }    else {      while(r == 1){         disp();        if(digitalRead(2) == HIGH){          r = 0;        } else {          if(digitalRead(7) == HIGH){            pos = pos - incr;            r = 0;          }}}    }     } } void disp(){   val = int(pos * 1000);          TV.print_char(4,4,char(value100)+48);     TV.print_char(10,4,char(value10)+48);     TV.print_char(16,4,char(value)+48);     TV.print_char(22,4,char(value01)+48); //  TV.delay_frame(1);       stringer(); }

Question by jduffy54   |  last reply


Help for first Arduino project

Greetings all! I just received my Arduino board in the mail on Saturday, and trying to learn how to write code for it. I have figured out how to make a button press trigger a pattern of LED's.  When button1 is pressed, pattern 1 is played.  When button 2 is pressed, it will run pattern 2 (once the first pattern has run twice). I would like to learn how to: 1.  Keep a pattern running continuously (unless the other pattern is initiated). 2.  Press the same button a second time, to turn the pattern off. Here is my code (forgive the sloppiness...I'm new at this): int pinled1 = 1; int pinled2 = 2; int pinled3 = 3; int pinled4 = 4; int button1 = 5; int button2 = 6; int buttonstate1 = 0; int buttonstate2 = 0; void setup() {   pinMode(pinled1, OUTPUT);   pinMode(pinled2, OUTPUT);   pinMode(pinled3, OUTPUT);   pinMode(pinled4, OUTPUT);   pinMode(button1, INPUT);   pinMode(button2, INPUT);   pinMode(8,OUTPUT); } void loop() {   digitalWrite(8,HIGH);   buttonstate1 = digitalRead(button1);   buttonstate2 = digitalRead(button2); if (buttonstate1 == HIGH){ {   buttonstate1 = digitalRead(button1);   buttonstate2 = digitalRead(button2);     digitalWrite(pinled1,HIGH);     digitalWrite(pinled2,HIGH);     delay(500);     digitalWrite(pinled1,LOW);     digitalWrite(pinled2,LOW);     digitalWrite(pinled3,HIGH);     digitalWrite(pinled4,HIGH);     delay(500);     digitalWrite(pinled3,LOW);     digitalWrite(pinled4,LOW);     }} else if (buttonstate2 == HIGH){ {   buttonstate1 = digitalRead(button1);   buttonstate2 = digitalRead(button2);     digitalWrite(pinled2,LOW);     digitalWrite(pinled1,HIGH);     delay(500);     digitalWrite(pinled1,LOW);     digitalWrite(pinled2,HIGH);     delay(500);     digitalWrite(pinled2,LOW);     digitalWrite(pinled3,HIGH);     delay(500);     digitalWrite(pinled3,LOW);     digitalWrite(pinled4,HIGH);     delay(500);     digitalWrite(pinled4,LOW);     digitalWrite(pinled3,HIGH);     delay(500);     digitalWrite(pinled3,LOW);     digitalWrite(pinled2,HIGH);     delay(500);     digitalWrite(pinled2,LOW); }} {   buttonstate1 = digitalRead(button1);   buttonstate2 = digitalRead(button2); }} Thank you to anyone who can pass on some knowledge!

Topic by huck alexander   |  last reply


Watering Pump with LCD, Arduino. Need some help with code

Hi, Building watering unit with LCD, based on Arduino mega. I couldn't get correct value on LCD. I want to show current sensor readings. Could you please help #include #include LiquidCrystal_I2C lcd(0x27,20,4); int PUMP = 13; int sensor = 8; int val; const int DigitalInPin = 8; int sensorValue = digitalRead(8); void setup() {   pinMode(13,OUTPUT);   pinMode(8,INPUT); lcd.init();                      // initialize the lcd lcd.init(); delay(100); } void loop() {    val = digitalRead(8);     if(val ==LOW)   {   digitalWrite(13,LOW);   }   else   {   digitalWrite(13,HIGH);   }   delay(400); lcd.backlight(); lcd.setCursor(0,0); lcd.print("Soil Moisture:"); sensorValue = digitalRead(8); lcd.setCursor(0, 1); lcd.print(sensorValue); }

Topic by PASHGEN   |  last reply


Help with Capacity and Inductive Proximity Code for Arduino?

I am a beginner. I'm trying to figure out what wrong with this code. The project is suppose to turn a servo motor left and right based on which sensors are active. Capacity Sensor (cpsensor) and Inductive Proximity Sensor (ipsensor). Here is the code:                                                                                                                                                                                     #include int ipsensor = 9; int servo = 7; int pos = 90; int val = 0; int cpsensor = 5; int led = 4; Servo myservo; void setup(){   pinMode(ipsensor, INPUT);   pinMode(servo, OUTPUT);   pinMode(cpsensor, INPUT);   pinMode(led, OUTPUT);   myservo.attach(servo);   digitalWrite(ipsensor, LOW);   digitalWrite(cpsensor, LOW); } void loop() {   int ipsensor = 9;   int cpsensor = 5;   if ((digitalRead(ipsensor) == HIGH && digitalRead(cpsensor)) == HIGH){     for(pos =90; pos < 135; pos+=45)       delay(15);     for(pos = 135; pos>=90; pos-=45)     {       myservo.write(pos);     }   }   else if ((digitalRead(ipsensor) == LOW && digitalRead(cpsensor) == HIGH)){     for(pos =90; pos < 45; pos-=45)       delay(15);     for(pos = 45; pos>=90; pos+=45)     {       myservo.write(pos);     }   }   delay(1); }  

Question by charlie.spells   |  last reply


Super Easy Arduino Question?

Hey all, below is schematic for a really simple water level sensor. I want to hook this up to my Arduino so that Arduino will know when each LED is ether HIGH or LOW. My question is where at what point in the schematic do I hook up the digital read pins?   

Question by Mpc1055   |  last reply


Arduino button problems

Hello, I am trying to use two buttons to control a variable, When one is pressed the number goes up but when the other is pressed it goes down. But, this doesn't seem to be working, it goes up fine but when i want to come back down it increases by one and then goes down. I don't know why it is increasing by one but then going down. Any help will be helpful. the code is here: int button = 8; int button_two = 7;; int val = 0; int val_two = 0; int numb = 0; void setup() {   pinMode(button, INPUT);   pinMode(button_two, INPUT);   Serial.begin(9600); } void loop() {   val = digitalRead(button);   val_two = digitalRead(button_two);     if (val == HIGH) {     Serial.println(numb);     numb=numb+1;     delay(300);     } else if (val_two == HIGH) {     Serial.println(numb);     numb=numb-1;     delay(300);     } else {     numb=numb;   } } Thanks.

Topic by Isaac Emery   |  last reply


Arduino Coding help? Answered

I need some guidance on how to write some Arduino code. The physical side is an Arduino mega ADK connected to some buttons and leds. On the code side, I modified the button sketch. I am stuck on how to add multiple buttons. in the void loop. I just need someont to show me how to add 1 after that i can figure out how to add the rest. Thanks,  Kaden const int button1 = 24;     // the number of the pushbutton pin const int button2 = 25; const int button3 = 26; const int button4 = 27; const int button5 = 28; const int Bucket1 = 2; const int Bucket2 = 3; const int Bucket3 = 4; const int Bucket4 = 5; const int Bucket5 = 6; const int Bucket6 = 7; const int Bucket7 = 8; const int Bucket8 = 9; const int Bucket9 = 10; const int Bucket10 = 11; const int Bucket11 = 12; const int Bucket12 = 13; int buttonState1 = 0;         // variable for reading the pushbutton status int buttonState2 = 0; int buttonState3 = 0; int buttonState4 = 0; int buttonState5 = 0; void setup() {   // initialize the LED pin as an output:   pinMode(Bucket1, OUTPUT);   // declare LED strip pin as output   pinMode(Bucket2, OUTPUT);   pinMode(Bucket3, OUTPUT);   pinMode(Bucket4, OUTPUT);   pinMode(Bucket5, OUTPUT);   pinMode(Bucket6, OUTPUT);   pinMode(Bucket7, OUTPUT);   pinMode(Bucket8, OUTPUT);   pinMode(Bucket9, OUTPUT);   pinMode(Bucket10, OUTPUT);   pinMode(Bucket11, OUTPUT);   pinMode(Bucket12, OUTPUT);   // initialize the pushbutton pin as an input:   pinMode(button1, INPUT);   pinMode(button2, INPUT);   pinMode(button3, INPUT);   pinMode(button4, INPUT);   pinMode(button5, INPUT); } void loop() {     buttonState1 = digitalRead(button1);   buttonState2 = digitalRead(button2);   buttonState3 = digitalRead(button3);   buttonState4 = digitalRead(button4);   buttonState5 = digitalRead(button5);   // check if the pushbutton is pressed.   // if it is, the buttonState is HIGH:   if (buttonState1 == HIGH) {     // turn LED on:   digitalWrite(Bucket1, HIGH);  // turn LED strip on when button is pressed   digitalWrite(Bucket2, HIGH);   digitalWrite(Bucket3, HIGH);   digitalWrite(Bucket4, HIGH);   digitalWrite(Bucket5, HIGH);   digitalWrite(Bucket6, HIGH);   digitalWrite(Bucket7, HIGH);   digitalWrite(Bucket8, HIGH);   digitalWrite(Bucket9, HIGH);   digitalWrite(Bucket10, HIGH);   digitalWrite(Bucket11, HIGH);   digitalWrite(Bucket12, HIGH);   }   else {     // turn LED off:   digitalWrite(Bucket1, LOW);  // turn LED strip on when button is pressed   digitalWrite(Bucket2, LOW);   digitalWrite(Bucket3, LOW);   digitalWrite(Bucket4, LOW);   digitalWrite(Bucket5, LOW);   digitalWrite(Bucket6, LOW);   digitalWrite(Bucket7, LOW);   digitalWrite(Bucket8, LOW);   digitalWrite(Bucket9, LOW);   digitalWrite(Bucket10, LOW);   digitalWrite(Bucket11, LOW);   digitalWrite(Bucket12, LOW);   } }

Question by FarmerKJS   |  last reply


Please help with my Arduino program (controlling servo)? Answered

I started trying the Arduino programming 1 days ago so I'm not sure what is wrong with my program (also, sorry for the messy look) const int buttonPin = 2;     int buttonState = 0;         #include Servo myservo;  int n = 0; int pos; int lc = 0; void setup() {   myservo.attach(9);   pinMode(buttonPin, INPUT);   myservo.write(pos); } void loop() {   buttonState = digitalRead(buttonPin);   if (buttonPin == HIGH)  {     if (lc == 0) {     for(pos = n; pos <= 180; pos++) {     myservo.write(pos);                   buttonState = digitalRead(buttonPin);     if (buttonPin == LOW){       n = pos;       break; }     if (pos == 180) {       n=pos;       lc = 1;}      delay(15);   } }     else {   for(pos = n; pos>=0; pos--)        {                                    myservo.write(pos);                   buttonState = digitalRead(buttonPin);     if (buttonPin == LOW){       n = pos;       break; }     if (n == 0) {       n = pos;       lc = 0;}      delay(15);    } }   } } Basically, it's to use a button to control the servo, if the button is press, the servo will spin (0 to 180 then 180 back to 0), if the button is released, it will stop the servo, and pressing the button will continues the servo movement (not resetting it). The "lc" int is used to show if the servo was moving from 0 to 180 (lc = 0) or 180 back to 0 (lc = 1). I only studied Pascal before so I have a bit trouble understand it so if there was big mistake in my program, please let me know. Thanks for your help.

Question by Shizen   |  last reply


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   |  last reply


How to make a push button make double clicks and a single click like on a mouse?

I am making a mouse using push buttons. I want to record double clicks and single clicks separately but am not bein able to. Either it shows a single click or a double click. Could someone help me with an example code or a tutorial somewhere? Greatly appreciated. This is my code so far.. int ck = 13; int t; int i; void setup() {   // put your setup code here, to run once:   digitalWrite(ck, HIGH);   t = 0;   i = 0; } void loop() {   // put your main code here, to run repeatedly:   digitalWrite(ck, HIGH);   if (digitalRead(ck) == LOW) {     digitalWrite(ck, HIGH);     delay(150); while(i < 300) {       digitalWrite(ck, HIGH);       i++;       if (digitalRead(ck) == LOW) {         t = 1;         break;       }       delay(3);     }     if (t == 0) {       Mouse.click(MOUSE_LEFT);       delay(1500);     }     else if (t == 1) {       Mouse.click(MOUSE_LEFT);       Mouse.click(MOUSE_LEFT);       delay(1500);     }   } }

Question by PrabhavM   |  last reply


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

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

Question by DejunL   |  last reply


Binary Arduino Alarm Clock HELP!

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

Topic by holidayv 


Arduino Pish Button code Issue

Hey all, I am having a problem with my code and was hoping someone could help shed some light on how to fix it. Below is a code for an arduino push button counter. The concept is that there are 2 buttons, an "add" button and "subtract" button. Every time add is pressed it adds 1 to the count and vice versa when subtract is hit. The code works fine until we hit double digits. Once you subtract from 1 from 10 the LCD displays 90 not 9. Not sure how to fix this, any ideas?LiquidCrystal lcd(1, 2, 4, 5, 6, 7);int add=8;int sub=9; int valadd;int valsub;int count=000; int press;void setup() { lcd.begin(16,2); pinMode(add,INPUT); pinMode(sub,INPUT);}void loop() {valadd=digitalRead(add);valsub=digitalRead(sub);if(valadd==HIGH) {delay(100);press=count++;delay(250);}if(valsub==HIGH) {delay(100);press=count--;delay(250);}lcd.setCursor(0,0);lcd.print(press);}

Topic by Mpc1055   |  last reply


I need help with my arduino code, the error code is "stray #" . located at #define DO_NEXT 4

1.//iOS switch control example 2.//Simple version 3.#define MY_DEBUG 1 4.#include "BluefruitRoutines.h" 5. 6.//Pin numbers for switches 7.#define PREVIOUS_SWITCH A0 8.#define SELECT_SWITCH A1 9.#define NEXT_SWITCH A2 10. 11.//Actions 12.#define DO_PREVIOUS 1 13.#define DO_SELECT   2 14.#define DO_NEXT     4 15. 16.uint8_t readSwitches(void) { 17.  return (~(digitalRead(PREVIOUS_SWITCH)*DO_PREVIOUS 18.      + digitalRead(SELECT_SWITCH)*DO_SELECT 19.      + digitalRead (NEXT_SWITCH)*DO_NEXT) 20.     ) & (DO_PREVIOUS+ DO_SELECT+ DO_NEXT); 21.} 22. 23.//Translate character to keyboard keycode and transmit 24.void pressKeyCode (uint8_t c) { 25.  ble.print(F("AT+BLEKEYBOARDCODE=00-00-")); 26.  uint8_t Code=c-'a'+4; 27.  if (Code<0x10)ble.print("0"); 28.  ble.print(Code,HEX); 29.  ble.println(F("-00-00-00-00")); 30.  MESSAGE(F("Pressed.")); 31.  delay(100);//de-bounce 32.  while (readSwitches()) { //wait for button to be released 33.    /*do nothing*/ 34.  }; 35.  ble.println(F("AT+BLEKEYBOARDCODE=00-00")); 36.  MESSAGE(F("Released")); 37.} 38. 39.void setup() { 40.  if(MY_DEBUG) 41.  while (! Serial) {}; delay (500); 42.  Serial.begin(9600); Serial.println("Debug output"); 43.endif 44.  pinMode(SELECT_SWITCH, INPUT_PULLUP); 45.  pinMode(NEXT_SWITCH, INPUT_PULLUP); 46.  pinMode(PREVIOUS_SWITCH, INPUT_PULLUP); 47.  initializeBluefruit(); 48.} 49. 50.void loop() { 51.  uint8_t i=readSwitches(); 52.  switch (i) { 53.    case DO_PREVIOUS: pressKeyCode('p'); break; 54.    case DO_SELECT:   pressKeyCode('s'); break; 55.    case DO_NEXT:     pressKeyCode('n'); break; 56.  } 57.} void setup() {   // put your setup code here, to run once: } void loop() {   // put your main code here, to run repeatedly: }

Question by JacLir00179   |  last reply


Arduino multiple if statements

Hi, Thank you in advance for any feedback for my question. I made a XY plotter machine that I want to control with a joystick. The joystick has 4 momentary pushbuttons. One for up, down, left, right. I want the up and down to control one motor (or x axis), forward and backwards, and the left and right to control the second motor (y axis), forwards and backwards. I am using an Arduino UNO with Motor shield. I have all of the wiring part sorted out, but I am having trouble with my code. The problem is when I push forwards, the motor keeps going forward even when I stop pushing the button. I would like it to stop when I stop pushing the button. I am not too familiar with programming. Here is the code I am using: //Channel A or X Axis int upPinX = 2; int downPinX = 4; int forwardX = 0; int reverseX = 0; //Channel B or Y Axis int upPinY = 5; int downPinY = 6; int forwardY = 0; int reverseY = 0; void setup() {     //Setup Channel A or X Axis pinMode(12, OUTPUT); //Initiates Motor Channel A pin pinMode(9, OUTPUT); //Initiates Brake Channel A pin pinMode(upPinX, INPUT); //Motor A forward pushbutton pinMode(downPinX, INPUT); //Motor A backward pushbutton //Setup Channel B or Y Axis pinMode(13, OUTPUT); //Initiates Motor Channel A pin pinMode(8, OUTPUT); //Initiates Brake Channel A pin pinMode(upPinY, INPUT); //Motor A forward pushbutton pinMode(downPinY, INPUT); //Motor A backward pushbutton } void loop(){ forwardX = digitalRead(upPinX); reverseX = digitalRead(downPinX); forwardY = digitalRead(upPinY); reverseY = digitalRead(downPinY); if (forwardX == LOW) { digitalWrite(12, HIGH); //Establishes forward direction of Channel A digitalWrite(9, LOW); //Disengage the Brake for Channel A analogWrite(3, 1023); //Spins the motor on Channel A at full speed } if (reverseX == LOW) {   digitalWrite(12, LOW); //Establishes forward direction of Channel A digitalWrite(9, LOW); //Disengage the Brake for Channel A analogWrite(3, 1023); //Spins the motor on Channel A at full speed } if (forwardY == LOW) { digitalWrite(13, HIGH); //Establishes forward direction of Channel A digitalWrite(8, LOW); //Disengage the Brake for Channel A analogWrite(11, 1023); //Spins the motor on Channel A at full speed } if (reverseY == LOW) {   digitalWrite(13, LOW); //Establishes forward direction of Channel A digitalWrite(8, LOW); //Disengage the Brake for Channel A analogWrite(11, 1023); //Spins the motor on Channel A at full speed } else {   digitalWrite(9, HIGH); //Eengage the Brake for Channel A digitalWrite(8, HIGH); //Engage the break for Channel B } } - Also perhaps someone could let me know how I can insert code in one of those code boxes? Thanks,

Topic by toedip   |  last reply


How to alter the code in this LED chase

Hi,here is the code i have for a chase controlled by a button. When the button is engaged (held in) the chase runs. When the button is released the chase stops. My question is how can I make the LEDS appear to go haywire when the button is released and not simply go off. // A chase controlled by a button int Button=2; //button assigned to pin 2 int timer = 150; // The higher the number, the slower the timing. int ledPins[] = { 3,4,5,6,7,8,9,10 }; // an array of pin numbers to which LEDs are attached int pinCount = 8; // the number of pins (i.e. the length of the array) void setup() { Serial.begin(9600); pinMode(Button, INPUT); int thisPin; // the array elements are numbered from 0 to (pinCount - 1). // use a for loop to initialize each pin as an output: for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); } } //turn LEDS on void loop() { while (digitalRead(Button)==HIGH); { //delay (10); Serial.println("LOW"); } while (digitalRead(Button)==LOW) { Serial.println("HIGH"); for (int thisPin = 0; thisPin < pinCount; thisPin++) { //turn leds on digitalWrite(ledPins[thisPin], HIGH); delay(timer); //turn leds off digitalWrite(ledPins[thisPin], LOW); } //turn leds on for (int thisPin = pinCount -1; thisPin >= 0; thisPin--) { //turn leds off digitalWrite(ledPins[thisPin], HIGH); delay(timer); digitalWrite(ledPins[thisPin], LOW); } } } many thanks, Frank

Topic by frankhiggins 


PIR motion sensor,DC motor and Speaker alarm system help? Answered

I'm trying to create an alarm system using a PIR motion sensor, DC motor and a speaker so when someone gets close to it the DC motor should vibrate and sound and alarm through the speaker. (using and Arduino UNO) I've got  an external 9V battery powering it. the PIR and sound works fine I just want to hook up the DC motor to run along with everything else.  I've got some code for a button switch that could turn the motion sensor on and off when I want to use it also, if you know how to set that up that would help. I'm new to Arduino and circuits please help.  Here is the code I'm using: int ledPin = 13;                 int inputPin = 2;                int pirState = LOW;              int val = 0;                    int pinSpeaker = 10;           boolean on = true; void setup() {   pinMode(ledPin, OUTPUT);      // declare LED as output   pinMode(inputPin, INPUT);     // declare sensor as input   pinMode(pinSpeaker, OUTPUT);   pinMode(3,INPUT);   Serial.begin(9600); } void loop() {   //button code for turning on and off the PIR //  if (on == false) { //    if (digitalRead(3) == HIGH) { //      on = true; //      Serial.println("turned on"); //    } //    return; //  } //  //  if (on == true) { //    if (digitalRead(3) == HIGH) { //      on = false; //      Serial.println("turned off"); //    } //  }     val = digitalRead(inputPin);  // read input value   if (val == HIGH) {            // check if the input is HIGH     digitalWrite(ledPin, HIGH);  // turn LED ON     playTone(300, 160);     delay(150);         if (pirState == LOW) {       // we have just turned on       Serial.println("Motion detected!");       // We only want to print on the output change, not state       pirState = HIGH;     }   } else {       digitalWrite(ledPin, LOW); // turn LED OFF       playTone(0, 0);       delay(300);          if (pirState == HIGH){       // we have just turned off       Serial.println("Motion ended!");       // We only want to print on the output change, not state       pirState = LOW;     }   } } // duration in mSecs, frequency in hertz void playTone(long duration, int freq) {     duration *= 1000;     int period = (1.0 / freq) * 1000000;     long elapsed_time = 0;     while (elapsed_time < duration) {         digitalWrite(pinSpeaker,HIGH);         delayMicroseconds(period / 2);         digitalWrite(pinSpeaker, LOW);         delayMicroseconds(period / 2);         elapsed_time += (period);     } }     

Question by TianL4   |  last reply


Arduino code help input binary to pin 4?

Unsigned char APin=4; unsigned char BPin=5; unsigned char CPin=6; unsigned char PinState; unsigned char LastPinState=B111;  // As in High, High, High for random mode pinMode(APin, INPUT);   pinMode(BPin, INPUT);   pinMode(CPin, INPUT);   digitalWrite(APin, HIGH);   digitalWrite(BPin, HIGH);   digitalWrite(CPin, HIGH); this code im using is outdated for me now and im using an iphone to send binary commands to atmel328 chip witch tells sends the binary code out a pin to my arduino can i recieve a b101 or b111 on pin 4 or any other pin. how do i change what i have right now it reads the state of pins 4,5,6 aka a,b,c and displays different messages. so if i ground b and c it plays one of the messages and so on i dont want this i want to take the b001 being sent from my other boards and use it on pin 4 aka a void loop(){   PinState = B111;       // Read ABC and assign to a 3 bit number   if(digitalRead(CPin)==LOW){        // A if Gnd -1 to make B??0     PinState = PinState - 1;                     }   if(digitalRead(BPin)==LOW){        // B if Gnd -2 to make B?0?     PinState = PinState - 2;      }   if(digitalRead(APin)==LOW){        // C if Gnd -4 to make B0??     PinState = PinState - 4;      }   if (PinState != LastPinState){     LastPinState = PinState;     switch (PinState){       case B000:{    // B000  HPs all on random on/off         if((FrontHPStateDefault==0) && (RearHPStateDefault==0) && (TopHPStateDefault==0)){           FrontHPStateDefault=3;           RearHPStateDefault=3;           TopHPStateDefault=3;         } else {           FrontHPStateDefault=0;           RearHPStateDefault=0;           TopHPStateDefault=0;         }         break;       }       case B001:{    // B001 Cantina MP3         FeedString    (1, FrontHPStateDefault, RearHPStateDefault, TopHPStateDefault, 1,0, 0, "<<<<<<<<<");         break;       }       case B010:{    // B010 Han Shot First         FeedString    (8, 3,3,3, 1,1, 1, " HAN SHOT FIRST! ");         break;       }       case B011:{    // B011 Short Circuit         Failure       (7, 5,5,5, 8);         LogicOffDelay (6, 0,0,0, 1, 20);         FailureReverse(8, 4,4,4, 2);         break;       }

Question by slipnots   |  last reply


help with arduino programming?

Right so i made this IR proximity detector, and having trouble with the code...#include #define irx 2 static boolean output = HIGH; int Ledpin = 13;void setup(){ pinMode(Ledpin, OUTPUT); pinMode(irx, INPUT); Serial.begin(9600); MsTimer2::set(5, flash); MsTimer2::start(); } void loop(){ while(digitalRead(irx)); Serial.println("detected"); digitalWrite(Ledpin, HIGH);}void flash() { digitalWrite(12, output); output = !output; }i want the LED to be on when it detects something and go off when it doesnt detect anything, but after it detecs something it stays on for ever... :(wjhat wrong here?

Question by amando96   |  last reply


Why do I get the error: expected `(' before 'buttonState' in myprogram?

So my code is int small = 9; int big = 8; int buttonPin = 6; void setup() {   pinMode(small, OUTPUT);   pinMode(big, OUTPUT);   pinMode(2, OUTPUT); } void loop() {   digitalWrite(2, HIGH);   int buttonState = digitalRead(buttonPin);   buttonState = map(buttonState, 0, 1023, 0, 1);   if buttonState = 1 {     digitalWrite(small, HIGH);     digitalWrite(big, HIGH);   }   else {     digitalWrite(small, LOW);     digitalWrite(big, LOW);   } } but for some reason I get that error. Please reply asap Thanks in advance

Question by Myidentityisasecret   |  last reply


Buzzer and LED interfering with each other on an arduino? Answered

Hi, I recently got an arduino for Christmas and am experiencing a problem.  I am practicing using it with a piezo buzzer, push button, and a RGB LED.  I programmed it so that whenever the button was pushed, the LED turned green, and when it wasn't pushed, the LED turned RED.  It worked fine until I added the buzzer.  I modified the program so that the buzzer was on when the button was not pushed.  Once I did this, the buzzer turned on and green and red pin of the LED came on dimly making the LED orange when the button was not pushed, and when the button was pushed, the buzzer turned off and the LED lit up green like it was supposed to.  I wan't to know why the LED is orange instead of solid red.  Any help would be appreciated.  If you need more information let me know. Here is my sketch //#include const int RED_PIN = 9; const int GREEN_PIN = 10; const int BUTTON_PIN = 7; const int BUZZER_PIN = 6; //const int TRIGGER_PIN = 12, ECHO_PIN = 11; //NewPing sonar(TRIGGER_PIN, ECHO_PIN); void setup() {   pinMode (RED_PIN, OUTPUT);   pinMode (GREEN_PIN, OUTPUT);   pinMode (BUTTON_PIN, INPUT);   pinMode (BUZZER_PIN, OUTPUT); } void loop() {   if (digitalRead(BUTTON_PIN) == HIGH)   {     digitalWrite(GREEN_PIN, LOW);     digitalWrite(RED_PIN, HIGH);     analogWrite(BUZZER_PIN, 100);   }   else if (digitalRead(BUTTON_PIN) == LOW)   {     digitalWrite(RED_PIN, LOW);     digitalWrite(GREEN_PIN, HIGH);     analogWrite(BUZZER_PIN,0);   } }

Question by roboticarrow   |  last reply


How can I use a button to control a loop within a specific time limit?

Hello everyone,in my code below I have a button that initiates several actions. Initially it is set to LOW and when the button is HIGH several actions occur. I would like to add a time limit of 3 seconds so if the button stays LOW after that a different set of actions will occur. I tried using the if/else functions. Any suggestions will be appreciated!Thanks!Thomas. #include Servo s2; int BUTTON = 2; int COUNT = 1; int buzzerPin = 8; int counter;void setup() { Serial.begin(9600); pinMode(10, INPUT); pinMode(13, OUTPUT); pinMode(12, OUTPUT); s2.attach(5); } void loop() { unsigned long start_time; unsigned long stop_time; s2.write(6); if (Serial.available() > 0) { char data = Serial.read(); // reading the data received from the bluetooth module switch (data) { { case '1': start_time = millis(); Serial.println(" "); Serial.println(" Go...Go.. "); for (counter = 0; counter < 3; ++counter) { switch (COUNT); int servo = random(5); while (digitalRead(BUTTON) == LOW) { digitalWrite(13, HIGH); digitalWrite(12, LOW); s2.write(90); delay(10); } if (digitalRead(BUTTON) == HIGH) { Serial.write ("*S"); tone(buzzerPin, 600); delay(50); noTone(buzzerPin); digitalWrite(13, LOW); digitalWrite(12, HIGH); s2.write(6); delay(600); COUNT ++; Serial.print("You hit "); Serial.println(COUNT); } } } Serial.println(" "); Serial.println(" Finished: "); Serial.println("Your result is: "); Serial.print(COUNT); Serial.print(" Target in "); stop_time = millis(); Serial.print(stop_time - start_time); Serial.println(" Time"); Serial.println(" "); if (COUNT > 0) { COUNT = 0; } } } }

Question by tomstell1111   |  last reply


Arduino code help? Answered

I'm really new to the arduino and I'm struggling to get this code working. I'm trying to have a servo continuously go back and forth until I change its state, which result on the servo to stop at its current position. However, it gets stuck on that for loop and i can't change its state. I assume this is caused by the delay, but I am not sure how to make it so it works without delays, unless there is another way.My code is right here: {edited} const int Button = 2; //This is interrupt 0 int Pos; const int button2=14; volatile int sweep = HIGH; //Our state variable, initialise so we always sweep #include Servo servo1; int buttoncount=1; int lastbuttonstate=0; const int led_1=7; void setup() { servo1.attach(10); pinMode(Button, INPUT); pinMode(button2,INPUT); pinMode(led_1,OUTPUT); Serial.begin(9600); attachInterrupt(0, Isweep, CHANGE); } void loop() { Serial.println(buttoncount); switch(buttoncount){ case 1: servo1.write(0); digitalWrite(led_1, LOW); break; case 2:     Pos=0; while (Pos<180 & sweep==true) {servo1.write (Pos); Pos++; delay(10); } while (Pos>0 & sweep==true) {servo1.write(Pos); Pos--; delay(10); } break; case 3: digitalWrite(led_1,HIGH); break; default: Serial.println("error"); } //both these whiles will terminate and not do anything if sweep is true. } void Isweep() //Interrupt routine { int buttonstate=digitalRead(Button); if (buttonstate !=lastbuttonstate){    if (buttonstate==HIGH){      buttoncount++;    } } lastbuttonstate=buttonstate; if (buttoncount==4){    buttoncount=1;   } sweep = !sweep; while (digitalRead(Button)==true); //change state only once when button is pressed }

Question by cmasuo   |  last reply


How to reset arduino after pressing the pushbutton 16 times?

Good afternoon, I'm trying to reset my Arduino after pressing the pushbutton 16 times. What I'm currently experiencing is that it is not resetting. I'm trying to achieve this using the StateChangeDetection example. Could anyone give me tips on how to achieve this? I'm working on this using an Multi Function Shield or MFS. My code is: // this constant won't change: const int  buttonPin = A1;    // the pin that the pushbutton is attached to const int ledPin = 13;       // the pin that the LED is attached to // Variables will change: int buttonPushCounter = 0;   // counter for the number of button presses int buttonState = 0;         // current state of the button int lastButtonState = 0;     // previous state of the button int count = 0; void setup() {   // initialize the button pin as a input:   pinMode(buttonPin, INPUT);   // initialize the LED as an output:   pinMode(ledPin, OUTPUT);   // initialize serial communication:   Serial.begin(9600); } void loop() {   // read the pushbutton input pin:   buttonState = !digitalRead(buttonPin);   // compare the buttonState to its previous state   if (buttonState != lastButtonState) {     // if the state has changed, increment the counter     if (buttonState == LOW) {       // if the current state is HIGH then the button went from off to on:       buttonPushCounter++;       Serial.println("on");       Serial.print("number of button pushes: ");       Serial.println(buttonPushCounter);     } else {       // if the current state is LOW then the button went from on to off:       Serial.println("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;   // read the state of the pushbutton value:   buttonState = digitalRead(buttonPin); //Source: https://www.instructables.com/answers/Is-there-a-way-to-count-button-pushes-on-an-arduin/ if (buttonState == HIGH) {        // turn LED on:       digitalWrite(ledPin, HIGH);     count++;               // add 1 to the count     if (count >= 8) {       count = 0;     }   }   else {     // turn LED off:     digitalWrite(ledPin, LOW);   } }

Question by DanielB804   |  last reply


Need help with changing arduino code for more servos Answered

This code makes a continuous rotation servo motor turn on and run until you let go of the button. I need to change this sketch so that there are 3 buttons, instead of 1, and if I press 1, a continuous rotation servo would turn for each button until I let go of the button. #include Servo myServo; int servoPin = 2; int buttonPin = 7; int buttonState = 0; void setup() {   // put your setup code here, to run once: pinMode(buttonPin, INPUT); myServo.attach(servoPin); } void loop() {   // put your main code here, to run repeatedly: buttonState = digitalRead(buttonPin); if (buttonState == HIGH) {   myServo.write(0); }else{   myServo.write(90); } delay(15); }

Question by Orange robot   |  last reply


Arduino coding help! Buttons, switches, and servos are not agreeing.

Hi my name is Nash and I've been playing with Arduino Duemilanove for about a year and just touching a little bit of everything. Right now I'm have the Arduino powering basically a pan/tilt device that rotates horizontally 360 degrees and vertically 90 degrees. Using a specific code containing one button, I can have the Arduino run a sequence of the two servos. I would like to add a second button and have a switch to choose "modes." If the switch is OFF, then pushing one button will run the sequence- simple enough. When the switch is ON, I would like the same button as before as well as an additional button control rotation of the horizontal servo. I have the code using only one button and no switch to run the sequence and the device runs flawlessly. Once I add the "switching" part to the code, the servos freak out and fidget constantly without a positive result. I am fairly new to the servo library in Arduino and am open to any kind of instruction or changes to my code below. Thanks for your help! #include Servo servo; //we think this will make the Cont-Rot servo to sit still Servo iservo; //set second servo #define button 3 //attaches button to pin 3 int ibutton = 0; //ibutton is used to store state of input #define button2 2 //second button attached to pin 2 int qbutton = 0; //qbutton stores input #define button7 7 //switch connected to pin 7 int sbutton = 0; //switch stores input void setup() {   servo.attach(5); //attaches servo to pin 5   iservo.attach(6); //attaches second servo to pin 6   pinMode(button, INPUT); //sets button as input   pinMode(button2, INPUT); //sets button2 as input   pinMode(button7, INPUT); //sets switch as input } void loop() {   ibutton = digitalRead(button); //reads state of button   qbutton = digitalRead(button2); //reads state of second button   Switch = digitalRead(button7); //reads state of switch   if (Switch == LOW) { //if switch is off   if (ibutton == HIGH) { //and ibutton is pressed     iservo.write(0); //run this servo sequence     servo.write(100);     delay(2000);     iservo.write(0);     servo.write(80);     delay(4000);     iservo.write(0);     servo.write(100);     delay(2000);   }   if (ibutton == LOW) { //ibutton is not pressed     servo.write(90); //do nothing     iservo.write(50);   } }   if (Switch == HIGH) { //switch is on     if ((ibutton == HIGH) && (qbutton == LOW)) { //ibutton is pressed and qbutton is not       servo.write(80); //servo spin counter-clockwise     }     if ((ibutton == LOW) && (qbutton == HIGH)) { //ibutton is not pressed and qbutton is       servo.write(100); //servo spin clockwise     }     if ((ibutton == LOW) && (qbutton == LOW)) { //neither button is pressed       servo.write(90); //do nothing     }   } }

Question by shooternash   |  last reply


arduino button problems, again

I have a problem with two buttons and a RGB LED. I want the two buttons to be pressed and then the brightness decreases/increases but it isn't working. When i press it, it decreases it but then it doesn't do it again. Any help would be appreciated. Code included below (problem is in bold) : int button = 8; int button_two = 7; int redPin = 6; int greenPin = 5; int bluePin = 3; int val = 0; int val_two = 0; int numb = 0; int r = 0; int g = 0; int b = 0; int i = 0; void setup() {   pinMode(redPin, OUTPUT);   pinMode(greenPin, OUTPUT);   pinMode(bluePin, OUTPUT);   pinMode(button, INPUT);   pinMode(button_two, INPUT);   Serial.begin(9600); } void loop() {   val = digitalRead(button);   val_two = digitalRead(button_two);     if (val == HIGH && val_two == LOW && numb < 7) {     numb++;     delay(300);     } else if (val_two == HIGH && val == LOW && numb > 1) {     numb--;     delay(300);     } else {     numb=numb;   }     if (numb == 1){       r = 255;       g = 255;       b = 255;   }   if (numb == 2){       r = 255;       g = 0;       b = 0;   }   if (numb == 3){       r = 0;       g = 255;       b = 0;   }   if (numb == 4){       r = 0;       g = 0;       b = 255;   }   if (numb == 5){       r = 255;       g = 255;       b = 0;   }    if (numb == 6){       r = 255;       g = 0;       b = 255;   }    if (numb == 7){       r = 0;       g = 255;       b = 255;   }   if (val == HIGH && val_two == HIGH) {       int r_cal = r / 5;     int g_cal = g / 5;     int b_cal = b / 5;         r = r - r_cal;     g = g - g_cal;     b = b - b_cal;   Serial.println(r);   Serial.println(g);   Serial.println(b);   delay(300);   } else {     val == LOW;     val_two == LOW;   }   analogWrite(redPin, r);   analogWrite(greenPin, g);   analogWrite(bluePin, b); }

Topic by Isaac Emery 


Help with Arduino? Answered

Hey everyone,          I'm doing a project with the arduino and i just want an led to light if a PIR senses motion. I am using this sensor:     http://www.sparkfun.com/commerce/product_info.php?products_id=8630 I know I have everything hooked up right, my code is just wrong.(Yes, MOTOR is used for the LED) Can someone tell me what to do? Here is the code: //Motion Detecting Box-Second Attempt #define MOTOR 13 //Motor connected to pin 13 #define PIR 2   //Motion Sensor is connected to pin 2 void setup() {   pinMode(MOTOR, OUTPUT); //sets the digital pin as output     pinMode(PIR, INPUT);    //sets the digital pin as input   } void loop() {  digitalRead(PIR); //checks pin 2     if (PIR==LOW) {     digitalWrite(MOTOR, HIGH); //turn on Motor }  else {   digitalWrite(MOTOR, LOW); } }

Question by Adum24   |  last reply


PIR DC Motor? Answered

Hi all, I am trying to set up a dc motor controlled by a PIR sensor using an arduino.  When the PIR sensor is triggered, I would like the motor to turn on for half a second and then off.  However, no matter what "delay" I write into the sketch, the motor always stays on for around four seconds.  Could someone please help me? The sketch I have written is below and have provided a picture of my set-up: const int pirPower = 12; const int pirIn = 13; int motorPin1 = 3; void setup(){ pinMode(pirPower, OUTPUT); pinMode(pirIn, INPUT); pinMode(motorPin1, OUTPUT); digitalWrite(motorPin1, LOW); digitalWrite(pirPower, HIGH); } void loop(){   int value= digitalRead(pirIn);     if (value == HIGH){       digitalWrite(motorPin1, HIGH);       delay(2000); //will not start if = 0-20.  The signal is stronger the higher the delay goes.  Time active remains the same.       digitalWrite(motorPin1, LOW);     } }

Question by Josh_Lucas   |  last reply


arduino coding problem

Im working on a project of mine which needs an arduino to easily manipulate the PIR sensor and easily use its outputs via LED light. this is my current program. int ledPin = 13; int pinPir = 2; int val = 0; int led2Pin = 12; void setup() {   pinMode(ledPin, OUTPUT);   pinMode(pinPir, INPUT);   pinMode(led2Pin, OUTPUT);     Serial.begin(9600); } void calcLed(){   val = digitalRead(pinPir);   if (val == HIGH){     digitalWrite(ledPin, HIGH);     delay(5000);   }   else   {     digitalWrite(ledPin, LOW);   } } void loop(){   digitalWrite(led2Pin, HIGH);   calcLed();   delay(5000);   digitalWrite(led2Pin, LOW);   delay(2000); } im having a problem with how the sequence of the program works. when i test the project . its works fine. but while the program is running . it seems that it wont  recognize the input of the Pir sensor until the program is done? how can i intervene ? i want the program to go back to 1st step when the PIR sensor . detects motion. please help? thankyou :)

Topic by charmaineanne.bahia   |  last reply


Arduino programming help: Do two things at once!

So I'm making a new project but I ran up into a little problem with the code. So this is what I want: Arduino check to see if A0 is HIGH, If so, turn on LED for 5 minutes. If, during any period within the 5 minutes, if pin A0 goes HIGH again, then start the 5 minutes all over again.  So basically every time pin A0 is HIGH no matter when always start a new 5 min timer. This is what I had. . . void loop() {     pirstate = digitalRead(pir);     if (pirstate == HIGH)   {     digitalWrite(LED, HIGH);     digitalWrite(relay, HIGH);     delay(pulse);   }    else   {     digitalWrite(LED, LOW);     digitalWrite(relay, LOW);   }   } The only problem with the above code is that it doesn't do anything while waiting the 'pulse' time. I need it to be able to within 'pulse' time check again to see if the pin is HIGH, and if it is, start all over again with 'pulse' seconds. Thanks guys! Your help is invaluable!

Topic by HavocRC   |  last reply


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

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

Topic by ShaidK 


Arduino Script Issue?

Hey world, I am making device that will automatically water my xmas tree: I am using the basic "button" script from the Arduino IDE examples. the only change I have made so far is instead of using an actual push button I am sticking 2 bare copper wires(the ground has a 10k resistor) into a jar.  When water is added to the jar the connection is made and the LED goes on. The problem is that it only stays on for like 7 seconds. I need it so as long as there is water in the cup the light stays on. any ideas? Below is a copy of the script. Thanks! const int buttonPin = 2;     // the number of the pushbutton pin const int ledPin =  13;      // the number of the LED pin // variables will change: int buttonState = 0;         // variable for reading the pushbutton status void setup() {   // initialize the LED pin as an output:   pinMode(ledPin, OUTPUT);   // initialize the pushbutton pin as an input:   pinMode(buttonPin, INPUT); } void loop() {   // read the state of the pushbutton value:   buttonState = digitalRead(buttonPin);   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:   if (buttonState == HIGH) {     // turn LED on:     digitalWrite(ledPin, HIGH);   } else {     // turn LED off:     digitalWrite(ledPin, LOW);

Question by Mpc1055   |  last reply


I need help with arduino code. Can someone help me remove the ping sensor from the code below?

I need to take the ping sensor out of this code. I want the robot to drive around like crazy until it bumps into something with the bump switch. /* Rumblebot Driving with object avoidance utiliszing PING Ultrasound Sensor * and a bump switch. * Reads values (00014-01199) from an ultrasound sensor (Parallax PING) * * Version 1.1.2 Motor runs and drives full time unless object detected. *-------------------------------------------------------------------- * * * * * * */ int switchPin= 2; // Right bump switch on pin 2 int swval; // Variable for reading switch status int ultraSoundSignal = 7; // Ultrasound signal pin int val = 0; int ultrasoundValue = 0; int timecount = 0; // Echo counter int ledPin = 13; // LED connected to digital pin 13 int motorpinright = 10; // pin for left motor reverse int motorpinleft = 11; // pin for left motor forward int motorpinrevright = 5; // pin for right motor reverse int motorpinrevleft = 6; // pin for right motor forward void setup() { pinMode(switchPin, INPUT); // Sets the digital pin as input pinMode(ledPin, OUTPUT); // Sets the digital pin as output pinMode(motorpinright, OUTPUT); // Motor drives----------- pinMode(motorpinleft, OUTPUT); //------------------------ pinMode(motorpinrevright, OUTPUT); //------------------------ pinMode(motorpinrevleft, OUTPUT); //------------------------ } void loop() { /* Start Scan * -------------------------------------------------- */{ timecount = 0; val = 0; pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output /* Send low-high-low pulse to activate the trigger pulse of the sensor * ------------------------------------------------------------------- */ digitalWrite(ultraSoundSignal, LOW); // Send low pulse delayMicroseconds(2); // Wait for 2 microseconds digitalWrite(ultraSoundSignal, HIGH); // Send high pulse delayMicroseconds(5); // Wait for 5 microseconds digitalWrite(ultraSoundSignal, LOW); // Holdoff /* Listening for echo pulse * ------------------------------------------------------------------- */ pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input val = digitalRead(ultraSoundSignal); // Append signal value to val while(val == LOW) { // Loop until pin reads a high value val = digitalRead(ultraSoundSignal); } while(val == HIGH) { // Loop until pin reads a high value val = digitalRead(ultraSoundSignal); timecount = timecount +1; // Count echo pulse time } /* Lite up LED if any value is passed by the echo pulse * ------------------------------------------------------------------- */ if(timecount > 0){ digitalWrite(ledPin, HIGH); delay(50); //LED on for 50 microseconds digitalWrite(ledPin, LOW); } /* Delay of program * ------------------------------------------------------------------- */ delay(100); } /* Action based on data * ------------------------------------------------------------------- */ { ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue } if (ultrasoundValue > 800) { /* Drive straight forward *----------------------------------------------- */ analogWrite(motorpinleft, 255); //100% speed analogWrite(motorpinright, 255); //100% speed0 } /*------------------------------------------------ */ else /* Turn hard right *--------------------------------------------- */ { analogWrite(motorpinleft, 0); //stop left motor analogWrite(motorpinright, 0); //stop right motor analogWrite(motorpinrevright, 0); // stop right rev motor analogWrite(motorpinrevleft, 0); // stop left rev motor analogWrite(motorpinrevright, 255); //100% speed analogWrite(motorpinleft, 255); //100% speed delay(380); //380 milliseconds analogWrite(motorpinrevright, 0); // off analogWrite(motorpinleft, 0); // off /*---------------------------------------------- */ } /* Backup and turn right when switch gets bumped and closes circuit to ground *--------------------------------------------------- */ /* */ digitalWrite(switchPin, HIGH); // Sets the pin to high swval = digitalRead(switchPin); // Read input value and store it if (swval == LOW) { analogWrite(motorpinleft, 0); //stop left motor analogWrite(motorpinright, 0); //stop right motor analogWrite(motorpinrevleft, 0); // stop left rev motor analogWrite(motorpinrevright, 0); // stop right rev motor analogWrite(motorpinrevleft, 255); //100% speed analogWrite(motorpinrevright, 255); //100% speed delay(800); //800 milliseconds analogWrite(motorpinrevleft, 0); // off analogWrite(motorpinrevright, 0); // off analogWrite(motorpinrevright, 255); //100% reverse speed analogWrite(motorpinleft, 255); //100% forward speed delay(700); //700 milliseconds analogWrite(motorpinrevright, 0); // off analogWrite(motorpinleft, 0); // off delay(50); //50 milliseconds } /*------------------------------------------------ */ } UPDATE I tried deleting some stuff and changing some stuff. When I turn on the robot noting happens. Here is the code after the changes. * Rumblebot Driving with object avoidance utiliszing PING Ultrasound Sensor * and a bump switch. * Reads values (00014-01199) from an ultrasound sensor (Parallax PING) * * Version 1.1.2 Motor runs and drives full time unless object detected. *-------------------------------------------------------------------- * * * * * * */ int switchPin= 2; // Right bump switch on pin 2 int swval; // Variable for reading switch status int ultraSoundSignal = 7; // Ultrasound signal pin int val = 0; int ultrasoundValue = 0; int timecount = 0; // Echo counter int ledPin = 13; // LED connected to digital pin 13 int motorpinright = 10; // pin for left motor reverse int motorpinleft = 11; // pin for left motor forward int motorpinrevright = 5; // pin for right motor reverse int motorpinrevleft = 6; // pin for right motor forward void setup() { pinMode(switchPin, INPUT); // Sets the digital pin as input pinMode(ledPin, OUTPUT); // Sets the digital pin as output pinMode(motorpinright, OUTPUT); // Motor drives----------- pinMode(motorpinleft, OUTPUT); //------------------------ pinMode(motorpinrevright, OUTPUT); //------------------------ pinMode(motorpinrevleft, OUTPUT); //------------------------ } void loop() { /* Start Scan * -------------------------------------------------- */{ timecount = 0; val = 0; pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output /* Send low-high-low pulse to activate the trigger pulse of the sensor /* Delay of program * ------------------------------------------------------------------- */ delay(100); } /* Action based on data * ------------------------------------------------------------------- */ { ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue } if (true) { /* Drive straight forward *----------------------------------------------- */ analogWrite(motorpinleft, 255); //100% speed analogWrite(motorpinright, 255); //100% speed0 } /*------------------------------------------------ */ else /* Turn hard right *--------------------------------------------- */ { analogWrite(motorpinleft, 0); //stop left motor analogWrite(motorpinright, 0); //stop right motor analogWrite(motorpinrevright, 0); // stop right rev motor analogWrite(motorpinrevleft, 0); // stop left rev motor analogWrite(motorpinrevright, 255); //100% speed analogWrite(motorpinleft, 255); //100% speed delay(380); //380 milliseconds analogWrite(motorpinrevright, 0); // off analogWrite(motorpinleft, 0); // off /*---------------------------------------------- */ } /* Backup and turn right when switch gets bumped and closes circuit to ground *--------------------------------------------------- */ /* */ digitalWrite(switchPin, HIGH); // Sets the pin to high swval = digitalRead(switchPin); // Read input value and store it if (swval == LOW) { analogWrite(motorpinleft, 0); //stop left motor analogWrite(motorpinright, 0); //stop right motor analogWrite(motorpinrevleft, 0); // stop left rev motor analogWrite(motorpinrevright, 0); // stop right rev motor analogWrite(motorpinrevleft, 255); //100% speed analogWrite(motorpinrevright, 255); //100% speed delay(800); //800 milliseconds analogWrite(motorpinrevleft, 0); // off analogWrite(motorpinrevright, 0); // off analogWrite(motorpinrevright, 255); //100% reverse speed analogWrite(motorpinleft, 255); //100% forward speed delay(700); //700 milliseconds analogWrite(motorpinrevright, 0); // off analogWrite(motorpinleft, 0); // off delay(50); //50 milliseconds } /*------------------------------------------------ */ }

Question by TOCO   |  last reply


Need help with Arduino. Xbees won't connect when I upload my code?

I am working on a RC Gripper lifter that works with 2 Servos and 2 DC motors. For wireless control I am using a Series 1 configured Xbee. Now the problem is that the Xbees don't connect when I upload the code. They do connect if I upload some other small code. Here's the Sender Code int potGripper = 1;   int potLifter = 2;   //int oldGripper = 0;   int newGripper = 0;   //int oldLifter = 0;   int newLifter = 0;   int midPin = 2;   int leftPin = 3;   int newGear =0;   int oldGear=1; void setup() {   Serial.begin(9600); pinMode(midPin, INPUT); pinMode(leftPin, INPUT); pinMode(potGripper, INPUT); pinMode(potLifter, INPUT); } void loop() {   if ( digitalRead(midPin) == LOW)   {      oldGear = 1;   }   else if ( digitalRead(leftPin) == LOW)   {       oldGear = 2;   }     int oldGripper = analogRead(potGripper);   int oldLifter = analogRead(potLifter);   int Grippervalue = map(oldGripper,0,1023,0,9);   int Liftervalue = map(oldLifter,0,1023,0,9);   if(newGripper != Grippervalue)   {     Serial.println('!');     Serial.println(Grippervalue);     Serial.println('#');     newGripper = Grippervalue;   }   else if(newLifter != Liftervalue)   {     Serial.println('@');     Serial.println(Liftervalue);     Serial.println('#');     newLifter = Liftervalue;   }   else if( newGear != oldGear)   {     Serial.println(';');     Serial.println(oldGear);     Serial.println('#');     newGear = oldGear;   }   delay(500); } And here's the receiver code- #include //If serial dsn't work as expected, add  while(Serial.available()>0) Serial.read(); at end of each loop! int gripperPin = 9; int lifterPin = 10; int rpmData = 0; int motorLeft, motorRight, gripperData, lifterData, angle, flag; Servo myGripper; Servo myLifter; void setup() {   Serial.begin(9600);   myGripper.attach(gripperPin);   myLifter.attach(lifterPin);   delay(500); } void loop() {   while( Serial.available() == 0);   int data = Serial.read() - '0'; if (data >=0)   {     if(data == ';') // For setting the motor RPM     {       rpmData= Serial.read() - '0';       if (rpmData == 0)       {        motorLeft= 300;        motorRight= 250;       }       else if (rpmData == 1)       {         motorLeft= 200;         motorRight= 150;       }     }     if (data == '!') // For the Gripper     {       gripperData = Serial.read() - '0';       angle= map(gripperData, 0, 9, 0, 80);       myGripper.write(angle);      }     if (data == '@') // For the Lifter     {       lifterData = Serial.read() - '0';       angle= map(lifterData, 0, 9, 0, 160);       myLifter.write(angle);     }     //if (data == '%') // For the Buttons      if (data == '#') // For marking end of Serial Data      {       flag = 0;      }      }     } My main aim is to send a value between 0-9 from one arduino to another so that I can map it on the other arduino from 0-160 and 0-80 (I am using 2 servos). I have used a symbol to differentiate the values from each other so that the correct value reaches the desired servo/motor. Please help me figure out my mistake..

Question by ReshamP   |  last reply


Arduino stop the loop?

I have a problem with my code, i basically move a motor with the help of 3 relays, when a sensor does not detect the presence of an object part of a call, everything works perfectly, if it was after having called the function CHIAMATA() the arduino loop() stop unexplains, i certainly made a mistake, but i do not understand which. thanks for your help this is the code.... #include #include #include swRTC rtc; //create a new istance of the lib SoftwareSerial mySerial(3, 2); const int buttonPin = 19; const int sensorPin = 9; const int allarmPin =  13; int buttonState = 0; int sensorState = 0; int relay1 = 8; int relay2 = 7; int relay3 = 6; int var = 0; // initialize the stepper library on pins 8 through 11: void setup() {     rtc.stopRTC(); //stop the RTC     rtc.setTime(12,0,0); //set the time here     rtc.setDate(4,6,2012); //set the date here     rtc.startRTC(); //start the RTC   Serial.begin(19200); //choose the serial speed here   mySerial.begin(19200);   pinMode(allarmPin, OUTPUT); } void loop() { while(mySerial.available()!=0);{}delay(10);     Serial.print(rtc.getHours(), DEC);     Serial.print(":");     Serial.print(rtc.getMinutes(), DEC);     Serial.print(":");    Serial.print(rtc.getSeconds(), DEC);     Serial.println(" "); //stato riserva croccantini sensorState = digitalRead(sensorPin); if (sensorState == HIGH) {     // turn LED on:     digitalWrite(allarmPin, HIGH);     Serial.println("Croccantini esauriti");     Serial.println("Spia allarme ACCESA");     Serial.println("Tramoggia DISABILITATA");     Serial.println("Imposto la chiamata");     while(sensorState == HIGH) {CHIAMATA(); break;}   } else {     // turn LED off:     digitalWrite(allarmPin, LOW);     Serial.println("Croccantini OK");   } if (sensorState == LOW && rtc.getHours()== 12 && rtc.getMinutes()== 00 && rtc.getSeconds()== 5) {startmotor();}   //start manuale carico/scarico   // read the state of the pushbutton value:   buttonState = digitalRead(buttonPin);   // check if the pushbutton is pressed.   // if it is, the buttonState is HIGH:     if (buttonState == 1) {       Serial.print("Pulsante alimentazione manuale ATTIVO");                               // turn on:   // singlestartmotor();   }         } void startmotor(){ //numero di cicli di carico da eseguire (5) while(var < 5){ pinMode(relay1, OUTPUT);   pinMode(relay2, OUTPUT);     pinMode(relay3, OUTPUT); digitalWrite(relay3, LOW); //ABILITA TUTTO //AVANTI digitalWrite(relay1, LOW); digitalWrite(relay2, LOW); Serial.print("AVANTI"); delay(1000); // wait 2 seconds digitalWrite(relay3, HIGH);//STOP TUTTO digitalWrite(relay1, HIGH); digitalWrite(relay2, HIGH); delay(1000); //ATTESA PER INVERSIONE MARCIA //INDIETRO digitalWrite(relay3, LOW);//ABILITA TUTTO digitalWrite(relay1, HIGH); digitalWrite(relay2, HIGH); Serial.print("INDIETRO"); delay(1000); // wait 2 seconds   digitalWrite(relay3, HIGH);//STOP TUTTO   delay(5000); // wait 2 seconds   var++; }} void CHIAMATA() { mySerial.println("ATD329xxxxx135;");//dial the number, xxxx ix the phone number. delay(100); Serial.print("Chiamata in corso..."); return loop();}

Question by cris92   |  last reply


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   |  last reply


Can you help me to find error in the code?

Hi! When I try to upload it, error occurs: "expected unqualified-id before numeric constant" Here is the code: #include #include #include #define ONE_WIRE_BUS 10 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire;); LiquidCrystal lcd(1, 2, 4, 5, 6, 7);  #define trigPin 8 #define echoPin 9 #define button 22 #define temp 10 int w=0; void setup() {    pinMode(trigPin, OUTPUT);   pinMode(echoPin, INPUT);   pinMode(button, INPUT);   pinMode(temp,INPUT);   sensors.begin();       lcd.begin(16,2);        lcd.setCursor(0,0);     } void loop() {w = digitalRead(button);   if(w == LOW) ultrasonic();     if(w == HIGH) void temp(); } void ultrasonic() {   lcd.print("Target Distance:");   long duration, distance;   digitalWrite(trigPin, LOW);   delayMicroseconds(2);   digitalWrite(trigPin, HIGH);   delayMicroseconds(10);   digitalWrite(trigPin, LOW);   duration = pulseIn(echoPin, HIGH);   distance = (duration/2) / 29.1;   lcd.setCursor(0,1);   lcd.print("                ");   lcd.setCursor(0,1);    lcd.print(distance);   delay(250);   lcd.clear(); } void temp() { lcd.setCursor(0,0); lcd.print("TEMPERATURE"); lcd.setCursor(0,1); sensors.requestTemperatures(); lcd.print(sensors.getTempCByIndex(0)); } Thanks for help!

Question by KacperK8   |  last reply


NodeMCU to NodeMCU communication

Dear All,I am really a newbie here playing with two NodeMCUs. I started out with basics and after a while I stepped into my actual project. The project is to display toilet status indicator. My plan is to pick up the data from PIR sensor and feed it to one NodeMCU and have another NodeMCU process the data on the other end of the room and display the status on and I2c 16 x 2 LCD. I was able to connect the PIR and LCD onto one NodeMCU and test it and things were fine. I am really looking for some help to use TCP/IP protocol to have the nodeMCUs communicate to each other.My basic code is as below:#include#include int sensor = 13;LiquidCrystal_I2C lcd(0x27, 16, 2);void setup(){ Serial.begin(115200);Wire.begin(D2, D1); pinMode(sensor, INPUT); pinMode(LED_BUILTIN, OUTPUT);lcd.begin(); }void loop (){ long state = digitalRead(13); if (state == HIGH){ Serial.println("Motion recognized"); lcd.setCursor(5, 0); lcd.print("RESTROOM IS"); lcd.setCursor(0, 1); lcd.print("OCCUPIED"); digitalWrite (LED_BUILTIN, LOW); delay(5000); lcd.clear(); } else { if (state == LOW); Serial.println("Motion Absent!"); lcd.setCursor(0, 1); lcd.print("NOW VACANT"); digitalWrite(LED_BUILTIN, HIGH); delay(5000); lcd.clear(); }}Thanks for any help you can provide or guide me to examples.

Question by BharatharajV 


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   |  last reply


Toggling LCD Backlight with arduino ?

Hey, I'm working on a project where I need my LCD to toggle between On/Off.  By default, the LCD is OFF showing nothing. When button is pressed, LCD should be ON. When the button is pressed again, the LCD will display a “shutdown” warning message at which the user can confirm or cancel. Right now, I just need the ON/OFF function to work (without warning message). This is the code I have been trying, but it doesn't work properly. #include #include const int Temp = 0; const int Press = 1;      const int Noise = 2;          const int Settings = 3; const int ON_OFF = 8; const int LCD_LIGHT = A4; int buttonState0 = 0; int buttonState1 = 0; int buttonState2 = 0; int buttonState3 = 0; int buttonState4 = 0; bool isLcdOn = false; LiquidCrystal lcd(12, 11, 4, 5, 6, 7); void setup() {   Serial.begin(9600);   lcd.begin(16, 2);   lcd.noDisplay();   pinMode(Settings, INPUT);   pinMode(Temp, INPUT);   pinMode(Press, INPUT);   pinMode(Noise, INPUT);   pinMode(ON_OFF, INPUT);   pinMode (LCD_LIGHT, OUTPUT);     } void loop() {   buttonState4 = digitalRead(ON_OFF);   if (buttonState4 == LOW)   {     isLcdOn = !isLcdOn;     if(isLcdOn){       lcd.clear();       lcd.setCursor(4, 0);       lcd.print("WELCOME");       lcd.display();       digitalWrite(LCD_LIGHT, HIGH);           }   }     else{       lcd.noDisplay();       digitalWrite(LCD_LIGHT, LOW);     } delay(2000);   }

Question by BME22   |  last reply


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   |  last reply


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   |  last reply


ATtiny85 Supported Commands? Answered

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

Question by WWC   |  last reply


HELP ME ::: want to interface ps/2 mouse using uno to pc

Hi friends, i am new to arduino board. Trying to make a arduino uno based PS/2 mouse by using ps2dev.h... From the example from that the mouse move diagonally only. how to set that in other direction left,right,top,bottom.. // move the mouse diagonally     delta_x = 1;     delta_y = 1;     write_packet() Anyone guide me, how to move right or left or up or down...plz help me #include "ps2dev.h" PS2dev mouse(3,2); // 2 data 3clock char buttons[3] = {0,0,0}; int delta_x = 0; int delta_y = 0; //we start off not enabled int enabled =0; //ack a host command void ack() {   while(mouse.write(0xFA)); } void write_packet() {   char overflowx =0;   char overflowy =0;   char data[3];   int x,y;     if (delta_x > 255) {     overflowx =1;     x=255;   }   if (delta_x < -255) {     overflowx = 1;     x=-255;   }    if (delta_y > 255) {     overflowy =1;     y=255;   }   if (delta_y < -255) {     overflowy = 1;     y=-255;   }     data[0] = ((overflowy & 1) << 7) |     ( (overflowx & 1) << 6) |     ( (((delta_y &0x100)>>8) & 1) << 5) |     ( ( ((delta_x &0x100)>>8)& 1) << 4) |     ( ( 1) << 3) |     ( ( buttons[1] & 1) << 2) |     ( ( buttons[2] & 1) << 1) |     ( ( buttons[0] & 1) << 0) ;       data[1] = delta_x & 0xff;   data[2] = delta_y & 0xff;     mouse.write(data[0]);   mouse.write(data[1]);   mouse.write(data[2]);   delta_x = 0;   delta_y = 0; } int mousecommand(int command) {   unsigned char val;   //This implements enough mouse commands to get by, most of them are   //just acked without really doing anything   switch (command) {   case 0xFF: //reset     ack();     //the while loop lets us wait for the host to be ready     while(mouse.write(0xAA)!=0);      while(mouse.write(0x00)!=0);       break;   case 0xFE: //resend     ack();     break;   case 0xF6: //set defaults     //enter stream mode       ack();     break;   case 0xF5:  //disable data reporting     //FM     ack();     break;   case 0xF4: //enable data reporting     //FM     enabled = 1;     ack();     break;   case 0xF3: //set sample rate     ack();     mouse.read(&val;); // for now drop the new rate on the floor     //      Serial.println(val,HEX);     ack();     break;   case 0xF2: //get device id     ack();     mouse.write(00);     break;   case 0xF0: //set remote mode     ack();      break;   case 0xEE: //set wrap mode     ack();     break;   case 0xEC: //reset wrap mode     ack();     break;   case 0xEB: //read data     ack();     write_packet();     break;   case 0xEA: //set stream mode     ack();     break;   case 0xE9: //status request     ack();     //      send_status();     break;   case 0xE8: //set resolution     ack();     mouse.read(&val;);     //    Serial.println(val,HEX);     ack();     break;   case 0xE7: //set scaling 2:1     ack();     break;   case 0xE6: //set scaling 1:1     ack();     break;   }   } int xcenter ; int ycenter; int xsum = 0; int ysum = 0; void setup() {   unsigned char val;   // send the mouse start up   while(mouse.write(0xAA)!=0);    while(mouse.write(0x00)!=0); } void loop() {   unsigned char  c;   if( (digitalRead(3)==LOW) || (digitalRead(2) == LOW)) {     while(mouse.read(&c;)) ;     mousecommand(c);   } if (enabled) {     // move the mouse diagonally     delta_x = 1;     delta_y = 1;     write_packet()    }   delay(50); }

Question by melwin.a3   |  last reply