I have a question about arduino considering a setup with 8 leds and an potentiometer. I want to let 1 led light up, which is the led that matches the value returned by the potentiometer, and the rest of the leds should be turned off. Furthermore, when I change the position of the potentiometer, the leds should change accordingly. So far ive got this:
for(int i = 0; i)
{
if (i = draaiKnopStand)
{
status[i] = HIGH;
}
else
{
status[i] = LOW;
}
digitalWrite(draaiKnopStand, status[i]);
}
I'm considering this is Arduino Uno Front
I have no Arduino here in my job. I did this using a simulator. Please try it:
int _potentiometer = 9; // Potentiometer - Analog Pin
int _val = 0;
int _borderLineVal = 0;
int ledPins[] = { 2, 3, 4, 5, 6, 7 }; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() {
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
_val = analogRead(_potentiometer); //reading the Potentiometer value interval: 0 - 1023
_borderLineVal = (int)(1023 / pinCount);
Serial.println(_val);
// turn all leds off
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
digitalWrite(ledPins[thisPin], LOW);
}
// turn the select led on
if(_val > 0){
_pinHigh = (int)(1023 / _borderLineVal);
digitalWrite(ledPins[_pinHigh], HIGH); // turn the pin on
}
}
Related
Sorry to bother you but I have been having issues getting my a motor array to output in this code here.
// initialise motors
// Motor 1
//int in1 = 4;
//int in2 = 2 ;
// Motor 2
//int in3 = 8;
//int in4 = 7;
// Motor 3
//int in5 = 12;
//int in6 = 13;
// Motor 4
//int in7 = 9;
//int in8 = 10;
// Array of PWM's
int thisPin = 0;
uint8_t pwms[] = {3,5,6,11};
byte numberPwms = 4;
// Array for output channels
// Motor 1 (4 = High, 2 = Low)
// Motor 2 (8 = High, 7 = Low)
// Motor 3 (12 = High, 13 = Low)
// Motor 4 (9 = High, 10 = Low)
int mtrpin = 0;
uint8_t motors[] = {4,2,8,7,12,13,9,10};
byte motorPin = 8;
void setup()
{
// pinMode(in1, OUTPUT);
// pinMode(in2, OUTPUT);
// pinMode(in3, OUTPUT);
// pinMode(in4, OUTPUT);
// pinMode(in5, OUTPUT);
// pinMode(in6, OUTPUT);
// pinMode(in7, OUTPUT);
// pinMode(in8, OUTPUT);
for (pwmPin = 0; pwmPin < numberPwms; pwmPin++){
for (mtrPin = 0; mtrpin < motorPin; mtrPin++){
pinMode(motors[mtrPin], OUTPUT);
pinMode(pwms[pwmPin], OUTPUT);
};
};
}
void motorLoop(){
// setting the direction to turn and speed
// digitalWrite(in1, HIGH); // Motor 2
// digitalWrite(in2, LOW);
// digitalWrite(in3, HIGH); // Motor 2
// digitalWrite(in4, LOW);
// digitalWrite(in5, HIGH); // Motor 3
// digitalWrite(in6, LOW);
// digitalWrite(in7, HIGH); // Motor 4
// digitalWrite(in8, LOW);
// Set the speed for the Motors
for(int pwmPin = 0; pwmPin < numberPwms; pwmPin++){
for (mtrPin = 0; mtrpin < motorPin; mtrPin++){
pinMode(motors[mtrPin], LOW);
analogWrite(pwms[pwmPin], 200);
};
};
};
void loop()
{
motorLoop();
delay(500);
}
I have managed to get the initial call to work but I am now turning it all into arrays.
I have managed to get it to work for the PWMs but now after adding the motors array it has stopped working and gives this error message.
In Function 'Void setup()';
41:8: error: 'pwmPin' was not declared in this scope
42:11: error: 'mtrPin' was not declared in this scope
In function 'void motorLoop()';
74:8: error: 'mtrPin' was not declare in this scope.
I know the error will probably be really simple but I can't find to save my life.
Also the for loops have been called as they are now and separate and I am still getting the same errors.
You can see this code at https://www.tinkercad.com/things/fFQKRTjhDrb-motor-initial-turn/editel.
Any help on this would be greatly appreciated :)
In Function 'Void setup()'; 41:8: error: 'pwmPin' was not declared in this scope 42:11: error: 'mtrPin' was not declared in this scope In function 'void motorLoop()'; 74:8: error: 'mtrPin' was not declare in this scope.
As the compiler says: mtrPin has not been declared, and yet, you are using it.
Declarations introduce names in a program, like the name of your variable mtrPin. Other examples are namespaces, functions and classes. A name must be declared before it can be used. You cannot refer to a name which is declared later in the code.
int mtrPin; // this is a (uninitialized) declaration -> mtrPin can be used
int mtrPin { 0 }; // this is a (value) initialization -> mtrPin can be used
I'm trying to make a Whack-A-Mole game using an Arduino Mega with 10 LEDs (Moles) and 10 Push Buttons (Whack). The electronics are completed and tested, everything works fine. It also has a BLE radio attached which prompts the board to start one of three games I plan to do.
The problem I'm having is this:
In my main loop, I listen for a command from the app coming via BLE. When a "1" is sent by the app (serial pass through), I call the function
playGameOne();
The main thing is that everything loops in the main loop fine, but when I jump to the game function, it runs once and returns back to the main loop again. How can I keep the user looping in the game function until the game is over? Oh - and I'm not trying to use any Interrupts, but I imagine thats one way of doing it.
The latest incarnation of the game function looks like this:
//////////////////////////////////////////////
////////////////// GAME 1 //////////////////
void gameOne(){
//var int eTime;
// inform player game is about to begin
playCountdown();
Serial.println("Game Begun");
// initialize var to count time
elapsedMillis timeElapsed;
if(gameState < 1){
gameOneOne();
Serial.print("Game finished - Your time: ");
Serial.println(timeElapsed);
}
}
void gameOneOne(){
while(digitalRead(btPin31) == LOW){
// turn on LED45
digitalWrite(ledPin45, HIGH);
// wait for user to push corresponding button
if(digitalRead(btPin31) == HIGH){
// turn off the LED and jump to next LED - gameOneTwo()
digitalWrite(ledPin45, LOW);
gameOneTwo();
}
}
}
void gameOneTwo(){
while(digitalRead(btPin39) == LOW){
// turn on LED53
digitalWrite(ledPin53, HIGH);
if(digitalRead(btPin39) == HIGH){
digitalWrite(ledPin53, LOW);
// Finish the game, set state to 1
gameState = 1;
}
}
}
Not only this doesn't work, I highly doubt this is the proper way of coding games. In fact the ideal would be to have a Game Script that can be uploaded dynamically. The game Script would look like:
Header {name of game}
45 {pin of first LED}
500 {how long to keep it on, in ms}
49 {pin of the second LED}
500 {how long to keep it on, in ms}
... and so on
End of File
What is the best resource to learn this properly.
EDIT
Here's my main loop
// included header files
#include <elapsedMillis.h> // Measuring Elapsed Time Library
// Constant - Piezzo Speaker Pin
const int beepPin = 11; // the number of the Piezo Spkr pin
// Constants - Button Pins
const int btPin30 = 30;
const int btPin31 = 31;
const int btPin32 = 32;
const int btPin33 = 33;
const int btPin34 = 34;
const int btPin35 = 35;
const int btPin36 = 36;
const int btPin37 = 37;
const int btPin38 = 38;
const int btPin39 = 39;
// Constants - LED Pins
const int ledPin53 = 53;
const int ledPin52 = 52;
const int ledPin51 = 51;
const int ledPin50 = 50;
const int ledPin49 = 49;
const int ledPin48 = 48;
const int ledPin47 = 47;
const int ledPin46 = 46;
const int ledPin45 = 45;
const int ledPin44 = 44;
//Variable for storing BLUETOOTH received data
char data = 0;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int btPin30State = 0;
int btPin31State = 0;
int btPin32State = 0;
int btPin33State = 0;
int btPin34State = 0;
int btPin35State = 0;
int btPin36State = 0;
int btPin37State = 0;
int btPin38State = 0;
int btPin39State = 0;
// declare game state variable
int gameState = 0;
void setup() {
// initialize Serial Comms for Debug (0) and BT(3)
Serial.begin(9600); //Sets the buad for Serial (debug port)
Serial3.begin(9600); //Sets the baud for Serial3 data transmission
// initialize all button pins as INPUTs
for (int x = 30; x <= 39; x++){
pinMode(x, INPUT);
}
// initialize LED pins as OUTPUTs:
for (int i = 44; i <= 53; i++){
pinMode(i, OUTPUT);
}
// lightup all LEDs
for (int j = 44; j <= 53; j++){
digitalWrite(j, HIGH);
delay(100);
}
// prompt device is ready
Serial.println("Device Ready");
}
void loop() {
// Read Data from Serial3 -- This is to get initial game status/command from app/bluetooth
if(Serial3.available() > 0) { // Send data only when you receive data:
data = Serial3.read();
// See what the command is
if(data == '1') {
Serial.write("Send it to GameOne");
Serial.write("\n");
gameOne();
}
// See what the command is
if(data == '2') {
Serial.write("Send it to GameTwo");
Serial.write("\n");
gameTwo();
}
if(data == '3') {
Serial.write("Send it to GameThree");
Serial.write("\n");
gameThree();
}
if(data == '4') {
Serial.write("Test");
Serial.write("\n");
}
}
btPin30State = digitalRead(btPin30);
btPin31State = digitalRead(btPin31);
btPin32State = digitalRead(btPin32);
btPin33State = digitalRead(btPin33);
btPin34State = digitalRead(btPin34);
btPin35State = digitalRead(btPin35);
btPin36State = digitalRead(btPin36);
btPin37State = digitalRead(btPin37);
btPin38State = digitalRead(btPin38);
btPin39State = digitalRead(btPin39);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (btPin30State == HIGH) {
digitalWrite(ledPin44, HIGH);
tone(11, 1000, 500);
Serial.println("BTN 30 / LED 44");
gameOne();
} else {
digitalWrite(ledPin44, LOW);
}
if (btPin31State == HIGH) {
digitalWrite(ledPin45, HIGH);
Serial.println("BTN 31 / LED 45");
} else {
digitalWrite(ledPin45, LOW);
}
if (btPin32State == HIGH) {
digitalWrite(ledPin46, HIGH);
Serial.println("BTN 32 / LED 46");
} else {
digitalWrite(ledPin46, LOW);
}
if (btPin33State == HIGH) {
digitalWrite(ledPin47, HIGH);
Serial.println("BTN 33 / LED 47");
} else {
digitalWrite(ledPin47, LOW);
}
if (btPin34State == HIGH) {
digitalWrite(ledPin48, HIGH);
Serial.println("BTN 34 / LED 48");
} else {
digitalWrite(ledPin48, LOW);
}
if (btPin35State == HIGH) {
digitalWrite(ledPin49, HIGH);
Serial.println("BTN 35 / LED 49");
} else {
digitalWrite(ledPin49, LOW);
}
if (btPin36State == HIGH) {
digitalWrite(ledPin50, HIGH);
Serial.println("BTN 36 / LED 50");
} else {
digitalWrite(ledPin50, LOW);
}
if (btPin37State == HIGH) {
digitalWrite(ledPin51, HIGH);
Serial.println("BTN 37 / LED 51");
} else {
digitalWrite(ledPin51, LOW);
}
if (btPin38State == HIGH) {
digitalWrite(ledPin52, HIGH);
Serial.println("BTN 38 / LED 52");
} else {
digitalWrite(ledPin52, LOW);
}
if (btPin39State == HIGH) {
digitalWrite(ledPin53, HIGH);
Serial.println("BTN 39 / LED 53");
} else {
digitalWrite(ledPin53, LOW);
}
}
I think it would be ok to structure it something like this.
play_a_game:
for (some_number_of_times)
{
show_a_mole_and_let_them_wackit();
}
setup:
set up pins
say the game is starting
loop:
do
{
play_a_game();
}
while(game ending button not pressed and less then 10 moles have died);
say the game is over
I'm doing project like this http://grathio.com/2013/11/new-old-project-secret-knock-drawer-lock/ The project only process time interval between knock, and I try to add amplitude as input, if I just use the code from the link above it works fine but I want to add amplitude (loud and soft knock) as input too. But my code still have problem, it can't recognise knock and the LED acting weird. I need to recognise knock time interval and knock amplitude. Comment 'This is what I add' is the code that I add myself, but the code doesn't work. Could anyone tell me what is wrong with my code?
Below is the code:
#include <EEPROM.h>
const byte eepromValid = 123; // If the first byte in eeprom is this then the data is valid.
/*Pin definitions*/
const int programButton = 0; // Record A New Knock button.
const int ledPin = 1; // The built in LED
const int knockSensor = 1; // (Analog 1) for using the piezo as an input device. (aka knock sensor)
const int audioOut = 2; // (Digial 2) for using the peizo as an output device. (Thing that goes beep.)
const int lockPin = 3; // The pin that activates the solenoid lock.
/*Tuning constants. Changing the values below changes the behavior of the device.*/
int threshold = 3; // Minimum signal from the piezo to register as a knock. Higher = less sensitive. Typical values 1 - 10
const int rejectValue = 25; // If an individual knock is off by this percentage of a knock we don't unlock. Typical values 10-30
const int averageRejectValue = 15; // If the average timing of all the knocks is off by this percent we don't unlock. Typical values 5-20
const int knockFadeTime = 150; // Milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int lockOperateTime = 2500; // Milliseconds that we operate the lock solenoid latch before releasing it.
const int maximumKnocks = 20; // Maximum number of knocks to listen for.
const int maximumAmp = 20; // This is what i add
const int ampLoud = 10; // This is what i add
const int ampSoft = 20; // This is what i add
const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished. (milliseconds)
byte secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits."
byte secretAmp[maximumAmp] = {10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // This is what i add
int knockReadings[maximumKnocks]; // When someone knocks this array fills with the delays between knocks.
int ampReadings[maximumAmp]; // This is what i add
int knockSensorValue = 0; // Last reading of the knock sensor.
int amp = 0; // This is what i add
boolean programModeActive = false; // True if we're trying to program a new knock.
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(lockPin, OUTPUT);
readSecretKnock(); // Load the secret knock (if any) from EEPROM.
doorUnlock(500); // Unlock the door for a bit when we power up. For system check and to allow a way in if the key is forgotten.
delay(500); // This delay is here because the solenoid lock returning to place can otherwise trigger and inadvertent knock.
}
void loop() {
// Listen for any knock at all.
knockSensorValue = analogRead(knockSensor);
if (digitalRead(programButton) == HIGH){ // is the program button pressed?
delay(100); // Cheap debounce.
if (digitalRead(programButton) == HIGH){
if (programModeActive == false){ // If we're not in programming mode, turn it on.
programModeActive = true; // Remember we're in programming mode.
digitalWrite(ledPin, HIGH); // Turn on the red light too so the user knows we're programming.
chirp(500, 1500); // And play a tone in case the user can't see the LED.
chirp(500, 1000);
} else { // If we are in programing mode, turn it off.
programModeActive = false;
digitalWrite(ledPin, LOW);
chirp(500, 1000); // Turn off the programming LED and play a sad note.
chirp(500, 1500);
delay(500);
}
while (digitalRead(programButton) == HIGH){
delay(10); // Hang around until the button is released.
}
}
delay(250); // Another cheap debounce. Longer because releasing the button can sometimes be sensed as a knock.
}
if (knockSensorValue >= threshold){
if (programModeActive == true){ // Blink the LED when we sense a knock.
digitalWrite(ledPin, LOW);
} else {
digitalWrite(ledPin, HIGH);
}
knockDelay();
if (programModeActive == true){ // Un-blink the LED.
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
listenToSecretKnock(); // We have our first knock. Go and see what other knocks are in store...
}
}
// Records the timing of knocks.
void listenToSecretKnock(){
int i = 0;
int j = 0;
// First reset the listening array.
for (i=0; i < maximumKnocks; i++){
knockReadings[i] = 0;
}
for (j=0; j < maximumAmp; j++){ // This is what i add
ampReadings[j] = 0;
}
int currentKnockNumber = 0; // Position counter for the array.
int currentAmpNumber = 0;
int startTime = millis(); // Reference for when this knock started.
int now = millis();
do { // Listen for the next knock or wait for it to timeout.
knockSensorValue = analogRead(knockSensor);
//===========================================================================================================
if(knockSensorValue >=3 && knockSensorValue <=75){ // This is what i add
amp = ampSoft; // This is what i add
}
if(knockSensorValue >=76){ // This is what i add
amp = ampLoud; // This is what i add
}
ampReadings[currentAmpNumber] = amp; // This is what i add
currentAmpNumber++; // This is what i add
//===========================================================================================================
if (knockSensorValue >= threshold){ // Here's another knock. Save the time between knocks.
now=millis();
knockReadings[currentKnockNumber] = now - startTime;
currentKnockNumber ++;
startTime = now;
if (programModeActive==true){ // Blink the LED when we sense a knock.
digitalWrite(ledPin, LOW);
} else {
digitalWrite(ledPin, HIGH);
}
knockDelay();
if (programModeActive == true){ // Un-blink the LED.
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
now = millis();
// Stop listening if there are too many knocks or there is too much time between knocks.
} while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
//we've got our knock recorded, lets see if it's valid
if (programModeActive == false){ // Only do this if we're not recording a new knock.
if (validateKnock() == true){
doorUnlock(lockOperateTime);
} else {
// knock is invalid. Blink the LED as a warning to others.
for (i=0; i < 4; i++){
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
}
}
} else { // If we're in programming mode we still validate the lock because it makes some numbers we need, we just don't do anything with the return.
validateKnock();
}
}
// Unlocks the door.
void doorUnlock(int delayTime){
digitalWrite(ledPin, HIGH);
digitalWrite(lockPin, HIGH);
delay(delayTime);
digitalWrite(lockPin, LOW);
digitalWrite(ledPin, LOW);
delay(500); // This delay is here because releasing the latch can cause a vibration that will be sensed as a knock.
}
// Checks to see if our knock matches the secret.
// Returns true if it's a good knock, false if it's not.
boolean validateKnock(){
int i = 0;
int currentKnockCount = 0;
int secretKnockCount = 0;
int currentAmpCount = 0; // This is what i add
int secretAmpCount = 0; // This is what i add
int maxKnockInterval = 0; // We use this later to normalize the times.
for (i=0;i<maximumKnocks;i++){
if (knockReadings[i] > 0){
currentKnockCount++;
}
if (secretCode[i] > 0){
secretKnockCount++;
}
if (ampReadings[i] > 0){ // This is what i add
currentAmpCount++; // This is what i add
}
if (secretAmp[i] > 0){ // This is what i add
secretAmpCount++; // This is what i add
}
if (knockReadings[i] > maxKnockInterval){ // Collect normalization data while we're looping.
maxKnockInterval = knockReadings[i];
}
}
// If we're recording a new knock, save the info and get out of here.
if (programModeActive == true){
for (i=0; i < maximumKnocks; i++){ // Normalize the time between knocks. (the longest time = 100)
secretCode[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);
}
for (int j = 0; j < maximumAmp; j++){
secretAmp[j] = ampReadings[j];
}
saveSecretKnock(); // save the result to EEPROM
programModeActive = false;
playbackKnock(maxKnockInterval);
return false;
}
if (currentKnockCount != secretKnockCount && currentAmpCount != secretAmpCount){ // Easiest check first. If the number of knocks is wrong, don't unlock. // This is what i add
return false;
}
/* Now we compare the relative intervals of our knocks, not the absolute time between them.
(ie: if you do the same pattern slow or fast it should still open the door.)
This makes it less picky, which while making it less secure can also make it
less of a pain to use if you're tempo is a little slow or fast.
*/
int totaltimeDifferences = 0;
int timeDiff = 0;
for (i=0; i < maximumKnocks; i++){ // Normalize the times
knockReadings[i]= map(knockReadings[i], 0, maxKnockInterval, 0, 100);
timeDiff = abs(knockReadings[i] - secretCode[i]);
if (timeDiff > rejectValue){ // Individual value too far out of whack. No access for this knock!
return false;
}
totaltimeDifferences += timeDiff;
}
// It can also fail if the whole thing is too inaccurate.
if (totaltimeDifferences / secretKnockCount > averageRejectValue){
return false;
}
return true;
}
// reads the secret knock from EEPROM. (if any.)
void readSecretKnock(){
byte reading;
int i;
int j;
reading = EEPROM.read(0);
if (reading == eepromValid){ // only read EEPROM if the signature byte is correct.
for (int i=0; i < maximumKnocks ;i++){
secretCode[i] = EEPROM.read(i+1);
}
for (int j=0; j < maximumAmp ;j++){ // This is what i add
secretAmp[j] = EEPROM.read(j+1); // This is what i add
}
}
}
//saves a new pattern too eeprom
void saveSecretKnock(){
EEPROM.write(0, 0); // clear out the signature. That way we know if we didn't finish the write successfully.
for (int i=0; i < maximumKnocks; i++){
EEPROM.write(i+1, secretCode[i]);
EEPROM.write(i+1, secretAmp[i]); // This is what i add
}
EEPROM.write(0, eepromValid); // all good. Write the signature so we'll know it's all good.
}
// Plays back the pattern of the knock in blinks and beeps
void playbackKnock(int maxKnockInterval){
digitalWrite(ledPin, LOW);
delay(1000);
digitalWrite(ledPin, HIGH);
chirp(200, 1800);
for (int i = 0; i < maximumKnocks ; i++){
digitalWrite(ledPin, LOW);
// only turn it on if there's a delay
if (secretCode[i] > 0){
delay(map(secretCode[i], 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly.
digitalWrite(ledPin, HIGH);
chirp(200, 1800);
}
}
digitalWrite(ledPin, LOW);
}
// Deals with the knock delay thingy.
void knockDelay(){
int itterations = (knockFadeTime / 20); // Wait for the peak to dissipate before listening to next one.
for (int i=0; i < itterations; i++){
delay(10);
analogRead(knockSensor); // This is done in an attempt to defuse the analog sensor's capacitor that will give false readings on high impedance sensors.
delay(10);
}
}
// Plays a non-musical tone on the piezo.
// playTime = milliseconds to play the tone
// delayTime = time in microseconds between ticks. (smaller=higher pitch tone.)
void chirp(int playTime, int delayTime){
long loopTime = (playTime * 1000L) / delayTime;
pinMode(audioOut, OUTPUT);
for(int i=0; i < loopTime; i++){
digitalWrite(audioOut, HIGH);
delayMicroseconds(delayTime);
digitalWrite(audioOut, LOW);
}
pinMode(audioOut, INPUT);
}
I'm guessing that you are wanting to record the knock pattern and knock volume at the same time. So that a similar pattern with softer or louder knocks will not activate the lock. If this is the case, I would suggest that you make the array mySecretKnock a 2 dimensional array.
Then use two variables to record the analog and digital inputs.
Capture them one after the other in the same control structure.
i.e. If the value of one is high enough to trigger the if statement just record the value of the other one on the next line of code.
Keep in mind that the analog input will be lower if processed after the digital one, so you may have to adjust your threshold numbers
I'm programming Arduino. I have a problem with the IR sensor. It only detects this ball (equiped with IR LEDS) in range of 0,5m and I would need at least 2m. This is the ball:
"http://drgraeme.net/drgraeme-free-nxt-g-tutorials/Ch108/SoccerGenIINXTG/Soccer%20Ball/HiTechnicRCJ05V2.jpg"
and this is my arduino code:
// digital pin 2 has a pushbutton attached to it. Give it a name:
int IR = 2;
int i = 0;
int ii = 0;
int led = 0;
void setup()
{
Serial.begin(9600);
pinMode(IR, INPUT_PULLUP);
pinMode(led, OUTPUT);
}
void loop() {
i = 0;
ii = 0;
do
{
i = i + 1;
int STANJE1 = digitalRead(IR);
if(STANJE1 < 1)
{
ii = ii + 1;
}
}while(i<1000);
if(ii > 1)
{Serial.println("IS");}
else{Serial.println("IS NOT");}
}
IR sensor is 38kHZ and the balls LEDs are 40kHZ, but I found a program that allowed me to detect the ball 10m away from sensor, but It was ment for something else, and I didn't understand it, so that is not the problem.
This is the code that works further (That's because it doesn't use "DigitalRead()")
/* Raw IR decoder sketch!
This sketch/program uses the Arduno and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/
// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20
// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing
void setup(void) {
Serial.begin(9600);
Serial.println("Ready to decode IR!");
}
void loop(void) {
uint16_t highpulse, lowpulse; // temporary storage timing
highpulse = lowpulse = 0; // start out with no pulse length
// while (digitalRead(IRpin)) { // this is too slow!
while (IRpin_PIN & (1 << IRpin)) {
// pin is still HIGH
// count off another few microseconds
highpulse++;
delayMicroseconds(RESOLUTION);
// If the pulse is too long, we 'timed out' - either nothing
// was received or the code is finished, so print what
// we've grabbed so far, and then reset
if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
printpulses();
currentpulse=0;
return;
}
}
// we didn't time out so lets stash the reading
pulses[currentpulse][0] = highpulse;
// same as above
while (! (IRpin_PIN & _BV(IRpin))) {
// pin is still LOW
lowpulse++;
delayMicroseconds(RESOLUTION);
if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
printpulses();
currentpulse=0;
return;
}
}
pulses[currentpulse][1] = lowpulse;
// we read one high-low pulse successfully, continue!
currentpulse++;
}
void printpulses(void) {
Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
for (uint8_t i = 0; i < currentpulse; i++) {
Serial.print(pulses[i][0] * RESOLUTION, DEC);
Serial.print(" usec, ");
Serial.print(pulses[i][1] * RESOLUTION, DEC);
Serial.println(" usec");
}
}
I am using a LDR to tell me whether there is light or not with an Arduino. My code is pretty simple, but instead of spamming "light light light light" I would like it to say "light" once, and then if the light goes off, for it to say "No light" once.
code edited from "readanalogvoltage":
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
if (voltage > 1.5)
{
Serial.print("Light");
Serial.println();
delay(5000);
}
if (voltage < 1.5)
{
Serial.print("No Light");
Serial.println();
delay(50);
}
}
Keep a variable that holds the last state:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
int wasLit = 0;
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
if (!wasLit && voltage > 1.5) {
wasLit = 1;
Serial.print("Light");
Serial.println();
delay(5000);
} else if(wasLit && voltage <= 1.5) {
wasLit = 0;
Serial.print("No Light");
Serial.println();
delay(50);
}
}
This sort of test will benefit from use of hysterisis. Especially if you have flourescent light, there will be some flicker. That will cause the sensor reading to vary such that it may not change from <1.5 to >=1.5 in a clean manner.
boolean bLast = false;
const float vTrip = 1.5;
// you find a good value for this by looking at the noise in readings
// use a scratch program to just read in a loop
// set this value to something much larger than any variation
const float vHyst = 0.1;
float getLight() {
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
return voltage;
}
void setup() {
// establish the initial state of the light
float v = getLight();
bLast = ( v < (vTrip-vHyst) );
}
void loop() {
float v = getLight();
if( bLast ) {
// light was on
// when looking for decreasing light, test the low limit
if( v < (vTrip-vHyst) ) {
bLast = false;
Serial.print("Dark");
}
}
else {
// light was off
// when looking for increasing light, test the high limit
if( v > (vTrip+vHyst) ) {
bLast = true;
Serial.print("Light");
}
}
}