setTimeout

Posted on
  • I connected a speaker I ripped out of a old cellphone and connected it between pin C8 and 3.3 V.
    I can get sound from it by

    analogWrite(C8, 0.1 , {freq : 500})
    

    But when I try to create short sounds it's not cooperating.
    Should this not send the sound to the speaker in 0.1 seconds?

    setTimeout(function () {analogWrite(C8, 0.1 , {freq : 500})}, 100);
    

    What am I doing wrong?

  • Ok, I got it!!
    After reading the reference again slower I understood what I was doing wrong.

    200 ms second sound:

    setTimeout(function() {analogWrite(C8, 0.5 , {freq : 2000})}, 0)
    
    setTimeout(function() {analogWrite(C8, 0)}, 200)
    
  • Great! glad you got it sorted!

    Minor thing, but to turn the speaker off you could use digitalRead(C8); instead - that'll put the pin back into an 'input' mode - so if for instance you'd connected the speaker between C8 and VCC then it would ensure that it was actually turned off.

  • I still can't understand the sence of the first setTimeout.
    Why not write:

    analogWrite(C8, 0.5 , {freq : 2000});
    setTimeout(function() {digitalRead(C8);}, 200);
    

    ?
    And why code

    setTimeout("print(1)",2000);
    setTimeout("print(2)",1000);
    

    prints
    1
    2
    without delay?

  • Yes, writing:

    analogWrite(C8, 0.5 , {freq : 2000}); 
    setTimeout(function() {digitalRead(C8);}, 200); 
    

    would work fine.

    I just tried the code exactly as you suggested, and it writes ....2....1 with a 1 second delay between them as expected. Perhaps you could explain exactly how the code is being used? Is it possible that when you tried it you didn't have the quotes?

  • Weren't there some firmware versions recently where timekeeping was not working correctly?

    I think time-keeping in general was broken on a bunch of my bigram builds (from nov 11 to mid/late december) - were you using one of those?

  • Well, if you set a timeout on onInit then saved it, you could have problems with some builds. But I'm not sure that's what @user51876 is doing - he definitely didn't suggest he'd done anything like that.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

setTimeout

Posted by Avatar for Hellis @Hellis

Actions