Huge Bummer with VOID~!~!~!~! - Page 1
Forum section: electronics / projects

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 12:00:41 am
content: Hey i wanted to make a simple arduino sketch but i cant understand something .I am trying to repeat a void but i can notAnyway take a look at the code because even when i searched about this from the arduino cc i could not find anything to tell me how to execute not repeat a voidCode:// when led lights due to low lightning the speaker beeps//when the led shuts due to high lightning speaker beeps// and red led lights.int spkr= 7;//int speaker pinint led =13;//int ledint indled=22;//int indicator ledint photoPin=A3; // int photoresistor pinint val = 0; // int value as 0int limit=255; // int the photoPin limitvoid setup(){pinMode(spkr,OUTPUT);pinMode(led, OUTPUT);pinMode(indled,OUTPUT);pinMode(photoPin,INPUT);}void beep(){digitalWrite(spkr,HIGH);delayMicroseconds(1000);digitalWrite(spkr,LOW);}void loop(){val=analogRead(photoPin);if (val -100 > limit){digitalWrite(led,HIGH);digitalWrite(indled,LOW);beep;}else{digitalWrite(led,LOW);digitalWrite(indled,HIGH);}}I made it from scratch so if there is any suggestions on improving my writing or any other tips please share

author: c4757p
author_rank: Super Contributor
timestamp: March 03, 2013, 12:09:35 am
content: I'm really not sure what you mean by "repeat a void", but I do see a problem:Code:beep;You're just mentioning "beep" here. "Hey, compiler, 'beep' exists!" "Great, thanks! I know!" You have tocallit with parentheses.Code:beep ();

author: c4757p
author_rank: Super Contributor
timestamp: March 03, 2013, 12:21:52 am
content: Quote from: ChrisGreece52 on March 03, 2013, 12:00:41 amComment better.Code:int val = 0; // int value as 0This comment is utterly useless - it adds nothing. The code itself explains what the code does, comments shouldneverdo this. If the code is so poorly written that it is no longer self-explanatory, it should be rewritten, not comment-littered.Comments should explainwhythe code does what it does. For example, you should have a comment explaining why you chose 255 as a threshold value.One more thing: "led" and "indled" really, really need to be clarified. Why is "indled" an indicator and "led" is not? You should fully explain their purposes in a comment and then name the variables something that reflects that.

author: David_AVD
author_rank: Super Contributor
timestamp: March 03, 2013, 12:25:59 am
content: I'm only new to C programming and have been caught by this before. Why does the missing () not generate an error or warning?

author: ecat
author_rank: Frequent Contributor
timestamp: March 03, 2013, 12:37:43 am
content: Quote from: David_AVD on March 03, 2013, 12:25:59 amBecause missing out the () is perfectly valid C... Oh dear.Take our old friend foo() for exampleint foo( int x ) {return x + 1;}Now...y = foo( 7 );y will of course be set to 8But...y=foo;y is now set to the address of the function foo()So, no () following a function name is C syntax for 'take the address of the function'

author: c4757p
author_rank: Super Contributor
timestamp: March 03, 2013, 12:51:30 am
content: In C, everything is either a value or a statement (likeif,while, etc). There are no "commands". The program you write will calculate all values, then throw them away. It's up to you to make sure that the calculation of the values has side effects. (Source for this assertion: I have written a working C compiler.)"spam ()" doesn'tactuallymean "call spam", it means "the value returned by spam", and the compiler infers that it must call it to get the value. "spam" by itself is just... spam, the function. @David_AVD, there is an implicit cast-to-pointer, so that if you use it as a pointer (memory address), it will automatically be converted to one. This is the same as the implicit cast that allows you to say "float x = 3" even though 3 is an integer, not a float. Still, a function is subtly different from a pointer-to-function in a few cases."eggs = ham ()" doesn't even actually mean "assign the value returned by ham to eggs". = is a binary operator just like + or -, defined such that itsvalueis the final value of the left-hand argument, andas a side effect, the left-hand argument is assigned the value of the right-hand argument.If you add the option -Wunused-value, you will be warned about values with no side effects. Even better, use -Wall to turn on a whole bunch of warnings. (Note that I don't know how to add compiler options within the Arduino environment.)

author: David_AVD
author_rank: Super Contributor
timestamp: March 03, 2013, 03:14:22 am
content: There ya go. I learned something new today. I usually program in assembler for PIC, Delphi for PC and (would you believe) Basic for some touch screens.The significance of the "missing" () being a pointer had eluded me. In other languages I use you'd use a prefix (^ for example) to specify that you want a pointer.I'm sure those unintentional missing parenthesis bite plenty of people that are learning C.

author: c4757p
author_rank: Super Contributor
timestamp: March 03, 2013, 03:19:39 am
content: "Technically" you are supposed to use the address-of operator (ampersand) to get the address of a function as well. In fact, I always do this - I'd rather be explicit than implicit, especially if the difference is just a single character, to make the intention of the code clear. I seem to remember hearing that old (well,elderly) versions of C didn't always have this implicit cast and would just bitch at you, but I could be completely wrong there.Quote from: David_AVD on March 03, 2013, 03:14:22 amQuoteFTFY

author: kizzap
author_rank: Unknown
timestamp: March 03, 2013, 05:31:09 am
content: Quote from: ChrisGreece52 on March 03, 2013, 12:00:41 amIf I read your code correctly you want the speaker to beep any time that the light level crosses over a certain level? This is how I would do it:Code:int spkr = 7;int led1 = 13;int led2 = 22;int photopin = A3;volatile int readval = 0;volatile int Bright = 0;volatile int Dark = 0;void setup(){pinMode(spkr, OUTPUT);pinMode(led1, OUTPUT);pinMode(led2, OUTPUT);pinMode(photopin, INPUT);}void loop(){readval = analogRead(photopin);if (readval - 100 > 255){if (Bright = 0){Bright = 1; // Changes the test so that the circuit only modifies the outputs once per change in state.Dark = 0;digitalWrite(led1, HIGH);digitalWrite(led2, LOW);digitalWrite(spkr,HIGH);delayMicroseconds(1000);digitalWrite(spkr,LOW);}}else{if (Dark = 0);{Bright = 0;Dark = 1;digitalWrite(led1, LOW);digitalWrite(led2, HIGH);digitalWrite(spkr,HIGH);delayMicroseconds(1000);digitalWrite(spkr,LOW);}}}hopefully I haven't screwed that up somehow...I would also consider modifying the code a little so that there is not such a hard point of change between bright and dark, In case the lighting level chooses to sit on that exact level and the circuit picks up small differences and continually flips...Kieran

author: kolonelkadat
author_rank: Regular Contributor
timestamp: March 03, 2013, 06:03:26 am
content: its not _super_ important, but if a variable wont change during a codes execution- eg your pin assignments for components- , its best to #define them. Especially on a uC like the arduino where resources are at a premium.so instead ofint spkr= 7;put#define SPKR 7The all caps arent neccessary, but it lets you know that its a #define macro and not a variable, so you shouldnt try to store anything in it.

author: jahonen
author_rank: Super Contributor
timestamp: March 03, 2013, 07:58:49 am
content: Quote from: Mechatrommer on March 03, 2013, 06:23:40 amI think it is better to learn to write 2 == i instead of i == 2 since former will generate an error if you miss one =.Regards,Janne

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 04:04:22 pm
content: Quote from: c4757p on March 03, 2013, 12:21:52 amI know that the commenting is very bad but in my defense i only commented because i wanted to get an idea about comments (i do not comment in my other sketches so this is new for me) and yeah... i got that theCode:int val=0; //int value as 0is completely uselessas for the ind led i have 2 leds the one that lights up when the brightness is low and the indicator which indicates that the other led is on or off !i am going to work on my writing but thanks for the comments.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 04:05:35 pm
content: Quote from: ecat on March 03, 2013, 12:37:43 amI could not understand a thing ( it is because im new in C ) but thank you .

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 04:13:52 pm
content: Quote from: kizzap on March 03, 2013, 05:31:09 amThank you but i blame myself for not being clear.I want it to work like this.Low light -> indicator led = off and lamp led = onwhenlight goes from Low --> High then the indicator led is on (indicating that the lamp led is off) , the lamp led = off and the speaker beeps due to the change of the led value (BUT ONLY ONE TIME) <------ THATS MY PROBLEM....i thought going with a for loop code so i candoCode:digitalWrite(speaker,HIGH);delayMicroseconds(1000);digitalWrite(speaker,LOW);one time when the state changes and i dont know how.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 04:15:12 pm
content: Quote from: kolonelkadat on March 03, 2013, 06:03:26 amThank you didnt know that.

author: Unknown
author_rank: Unknown
timestamp: March 03, 2013, 04:23:48 pm
content: Quote from: Mechatrommer on March 03, 2013, 12:48:06 pmPlease name one compiler that will not give an error for:Code:if (2 = i) ...;

author: dougg
author_rank: Regular Contributor
timestamp: March 03, 2013, 04:31:52 pm
content: Quote from: jahonen on March 03, 2013, 07:58:49 amGreat advice, some of the best I ever got in C (i.e. for equality tests if a constant is involved always place it to the left). And also if you want to do an assignment _and_ check if the result of the assignment is non-zero, use double parentheses around the assignment. For example:if ((y = foo(z + 1)))...It is a visual clue of your intent and gcc (forget which switches, perhaps '-W') will warn you if you don't have the double parentheses around the assignment expression.Oh, and BTW, if you are writing in the Arduino IDE, then it's C++. Got reminded yesterday with the assignment of a void * into a typed pointer .

author: dougg
author_rank: Regular Contributor
timestamp: March 03, 2013, 04:52:55 pm
content: Quote from: alm on March 03, 2013, 04:23:48 pmCan't remember the name but it was around 1980, probably written by a student. And it changed the value of the constant "2" to whatever "i" was! Horrible, a bit like '#define 2 3'But seriously, no compiler that even went close to implementing: K+R C, C89, C99 or C11 (plus every C++ standard) would accept 'if (2 = i)'.Perhaps Mechatrommer is older than me and has a long memory.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 03, 2013, 05:08:41 pm
content: I lost you there ...

author: kizzap
author_rank: Unknown
timestamp: March 04, 2013, 02:28:46 am
content: Quote from: ChrisGreece52 on March 03, 2013, 04:13:52 pmwell you could still do that in the code, just remove the code that does the beep where you dont need it...The rest is all there in the code

author: free_electron
author_rank: Super Contributor
timestamp: March 04, 2013, 03:48:02 am
content: bloody bleeping Crap language.if the compiler underpinning c was just a tiny little bit smarter it would actually be an enjoyable language. now it's not.Things that irk me :1) The need for semicolons. Use the bloody line termination character (CR/Lf on a normal OS or LF on loonix. Loonix's use of the single Lf is actually wrong. A line of text must terminate in CRLF or LFCR . CR and LF are printer / terminal control codes. CR means carriage return : bring the printhead /cursor back to the beginning of the line. it does NOT advance the paper or line! it only moves the head / cursor to the left. LF = line feed : means : advance paper/cursor to the next line. So to continue on a new line you NEED both CR and LF. A Cr alone would simply overwrite the existing line and an LF does not home the printhead so lines would be staggered. The only sane usage is both Cr and LF to indicate : i want to continue on the next line, at the beginning) in the sourcecode.Whenever there is a new line character a new command begins.If a long line needs continuation it should be rewritten because it is unreadable. Exception maybe function arguments, in that case us a continuation charactervoid blah ( int32 argument1 _int32 argument2 _int16 argument3 )2) == and =.The compiler is perfectly capable to figure out from the context if it is a comparison or an assignment. lots of other language can do it . why not 'c' ?if x = 12 ... clearly a comparisonx = 12 .. clearly an assignment.the craziest language is PL1 : this is perfectly valid PL1 code :if if = then then then = else else else = ifthe compiler understands what is a keyword and what is a variable. purely from analysing the source.3)function calls :beep vs beep()why do you need the address of beep ? by default you want to call it. just make an explicit command called 'addressof' it would make code much clearer, expecially for beginners. and in case you use function pointers make it clearly visible ( by using an explicit indication 'hey function pointer' ). if oyu are writing code with function pointers you are clearly doing very compilecated stuff... so make it known and very visible.beep : call beep, i don;t care about what it returns.x = beep : calls beep and traps return value in xx = addressof(beep) : explicitly request the address of beepcall x(arguments) : call a function through an address4)the size of integers:What an absolutle moronic idea to use the same name for different sizes of data storage.an integer for one compiler may mean 16 bit , while on another compiler it may mean 32 bit... and then you get the Ariane-5 effect ... -BOOM- 3 billion dollar rocket blown up .in code i write for embedded stuff it is not allowed to use the C generics. we need to use thing like int32 , int16 uint16 uint32 etc. nothing is allowed to be cast as 'integer' as you don't know what the compiler will do when code is ported to a different platform.5) the need to define function prototypes. Why can't dumb piece of junk compiler simply scan over all source code, collect the functions and then compile ? if i am calling something that doesn't exist the compiler can throw a fit.now i need to keep header files, include files and tons of other 'overhead'. Computers are there to make my life easier. not the other way around. i should only have to tell it something once. not twice ( once in the function declaration , once in the header file ) and i shouldn't have to include header files in every single module. the compiler should simply scan all sourcefiles in the project and collect its info from there.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 04, 2013, 10:09:39 pm
content: Quote from: kizzap on March 04, 2013, 02:28:46 amYeah but i need the speaker to beep when the led changes state i am thinking a boolean....

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 04, 2013, 10:12:28 pm
content: So what shall i doUse a boolean ? for loop ? while loop? do while loop(i dont think thats the right one.)Please help.

author: uprightsquire
author_rank: Contributor
timestamp: March 04, 2013, 10:25:19 pm
content: well, you can remember the value of the input from the last trip through the loop and only beep when now = bright, before = not bright...Code:int oldval;....void loop(){readval = analogRead(photopin);if(oldval <threshold && readval > threshold){beep();...oldval = readval;}

author: grumpydoc
author_rank: Super Contributor
timestamp: March 04, 2013, 11:08:00 pm
content: QuoteWell, like any language you have to learn its idioms. However, looking through your examples I believe the language you want exists and is called Visual BasicC was originally written for machines which, by today's standards, were very simple. You can get an (almost) K&R compiler for a Z80 fer fek's sake. This is why some of the features which annoy you are the way that they are.OK, some stuff was essentially an accident - "everything is a value" probably stemmed from the accumulator co-incidentally happening to have the result of whatever was just evaluated and the pre & post increment stuff mapped to some particular PDP instruction but C is notfundamentallyworse than any other language of its generation and better than many for real-world tasks. In fact, although it has bloated a bit in recent years it is not worse than many modern languages and, again, better than many as a general purpose tool.In particular it remains just about the best "high level" language for "low level" tasks so you're not likely to get far away from it in the embedded space - you might as well, therefore, learn to live with it.

author: grumpydoc
author_rank: Super Contributor
timestamp: March 04, 2013, 11:17:30 pm
content: QuoteBecause C wasdesignedto be a single pass compiler (think small 16-bit systems from the 70's) and that would have required multiple passes over the source files. It gets a bit hairy with libraries as well.

author: grumpydoc
author_rank: Super Contributor
timestamp: March 04, 2013, 11:21:20 pm
content: QuoteBecause a C "int" is intended to be whatever the most natural size of integer is on a particular hardware platform. I suspect that ideas about portability came along later but you might as well complain that a register on the 6502 is 8 bits but on a Pentium can be 32 (or 64 bits) despite them all being "registers".

author: ecat
author_rank: Frequent Contributor
timestamp: March 04, 2013, 11:32:09 pm
content: Quote from: free_electron on March 04, 2013, 03:48:02 amC was specified many years ago and over time technology, requirements and expectations have changed. While I do feel your pain, for better or for worse all your points have an explanation.1) The ';' is a statement delimiter, it does of course allow for a statement to be spread over many lines but more importantly it allows for many statements to be placed on a single line. Why would you want many statements on a single line? Macros. Back in the day macros were important, they allowed the programmer to encapsulate frequently used snippets of code and use them without the overhead of a call/return sequence or perhaps in an interrupt routine where calls were forbidden. A macro, of course, expands to a single line.2) = and == have been a source of many errors over the years. Certainly distinctions can be made, := as assignment in the case of Pascal for example, but we live in an imperfect world and C has a legacy spanning decades. Besides, do you want the compiler to try to determine the meaning of the code or should the compiler simply translate and in doing so assume the programmer knew what they were doing?3) Back in the day a compiler which allowed access to the address of functions was a big deal. Storing function pointers in data structures avoids many an if statement or switch block. And on the subject of switch, an array of function pointers makes for a jump table, a slightly dangerous but highly efficient switch block substitute. Again, you are correct in stating the syntax could be better handled.4) Integer size? Efficiency. A C integer should be the size of the most efficient multi bit native data type supported by the underlying architecture. Again, back in the day every ounce of speed would be a requirement, C provided for this avoiding the need to drop into assembly.5) Function definitions in C are not exclusive, foo() defined in file A may be redefined in file B. When a statement in file C calls foo() the choice between A foo and B foo is resolved by calling the version declared most immediately prior to the calling statement. This was and can still be a useful feature but again the implementation is rather archaic.tl;drC is several decades old, it was created as an means to write efficient code without the need to drop into highly platform specific assembly code and as such it has several quirks and features which appear bizarre or down right dangerous. In the early years it was the ideal tool for many tasks which lead to its popularity, the popularity has persisted to this day and due to billions of lines of legacy code the language itself remains in many ways unchanged, warts and all.

author: free_electron
author_rank: Super Contributor
timestamp: March 05, 2013, 01:04:24 am
content: Quote from: grumpydoc on March 04, 2013, 11:17:30 pmi know that. but we are 50 years later.. it would not break compatibility to make it scanning !

author: kizzap
author_rank: Unknown
timestamp: March 05, 2013, 05:05:46 am
content: Quote from: ChrisGreece52 on March 04, 2013, 10:09:39 pmdo you want the speaker to beep every time the lighting state changes from High to LowandLow to High? or just one of the two?secondly, what is happening with the code as you have it now? Does the speaker just continually beep when the system triggers the use of the speaker?Thirdly. what is the point of arguing the semantics of C coding and such when it has nothing to do with trying to help solve an obvious beginners question?

author: IanB
author_rank: Super Contributor
timestamp: March 05, 2013, 05:27:30 am
content: Quote from: ChrisGreece52 on March 04, 2013, 10:12:28 pmYou need to keep track of state:Code:initialize state to darkloop{if state is dark and sensor is light{set state to lightturn off LEDturn on indicatormake a beep}else if state is light and sensor is dark{set state to darkturn on LEDturn off indicatormake a beep}}Yes, you can use a bool to hold the light/dark state.

author: Kremmen
author_rank: Super Contributor
timestamp: March 05, 2013, 06:11:16 am
content: Quote from: free_electron on March 05, 2013, 01:04:24 amBut it would, break it! that would create the requirement that all of the source code must be available for every compilation. As pointed earlier, a C compiler acts of single files, and for a reason. The source code for external functions may not be available, sometimes on purpose. It is the job of the linker to glue the separately compiled object modules together. Back in the day we used to have a separate locator even, to fix addressing into the machine address space, but nowadays that is done by the linker as well.A good reason to have it this way is the concept of interface, and separate development. The purpose of an interface is to hide the implementation - a sound principle of software construction where minimum assumptions should be made in order to maintain generality. For those not into "programming in the large" this may seem like an unneeded obstruction, but in my opinion C has got it right. Whether the implementation of interface is up to today's standards is another matter - C is oldish already.Many things could be improved but at the cost of breaking a huge mass of existing code. Not likely to happen. Instead, the world moves on to things like C++, Java, C#, Rubyand whatnot.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 08:35:00 am
content: Quote from: kizzap on March 05, 2013, 05:05:46 amI need when the main LED change states the speaker to beep (only ONCE)(the indicator LED changes state when the main LED changes so with one beep we can show that both the LED's chanced state.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 08:37:07 am
content: Quote from: IanB on March 05, 2013, 05:27:30 amTHANK YOU GOT IT.ill try itAnd again thank you all.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 08:57:59 am
content: Quote from: IanB on March 05, 2013, 05:27:30 amTried what you said but i get an error always and i dont know what to do.it saysexpected primary-expression before '=' token and the area that the IDE highlights does no even have a = in it...take a look at the code.Code:# define mainLed =13;# define led = 6;# define indLed =7;# define photoPin = A0;int photoState =0;int ledState =0;int dark(){digitalWrite(mainLed,HIGH);digitalWrite(led,LOW);}int light();{digitalWrite(mainLed,LOW);digitalWrite(led,HIGH);}int beep();{digitalWrite(indLed,HIGH);delayMicroseconds(1000);digitalWrite(indLed,LOW);}void setup(){}void loop(){(photoState = analogRead(photoPin));if (ledState=photoState){dark();}else if (ledState =! photoState){light();}

author: kizzap
author_rank: Unknown
timestamp: March 05, 2013, 09:36:43 am
content: Quote from: ChrisGreece52 on March 05, 2013, 08:35:00 amOnce again you are still not clearly defining the problem or the symptoms.does the system need to beep once when the system detects that the light level gets brighter, and if it detects that it is getting darker it beeps?can you actually get the system to beep at all?Kieran

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 09:47:06 am
content: Here's a corrected version of your code. There were several problems. Compare this code to your your original code.Code:const int mainLed = 13;const int led = 6;const int indLed = 7;const int photoPin = A0;int photoState = 0;int ledState = 0;int dark(){digitalWrite(mainLed,HIGH);digitalWrite(led,LOW);}int light(){digitalWrite(mainLed,LOW);digitalWrite(led,HIGH);}int beep(){digitalWrite(indLed,HIGH);delayMicroseconds(1000);digitalWrite(indLed,LOW);}void setup(){pinMode(mainLed, OUTPUT);pinMode(led, OUTPUT);pinMode(indLed, OUTPUT);}void loop(){photoState = analogRead(photoPin); // This returns a value from 0 to 1023.if (ledState == photoState){dark();}else // Redundant: if (ledState != photoState){light();}}This code will compile but there arestillproblems. For one, analogRead() returns a value from 0 to 1023 so comparing its returned value to 0 is going to be problematic. You will likely need to say something like:Code:if (photoState <= 15)Also, an Arduino can't drive a speaker directly. I hope you don't have a speaker connected to one of the pins. You'll blow that pin (or the Arduino) up. Speakers are such low resistance that they basically look like a short.Even if the Arduino could drive a speaker directly, just setting an output to high wont produce any noise. They make piezo buzzers that you can drive directly with an Arduino like you are doing. Maybe that's what you have connected. I've only skimmed through the post.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 11:11:21 am
content: Quote from: kizzap on March 05, 2013, 09:36:43 amSorry again i am new in all of these things so i cant be clear enoughI need to do exactly what you are saying.And yes i can make it beep by these simple steps but it beeps continuously when i upload the code and that's my problem i need it to beep once.Code:int beep(){digitalWrite(spkr,HIGH); // the speaker is connected in a pwm pindelayMicroseconds(1000);digitalWrite(spkr,LOW);}and then we say it to beepfor example if the photoresistor is high it beeps (but continuously)if (photoPin -100 > limit ) // limit is set to 255{digitalWrite(led ,HIGH);beep();}

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 11:13:08 am
content: Quote from: TerminalJack505 on March 05, 2013, 09:47:06 amOH MY GOD I HAD NO IDEA.I am using an 8 ohm 3 watt speaker in a pwm pin... i had no problems so far... why is that???

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 11:23:59 am
content: Hard to say why you haven't had any problems yet but you're pushing your luck.The maximum current that a pin of an ATmega328 can provide is 40mA. An 8 ohm speaker would draw way too much current. Do you have a resistor in series with the speaker to reduce the current?

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 11:28:06 am
content: No what resistor would you suggest?

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 11:51:48 am
content: The simplest solution would be to use a piezo buzzer. These draw very little current and are fine for just sounding a tone. They have terrible frequency response compared to a speaker though so don't expect them to sound as good as a speaker for things like music.If you want to use a speaker then you need to put an audio amplifier IC between the Arduino and the speaker and let the amplifier IC drive the speaker. Or, since you are just using square waves you can use some transistors in a push-pull type of configuration to drive the speaker.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 12:54:35 pm
content: I know but since i cant wait 2 weeks for a piezzo to arrive i will use a speaker with 220 ohm resistor in series.Now what would you suggest to do with the code?

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 01:25:32 pm
content: Try something like this. The speaker is probably beeping continuously since you aren't keeping track of the state and only beeping with the state changes. I think someone else mentioned this already.Code:const int mainLed = 13;const int led = 6;const int indLed = 7;const int photoPin = A0;const int darkLevel = 15;enum TCurrentState { csInvalid, csDark, csLight };TCurrentState curState = csInvalid; // An initial value of csInvalid will ensure proper initialization.int dark(){digitalWrite(mainLed,HIGH);digitalWrite(led,LOW);}int light(){digitalWrite(mainLed,LOW);digitalWrite(led,HIGH);}int beep(){ // Does this actually work?...digitalWrite(indLed,HIGH);delayMicroseconds(1000);digitalWrite(indLed,LOW);}void setup(){pinMode(mainLed, OUTPUT);pinMode(led, OUTPUT);pinMode(indLed, OUTPUT);}void loop(){int photoLevel = analogRead(photoPin); // This returns a value from 0 to 1023.if (photoLevel < darkLevel && curState != csDark){curState = csDark;dark();beep();}else if (photoLevel >= darkLevel && curState != csLight){curState = csLight;light();beep();}}

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 01:52:09 pm
content: Hey thanks for this i uploaded the sketch to the arduino but it not do what it is supposed to ....only the led lights up(it tried changing the sensitivity on the sketchCode:(photoLevel >= darkLevel && curState != csLight) to (photoLevel -100 >= darkLevel && curState != csLight)

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 02:12:56 pm
content: I think you probably need to print some debugging information to see what the photo sensor is actually returning. A schematic of how your circuit is hooked-up would be useful as well. Also, if you have code that actually does make the speaker beep then you want to use it in the code I uploaded since I just left the beep() code like you had it and I don't think it will work.To see what the photo sensor is returning use this code and enable the serial monitor. You can add your own Serial.print() statements too to add additional debugging info.Code:const int mainLed = 13;const int led = 6;const int indLed = 7;const int photoPin = A0;const int darkLevel = 15;const bool DEBUG = true;enum TCurrentState { csInvalid, csDark, csLight };TCurrentState curState = csInvalid; // An initial value of csInvalid will ensure proper initialization.int dark(){digitalWrite(mainLed,HIGH);digitalWrite(led,LOW);}int light(){digitalWrite(mainLed,LOW);digitalWrite(led,HIGH);}int beep(){ // I doubt this actually works...digitalWrite(indLed,HIGH);delayMicroseconds(1000);digitalWrite(indLed,LOW);}void setup(){pinMode(mainLed, OUTPUT);pinMode(led, OUTPUT);pinMode(indLed, OUTPUT);if (DEBUG)Serial.begin(9600);}void loop(){int photoLevel = analogRead(photoPin); // This returns a value from 0 to 1023.if (DEBUG){Serial.print("photoLevel = ");Serial.println(photoLevel);}if (photoLevel < darkLevel && curState != csDark){curState = csDark;dark();beep();}else if (photoLevel >= darkLevel && curState != csLight){curState = csLight;light();beep();}}

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 02:21:56 pm
content: Thank you i will add a Serial.println to my sketch.

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 02:29:39 pm
content: The photocell values go from 940 (it goes up to 1010 when i place the photocell under a lamp) all the way down to 250(when i cover it completely with my hand and fingers)770 when i place my hand on itwhen i cover it with my 3 fingers goes to 600and it goes to 300 after i cover it with my fingers and hands.heres the tweaked code but nothing still.Code:const int mainLed = 13;const int led = 6;const int indLed = 7;const int photoPin = A0;const int darkLevel = 15;enum TCurrentState { csInvalid, csDark, csLight };TCurrentState curState = csInvalid; // An initial value of csInvalid will ensure proper initialization.int dark(){digitalWrite(mainLed,HIGH);digitalWrite(led,LOW);}int light(){digitalWrite(mainLed,LOW);digitalWrite(led,HIGH);}int beep(){ // Does this actually work?...digitalWrite(indLed,HIGH);delayMicroseconds(10000);digitalWrite(indLed,LOW);}void setup(){Serial.begin(9600);pinMode(mainLed, OUTPUT);pinMode(led, OUTPUT);pinMode(indLed, OUTPUT);}void loop(){int photoLevel = analogRead(photoPin); // This returns a value from 0 to 1023.Serial.println(photoLevel);if (photoLevel -200 < darkLevel && curState != csDark){curState = csDark;dark();beep();}else if (photoLevel -100 >= darkLevel && curState != csLight){curState = csLight;light();beep();}}

author: TerminalJack505
author_rank: Super Contributor
timestamp: March 05, 2013, 03:00:50 pm
content: So if the sensor returns 250 as the minimum use a value of 300 or so for the darkLevel constant. And get rid of the code you added where you subtract 200 or 100 from photoLevel.Code:const int darkLevel = 300;...if (photoLevel < darkLevel && curState != csDark){ ... }else if (photoLevel >= darkLevel && curState != csLight){ ... }

author: ChrisGreece52
author_rank: Frequent Contributor
timestamp: March 05, 2013, 08:30:18 pm
content: ok thank you