Hi i`m new to arduino and i am making a prototype for something at school.
it also has a lamp that needs to turn on randomly but i cant figure out how to make it.
can someone help me? (the lamp needs to turn on at 1)
here is the code:
int randompin = 1;
int lastnumber = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
delay(1000);
randompin = random(1,5);
while(randompin == lastnumber){
randompin = random(1,5);
}
lastnumber = randompin;
Serial.print(randompin);
{
if (digitalRead(1) == HIGH)
{
digitalWrite(1, HIGH);
}
else
{
digitalWrite(1, LOW);
}
}
}
What is connected to pin 1 ?
MarkT
December 23, 2017, 5:19pm
3
You spend some effort setting up randompin variable, then only print it.
You read pin 1 and if its high you set pin 1 high? Doesn't make sense.
i have a lamp connected to pin one
and markt i mean with that if the random number generator goes to one it should power pin one, but there is probably something wrong with it.
now it is just on all the time
Perhaps it might work better if your if statement checked if randompin is equal to 1 rather than if pin1 is HIGH?
Steve
Pin 1 is also used for serial communications. Can your program cope with that?
i changed it and now it works this is what i have now:
int boven = 2;
int rechts = 3;
int links = 4;
int randomnumber = 1;
int lastnumber = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(boven, OUTPUT);
pinMode(rechts, OUTPUT);
pinMode(links, OUTPUT);
randomSeed( analogRead(A0) );
}
void loop() {
// put your main code here, to run repeatedly:
randomnumber = random(2,5);
Serial.println(randomnumber);
while(randomnumber == lastnumber){
randomnumber = random(1,5);
}
digitalWrite(randomnumber, HIGH);
delay(300);
digitalWrite(randomnumber, LOW);
}
Well that's very different from what you said you wanted, particularly the way you write to a random pin number.
You do know that "while" statement does nothing because you never set lastnumber to anything other than 0 and randomnumber can never be 0?
But if you like what it's doing that's great!
Steve