body:
I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?

It works fine if I use `LOW` for `attachInterrupt` along with a pull-up resistor though. Just not with `RISING` and a pull-down.

    #include <avr/sleep.h>
    #include <avr/power.h>

    int pin2 = 2;

    void setup() {
      Serial.begin(9600);

      /* Setup the pin direction. */
      pinMode(pin2, INPUT);

      Serial.println("Initialisation complete.");

    }

    void pin2Interrupt(void)
    {
      /* This will bring us back from sleep. */

      /* We detach the interrupt to stop it from
       * continuously firing while the interrupt pin
       * is high.
       */
      detachInterrupt(digitalPinToInterrupt(pin2));
    }

    void enterSleep(void)
    {

      sleep_enable();

      /* Setup pin2 as an interrupt and attach handler. */
      attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
      delay(100);

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

      sleep_mode();

      /* The program will continue from here. */

      /* First thing to do is disable sleep. */
      sleep_disable();
    }

    int seconds=0;
    void loop()
    {
      delay(1000);
      seconds++;

      Serial.print("Awake for ");
      Serial.print(seconds, DEC);
      Serial.println(" second");

      if(seconds >= 3)
      {
        Serial.println("Entering sleep");
        delay(200);
        seconds = 0;
        enterSleep();
      }
    }

title: Not waking up more than once?

Answers: 2

body:
For a `RISING` interrupt you never need to disconnect the interrupt to prevent repeat triggering.

A `RISING` interrupt specifically only triggers the once when the input pin transitions from `LOW` to `HIGH` rather than all the time it's in a state like a *level* interrupt.

Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.

body:
<!-- language-all: lang-C++ -->

Probably your switch is bouncing and giving two interrupts. The first wakens it, and the second is lying there waiting until you attach the interrupt again. Then it fires, detaches the interrupt, then you go to sleep, never to awaken.

Clear any pending interrupt **before** doing the attachInterrupt:

    EIFR = bit (INTF0);  // clear flag for interrupt 0

See [Interrupts](http://www.gammon.com.au/interrupts).

It is also wise to have interrupts off while setting up for sleep.

---

Example code:

    #include <avr/sleep.h>

    const byte LED = 13;

    // interrupt service routine in sleep mode
    void wake ()
    {
      sleep_disable ();         // first thing after waking from sleep
    }  // end of wake

    void sleepNow ()
    {
      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      noInterrupts ();          // make sure we don't get interrupted before we sleep
      sleep_enable ();          // enables the sleep bit in the mcucr register
      EIFR = bit (INTF0);       // clear flag for interrupt 0
      attachInterrupt (0, wake, RISING);  // wake up on rising edge
      interrupts ();           // interrupts allowed now, next instruction WILL be executed
      sleep_cpu ();            // here the device is put to sleep
      detachInterrupt (0);      // stop this interrupt until next time
    }  // end of sleepNow

    void setup ()
      {
      pinMode (LED, OUTPUT);
      }  // end of setup

    void loop ()
      {
      sleepNow ();
      digitalWrite (LED, HIGH);
      delay (1000);
      digitalWrite (LED, LOW);
      }  // end of loop

Tested and works OK.

---

Note: Since this is a rising interrupt you should have a **pull-down** resistor on the pin, and you trigger the interrupt by connecting the pin to +5 V.


body:
So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);

    void setup() {
      pinMode(2, OUTPUT);
      mySerial.begin(9600);
    }

    void loop() {
      if (mySerial.isListening()){
        digitalWrite(2, HIGH);
      }
      mySerial.write(5);
    }

and on my receiving Arduino, I have:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(11, 10);

    void setup() {
      pinMode(2, OUTPUT);

      Serial.begin(9600);

      mySerial.begin(9600);
    }

    void loop() {
      mySerial.listen();
      if (mySerial.available()>0) {
        digitalWrite(2, HIGH);
        char inByte = mySerial.read();
        Serial.write(inByte);
      }
      digitalWrite(2, LOW);
    }

(with D2 being hooked up to an LED for both).

I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?

title: Can't get software serial to work

Answers: 2

body:
Sender:

    SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:

    SoftwareSerial mySerial(11, 10);  // Rx, Tx

> I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

---

      mySerial.listen();

You don't need that in this simple example.

body:
I agree with Nick above but want to add this simplify your code like this:

if (mySerial.available()) {
    digitalWrite(2, HIGH);
    Serial.write(mySerial.read());
  }

I have had to catch serial data from a printer feed before and this turned out to be the best way to catch all the data if you place it in a variable first it has to change the variable every time that you receive a byte but this way it places all in a buffer then sends it out

BTW I had to save to a F-RAM device and that worked the same way but instead of sending it I had it saved to a variable while using ReadString() in stead of read().


body: I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?

title: Storing array in PROGMEM

Answers: 3

body:
Store them with `const byte PROGMEM` with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become `const byte[] var PROGMEM {0x72, 0x52, 0xab}`

Use the following macro to retrieve them (untested):

    #define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had `const byte[] data PROGMEM {0x72, 0x52, 0xab};` you would call `loadbit(data, 3)` and it would return bit 3 starting with 0 on the left, i.e. `1`.

Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.

body:
As noted in Ignacio's answer, you can pack your bits of data into bytes and access them via `pgm_read_byte()` calls.  If (for coding convenience, not for efficiency) you prefer to pack the bits into larger units, you can use `word` and `dword` access functions, as listed in [AVR pgmspace.h](http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html) documentation.  The `_near` and `_far` suffixes denote 16 or 32 bit pointers, respectively; for an Uno with its 32K flash memory, `_near` is always suitable.  See [PROGMEM documentation](https://www.arduino.cc/en/Reference/PROGMEM) at arduino.cc for further discussion.

Here's an example program that accesses and prints data from program memory in 16-bit chunks:

    void setup() {
      Serial.begin(115200);         // initialize serial port
    }
    int k=0;
    const uint16_t fnums[] PROGMEM {191, 272, 353, 434, 515, 646, 767, 888};
    void loop() {
      uint16_t b = pgm_read_word_near(fnums+k);
      Serial.print(k);  Serial.print(" ");
      Serial.print(b);  Serial.println();
      k = (k+1)%8;
      delay(1000);
    }

To pack your 4000 bits of data in the first place, write a C or Python program that runs on a host computer and writes out array definitions that you can cut and paste into a sketch.  Here's an example (in Python) that packs bits into bytes:

    data = [1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1]

    first = 1; byt = 0
    for i, b in enumerate(data):
      if i%8==0:
        if first:
           print 'const uint8_t fnums[] PROGMEM {',
           first = 0
        else:
           print '{},'.format(byt),
           byt = 0
      byt = (byt<<1) | b  # add bit into byte being built

    print byt<<(8-i%8), '};'

Here is what the program produces:

    const uint8_t fnums[] PROGMEM { 197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 262 };

If you want that code to instead pack bits into 16-bit words, change 8 to 16 in four places.  Note, the code stores bits in the “bit 0 as MSb and bit 7 as LSb” order mentioned in Ignacio's answer.  Thus, `data[0]` is stored in the high bit of `fnums[0]`, `data[8]` is stored in the high bit of `fnums[1]` , and so forth.

body:
Building on the excellent other answers by jwpat7 and
Ignacio Vazquez-Abrams, you could conceivably convert your bits into a table using Lua:

<!-- language-all: lang-lua -->

    data = { 1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,
             0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,
             1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,
             0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,
             0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1 }

    output = 0
    bit = 0

    for _, num in ipairs (data) do
      assert (num == 0 or num == 1, "Number must be 0 or 1")
      output = (output * 2) + num
      bit = bit + 1
      if bit >= 8 then
        io.write (output .. ", ")
        output = 0
        bit = 0
      end -- if
    end --for

    print ""

<!-- language-all: lang-none -->

Output from above:

    197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,

<!-- language-all: lang-C++ -->

Now you can make a simple function to pull a particular bit out of PROGMEM:

    const byte myTable [] PROGMEM = {
      197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
      };

    bool getBit (const unsigned int which)
      {
      const unsigned int whichByte = which / 8;
      const byte whichBit = which & 0x07;
      return bitRead (pgm_read_byte (&myTable [whichByte]), 7 - whichBit);
      }  // end of getBit

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Starting");

      for (int i = 0; i < sizeof (myTable) * 8; i++)
        {
        Serial.print (int (getBit (i)));
        Serial.print (", ");
        }
      Serial.println ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output from above:

<!-- language-all: lang-none -->

    Starting
    1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,


body:
I want to write a little library;

the unlibrarized functionality does:

checking in every loop-cycle some inputs,

doing some calculations with it

and finally setting a boolean to either true or false.

**How do I periodically check the inputs inside the library?**

I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

**Is there a way, to instantiate a class and start an periodically function by doing so?** And if, how does this constant checking affect/coexist with my 'normal' loop()-function?

title: Can I automatically loop inside a library?

Answers: 2

body:
Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an `update` method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.

If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.

Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.

Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)

body:
> I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

What's the difference?

In the `loop` you can call something like:

    void loop ()
      {
    ...
      if (mylibrary.ready ())
        {
        // it's time to act!
        }
    ...
      }

You can make a function, that returns a boolean type, which tells you if the thing you need to do is ready. That function *does the checking* before returning true or false.

After all, you are planning to check the boolean periodically, presumably often enough to notice it changing, why not have that be the point of noticing whatever-it-is you need to notice?


body:
I have a 2008 Mac that hardly ever crashes. But from time to time (not always) it crashes (the whole computer shuts down as if the power has been cut off) when I plug in an Arduino via USB.

What could cause this?

----

I've done some testing and the constant in when this occurs seems to be a cheap PIR sensor from eBay. It works some of the time.

Should I get another sensor? Or is there something about PIR sensors that makes them prone to this? It has a lot of caps... Is there another kind of motion sensor?

title: Arduino crashed my computer when I plug in the USB cable

Answers: 3

body:
It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.

In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.

body:
I had this problem with a Chinese knock-off of an Arduino Nano -- looks like it was actually because I had previously installed some CH341 drivers that no longer work with Sierra.

Removing those drivers (`sudo rm -r /Library/Extensions/usbserial.kext`) stopped the crash (full computer shutdown when I plugged in the Arduino, even through an externally powered USB hub), but unfortunately my Mac doesn't seem to recognize the Arduino.

It looks like there is a newer version of the driver (1.4, 2017-01-11,  [downloadable from here](http://www.wch.cn/download/CH341SER_MAC_ZIP.html)), or the 1.3 version is [available as a homebrew cask](https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver) if you tap that repo.

I am a little wary about installing a driver from a random Chinese site. If you want, you can unzip the driver and unpackage the `.pkg` file with `pkgutil --expand package-name.pkg destination-folder`. There are a couple subfolders including a `Payload` that you can inspect a little with `zcat` -- way over my head.

Alternatively, it looks like [this repo](https://github.com/z4yx/osx-ch341-serial) may have a C++ driver that may work.

body: As n8henrie said this is an issue regarding drivers with Mac OS. I updated to Mac OS Mojave (Full disclosure I run a Hackintosh system) and plugging in the arduino nana would cause a massive kept stall causing my computer to loop (if playing a video it would loop back and forth) and I’d need to turn off the PSU in order to successfully boot. However by deleting the current drive I used (CH341) the board would no longer do this (note- I tried 3 boards from different sellers, with 1 genuine and 2 Chinese) in High Sierra this did not happen however


body:
I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).

avr/power sketch:

    #include <avr/power.h>
    #include <avr/sleep.h>

    void setup()
    {
      Serial.begin(9600);
      byte i;

      // Ensure no floating pins
      for(i=0; i<20 ; i++)
      {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
      }

      // Power-down board
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

      sleep_enable();

      // Disable ADC
      ADCSRA &= ~(1 << ADEN);

      // Power down functions
      PRR = 0xFF;

      // Enter sleep mode
      sleep_mode();
    }

    void loop()
    {
    }

rocketscream/Low-Power sketch:

    #include <LowPower.h>
    void setup() {
    }

    void loop() {
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
    }

title: High power consumption during power down mode

Answers: 1

body:
I tried your first sketch on my "bare-bones" board.

[![Bare-bones board][1]][1]

With the sketch exactly as written, it used 197 µA.

I wondered why it was that high, so I commented out this line:

      Serial.begin(9600);

That reduced consumption to 122 nA.

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power).

You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.

Of course, if you *need* the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.

  [1]: https://i.stack.imgur.com/OWnJk.jpg


body:
I  have connected a circuit to analog pin 0 in the Arduino.I have this code ,which I understand partially(online resources).The problem is that it prints nothing neither on Tera Term nor on Cool Term .Where am I mistaking ?(I am new to AVR programming).Here is the code:

      #include<stdio.h>
     void InitADC()
     {
     ADMUX=(1<<REFS0);// For Aref=AVcc;
     ADCSRA=(1<<ADEN)|(7<<ADPS0);
      }

     uint16_t ReadADC(uint8_t ch)
     {

        //Select ADC Channel ch must be 0-7
         ch=ch&0b00000111;
         ADMUX|=ch;

         //Start Single conversion

         ADCSRA|=(1<<ADSC);

          //Wait for conversion to complete
          while(!(ADCSRA & (1<<ADIF)));

          //Clear ADIF by writing one to it
          ADCSRA|=(1<<ADIF);

         return(ADC);
    }

    int main()

      {

    uint16_t adc_value;

    InitADC();

    while(1)

    {

      adc_value = ReadADC(0);
      printf("%d",adc_value);

      }

       return 0;

      }

title: AVR+Arduino ADC problem

Answers: 1

body:
Your code compiles, but as Gerben said, the printf won't do anything in its current state, as no output handlers are defined for it. Why go to all that trouble when you can do this?

    void setup()
      {
      Serial.begin (115200);
      }

    void loop()
      {
      uint16_t adc_value;
      adc_value = analogRead (0);
      Serial.println (adc_value);
      delay (100);  // stop output spamming your monitor
      }

---

You could conceivably make `printf` work by following the tutorial here: <http://playground.arduino.cc/Main/Printf>

However I don't really see the point, when what I posted is much easier.

---

> If performance is an issue, you might want to use the "advanced" code.

That "advanced" code above doesn't give you any more performance, because is still blocks. You can do a non-blocking version easily and readably enough:

    const byte adcPin = 0;  // A0

    bool working;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      ADCSRA =  bit (ADEN);   // turn ADC on
      ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
      ADMUX =   bit (REFS0) | (adcPin & 0x07);  // AVcc
      }  // end of setup

    void loop ()
      {
      if (!working)
        {
        bitSet (ADCSRA, ADSC);  // start a conversion
        working = true;
        }

      // the ADC clears the bit when done
      if (bit_is_clear(ADCSRA, ADSC))
        {
        int value = ADC;  // read result
        working = false;
        Serial.println (value);
        delay (500);
        }

      // do other stuff here

      }  // end of loop

Now **that** code (which admittedly fiddles with the registers) doesn't block so you could be doing other things during the conversion. I don't see any reason you wouldn't use that on a commercial product.

See [ADC conversion on the Arduino (analogRead)](http://www.gammon.com.au/adc) for more details.


body:
I've searched the forum for similar problems and still can't see my obvious issue. I'm working on a simple Halloween prop and I'm using an Arduino for the first time. I've tested each individual 'event' (i.e. fog machine, mp3, actuator, and LED strip) with a loop and all four have worked on continuous loop with no issue.

As soon as I combine them all together, the program runs successfully exactly one time. After that final 10 second delay, when I expect the program to start the loop again, it crashes. If it helps, right during the start of the next loop, the relay light turns on on the relay board for RELAY_1_A and sort of just flickers while the actuator hums. I usually shut it down quickly at this point. As soon as I turn the system back on, it successfully runs through another iteration until the loop hangs.

I'm happy to provide pictures or even a video of the issue if that helps. My guess is that you guys will spot my coding issue right away. Maybe some kind of memory overflow or something like that.

I know my code could be much more efficient but I'm just looking for the glaring problem that is keeping the loop from working.

    #include <SPI.h>
    #include <SdFat.h>
    #include <SdFatUtil.h>
    #include <SFEMP3Shield.h>

    const int RELAY_1_A = 7; //the one with the issue
    const int RELAY_1_B = 8;

    SdFat sd;
    SFEMP3Shield MP3player;
    void setup() {
      // initialize the digital pins as an output.
      pinMode(10, OUTPUT); //Fog machine on Relay1 on 5V relay board
      pinMode(3, OUTPUT); //LED strip off breadboard MOSFET
       pinMode(RELAY_1_A, OUTPUT); //12V relay for actuator on Relay1 on 12V relay board
       pinMode(RELAY_1_B, OUTPUT); //12V relay for actuator on Relay2 on 12V relay board

      //start the shield
      sd.begin(SD_SEL, SPI_FULL_SPEED);
      MP3player.begin();
      MP3player.setVolume(10, 10);
    }

    void loop() {
      MP3player.playTrack(2);  // Play MP3. Track 1 is coffin and track 2 is bird
      delay(5000);              // wait for 5 seconds
      digitalWrite(10, LOW);   // Turns ON fog machine
      delay(3000);
      digitalWrite(10, HIGH);   // Turns OFF fog machine
      digitalWrite(3, HIGH);   // Turn the LED on (HIGH is the voltage level)

      delay(5000);              // wait for 5 seconds

      retractActuator();       //Open coffin
      delay (9000);
      stopActuator();      //Close coffin
      delay (9000);
      extendActuator();      //Close coffin
      delay(8000);
      digitalWrite(RELAY_1_B, HIGH);  //Turns off this relay during the wait period before next loop

      digitalWrite(3, LOW);    // Turn the LED off by making the voltage LOW
      delay(10000);              // wait for 20 seconds

    }
    void extendActuator() {
      //Set one relay one and the other off
      //this will move extend the actuator
      digitalWrite(RELAY_1_A, HIGH);
      digitalWrite(RELAY_1_B, LOW);
    }

    void retractActuator() {
      //Set one relay off and the other on
      //this will move retract the actuator
      digitalWrite(RELAY_1_A, LOW);
      digitalWrite(RELAY_1_B, HIGH);
    }

    void stopActuator() {
     //Set both relays off
     //this will stop the actuator in a braking
     digitalWrite(RELAY_1_A, HIGH);
     digitalWrite(RELAY_1_B, HIGH); }

title: Very easy Arduino code challenge for you brainiacs to solve

Answers: 1

body:
You are attempting to use IO pins that are already in use by the MP3 shield.

According to your subsequent research, only digital pins 0,1,5, and 10 are available for use.

You should shy away from using pins 0 and 1 since they are also connected to the computer through the USB interface and are used for uploading sketches.  You will find that either you can't upload sketches with the relays connected to those pins, or the relays will "randomly" switch on and off while you're uploading a sketch.

Don't forget that the analog pins A0-A5 can also be used as digital pins, so you can quite happily drive your relays using any of those.


body:
**tl;dr** on on digital ouput/input I would like to communicate with a 1-wire device, whose protocol requires precision to ~15 microseconds. My question is if Arduino Uno's serial communication can be as quick as to support to map the digital pin via serial->USB to my host computers app which should implement the 1-wire protocol?

**long version**
The mode in which I thought to use my Arduino was, to attach it to a host computer and run the logic of what should be done on the host computer, having the Arduino only receive the data (for the pins) and return the state of the pins.

The challenge which prompts me to this question is that the Serial communication is not really that quick, compared to the timing requirement of some protocols (e.g. 1 wire) I wish to implement.
For example: 1-wire-protocol's timing requirements (i.e. range of micorseconds) could easily be kept from code running on the Arduino Uno's Atmega328 directly, which at 16Mhz and assumed 2 cycles per command would allow somewhat a resolution of 2/16Mhz = 0,125 us.

If alternatively the data/instruction for the 1-wire protocol should be mapped via the serial interface to an application running on an PC attached to the Arduino I wonder if the time requirements of the 1-wire protocal can be reached?

It boils down to a question if the Serial communication can have a temporal granularity as small as the about 1 to 15 microseconds needed to implement the 1-wire protocol - not within arduino itself - but in the attached PC's application.

title: Can Arduino Uno's serial handle to foward push through 1-wire protocol?

Answers: 3

body:
Ok, so there's two issues at stake here.

1. Can the Arduino generate a 1-wire protocol with enough accuracy?
2. Can you transfer the data fast enough through the UART to tell it to do that generation?

You can't just stream a 1-wire protocol through serial and expect it to work.  The low-level serial protocol would very much get in the way.  So you have to send instructions to the Arduino to say "Raise the IO pin" and "Lower the IO pin" and "Tell me when the IO pin changes level", and "Set the IO pin to input" etc.

Each of those actions would be a discrete item that you would have to send.  Given that you could have a single byte per action (send "I" for set to input, send "O" for set to output, send "L" for set to low, etc - Arduino sends "H" if the pin goes high, or "L" if it goes low, etc), what kind of response could you expect?

Well, at 8 bits + start + stop per byte (so 10 bits) at a good fast rate (say 1MBaud), you would expect one byte to take (1/(1000000/10) = 0.00001s (10µs) to transfer.  That's raw transfer speed.  On top of that you then have to add the processing of that incoming data - the Arduino adds it to a circular buffer to allow your sketch to read it, and that takes time, and your program then interpreting it, you could expect a latency of say 15µs.  At maximum stream rate (no breaks between characters being sent at all) you would have a basic granularity of 10µs (processing the last incoming character while the next one is being received).

That's not counting any other factors such as the UART buffers on your computer, latency before the character even gets to the USB port's endpoint, etc.

So all in all there *might* be a slim chance that you could do it, but it would be *very* slim and not easy to achieve a stable result.

Far better would be to implement the 1-Wire protocol on the Arduino and just send/receive the control information to tell it to go ahead and do the work and return the results.  After all, that's what the Arduino is designed for - low level interfacing like that.

body:
Your idea seems wrong-headed, if I may say so without giving offence.

The Arduino is quite capable of generating 1-wire protocol. It certain reads it easily enough with bit-banging.

Trying to send down HLHLHHHLL through serial because your PC is "more powerful" is just not the right way of doing it. Next you'll be wanting to generate PWM on the PC and have the Arduino relay it to an output pin.

Remember, the Arduino (Uno) runs at 16 MHz. The original IBM PC ran at 4.77 MHz (if I remember correctly) so you can regard the Arduino as being as powerful as an early PC.

The simple solution is to send from the PC the data you actually want communicated by 1-wire, and let the Arduino do the actual bit-banging.

body:
It certainly is possible for an Arduino to do this.  For example, source code for Atmel's implementations of [1-Wire protocol](https://en.wikipedia.org/wiki/1-Wire) via bit-banging, via polling UART, and via interrupt-driven UART, is available at [github.com](https://github.com/semicontinuity/embedded/tree/master/target/card-terminal/firmware/one-wire-thermometer).

There is a 21-page PDF file, [doc2579.pdf](http://www.atmel.com/images/doc2579.pdf), available at Atmel.  It documents how the different implementations work.

However, the notion of communicating faster than serial via the 1-Wire protocol seems like a mistaken notion.  As I understand it, the serial implementations above use one serial character per 1-Wire bit, so necessarily are slower than serial.


body:
My understanding has been that the Serial transmission is indeed done (on the Arduino Uno) via the pins named `TX->1` and `RX<-0`?
With this I assume that the Atmega has a machine code that would allow in 1 or processor cycles (125 or 62.5 ns) to set a byte (i.e. Port byte `DDRD`) as to forward exactly one bit of information for further processing to the `ATmega16U2` "serial to USB" chip?

If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

title: how many processor cycles/time does it minimaly take to transmit 1 Byte via Serial?

Answers: 2

body:
No, it is not true.

You are assuming (wrongly) that the CPU is doing the UART communication.  It isn't.

The UART is a completely separate piece of hardware inside the chip.  It runs by itself.  The CPU merely places the byte to transfer into a *special function register* (*SFR*).  The UART then takes that and clocks it out through the IO pins at the right rate for the serial communication.  While that is going on the CPU is free to perform other operations.

The CPU can then either consult another *SFR* to determine if the transmission has finished, or utilize an interrupt that the UART will trigger when the transfer has been completed.

body:
According to the datasheet:

[![Baud rates at 16 MHz][1]][1]

Running at 16 MHz (as the Uno does) you can get up to 2 Mbps.

> If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

For a bit or a  byte? At 2 Mbps that is a bit every 8 clock cycles.

>  would you know what would the UART be?

The UART is built into the processor chip. I suggest you read the datasheet.

>  I thought it was unable to tell more than 16 million times a second something to the UART, which then could have baud rates higher than what could be indicated by the Atmega328 on the Uno, right?

You can't do *anything* more than 16 million times a second at 16 MHz. And the clocking out of bits (in SPI, serial, or I2C) itself requires clock cycles, although they are done in parallel with the processor instructions by the hardware.

---

This is related to your other thread <https://arduino.stackexchange.com/questions/16032/can-arduino-unos-serial-handle-to-foward-push-through-1-wire-protocol> isn't it? Your end objective, I am guessing, is to try to implement 1-wire reading/writing via sending each bit via serial. This is just not the right way to achieve that objective.

In fact this thread in particular is coming across as an [X-Y problem](http://xyproblem.info/) - your stated objective of wanting high-speed serial, is not really the problem you are trying to solve, is it?

  [1]: https://i.stack.imgur.com/pXJhh.png


body:
I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.

I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file.

I am not sure that is just an idea, any thoughts or solutions?

title: Bluetooth Stream to USB

Answers: 1

body:
If your target is a USB audio device - like a USB headset or USB speakers (NOT an MP3 player with USB interface) then you could connect it to something which can act as a USB host with USB audio device drivers.  That means *not* an Arduino, but something much more powerful like a Raspberry Pi or BeagleBone Black for instance.

If your target is basically an MP3 player that allows you to connect a USB stick with songs on it then you're completely out of luck.  There's this small thing called *time* that gets in your way.  You can't stream data to something that expects the data to already be there. You can't seek in a file that doesn't exist until the moment you try to read from it. Also you have to act as if you were a USB memory stick, and that's not easy, and certainly not something an Arduino can do. Even things like the Pi would have a lot of difficulty in managing that since they are hosts, not devices, as far as USB is concerned.

The key word here is *stream*.  Your target as to be able to receive a *stream* of data rather than request blocks of data from a file.  USB audio *devices* can do that, but USB audio *hosts* cannot.


body:
I mistakenly posted this on stack overflow first.  The community was kind enough to point me to this forum.  I apologize for the double-post.

I've been working on an Arduino Uno r3 + WiFi Shield project for a few months now building up the complexity as I go. I've hit a wall. I started this project with exactly zero experience writing code of any kind and exactly zero experience working with boards. If you have any doubts as to whether or not I'll understand your response, please dumb it down!

I've made a simple arduino + wifi shield setup that can report a button push to a MySql database. All of the .php stuff on the backend works and the database is managed with phpmyadmin. I'm trying to add a second button but can't seem to make it work and need some help.

I have settled on a four-field database table as the output:

* 1st column: the key. A sequential, unique identifier for each entry
* 2nd column: the pin number that the sensor is connected to
* 3rd column: the sensor value
* 4th column: the date and time

Notice that I'm not using a dedicated column for each sensor. By using the sensor pin input, I want to simply print the sensor pin number in a column. This (a) saves space in the table and (b) allows the Arduino to use as many sensors as it has pins.

The idea is that each button press (even if two are pressed simultaneously) will get it's own line, sensor pin source, value, and timestamp. No values will be sent unless a button is pressed.

I haven't the foggiest idea of how to implement this! Help!

---

**My question:**

How can I ask the sketch to retrieve the pin from which a signal originates and write it to the db as a number in the second column? The 13th line of code is what will write the pin number (I think). The "senseval=" needs to be a variable that reports the source pin.

I don't know how to set this up and google has led to nothing but dead ends. I'd like this thread to answer the questions I'm sure a few more people have/will have!

---

My sketch is included below and the insert_php_doc below that. I'm using the Silinas/Benoit "Arduino /Post" example from github:

<!-- language-all: lang-C++ -->

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "linksys";
    int status = WL_IDLE_STATUS;
    WiFiClient client;
    IPAddress server(xxx,xxx,xxx,xxx);

    int inPin_0 = A0; // choose the input pin (sensor #1)
    int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON//
    int sensorSense_0 = 0; //variable
    int sensorSense_1 = 0; //variable //ADDED FOR SECOND BUTTON//
    String SensorVal = "senseval=";// "yourdata="
    String senseval;//yourdata //MUST KEEP sensval for PHP

    void setup() {
      Serial.begin(9600);
      pinMode(inPin_0,INPUT);
      pinMode(inPin_1,INPUT);  //ADDED FOR SECOND BUTTON//
      connectWifi();
    }

    void loop() {
      sensorSense_0=analogRead(inPin_0);
      if (sensorSense_0 == LOW){
        postData();
        delay(5000);
      }
      sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//
      if (sensorSense_1 == LOW){ //ADDED FOR SECOND BUTTON//
        postData(); //ADDED FOR SECOND BUTTON//
        delay(5000); //ADDED FOR SECOND BUTTON//
      }

    void connectWifi() {
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid);

        delay(7000);
      }
    }
    }
    void postData() {
      senseval=SensorVal+String(inPin_0);
      senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

      if (client.connect(server, 80)) {
        Serial.println("connecting...");

        client.println("POST /insert_mysql_doc.php? HTTP/1.1");
        client.println("Host: www.<domain>.com");
        client.println("User-Agent: Arduino/1.0");
        client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded;");
        client.print("Content-Length: ");
        client.println(senseval.length());//yourdata
        client.println();
        client.println(senseval);//yourdata
        client.stop();
      }
      else {
        Serial.println("Connection failed");
        Serial.println("Disconnecting.");
        client.stop();
        connectWifi();
        printWifiStatus();
      }
    }

---

<!-- language-all: lang-php -->

The insert PHP from https://github.com/ericbenwa/POST-Arduino-Data-Wireless:

    <?php

    foreach ($_REQUEST as $key => $value)
    {
        if ($key == "senseval") {
            $senseval = $value;
        }
    }

    // EDIT: Your mysql database account information
    $username = "test_user";
    $password = "test_password";
    $database = "test_db_name_here";
    $tablename = "test_table_name_here";
    $localhost = "localhost";

    // Check Connection to Database
    if (mysql_connect($localhost, $username, $password))
      {
        @mysql_select_db($database) or die ("Unable to select database");

        // Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
        $query = "INSERT INTO $tablename VALUES ($senseval,now())";
        $result = mysql_query($query);
      } else {
        echo('Unable to connect to database.');
      }

    ?>

title: Printing arduino pin numbers to MySQL

Answers: 2

body:
First of all, your statement: "*I've made a simple arduino + wifi shield setup that can report a button push to a MySql database.*" is incorrect (or, at best, misleading) as the code you're running in Arduino is **not** talking with MySQL at all, but simply calling a remote PHP script via an HTTP/POST request.

So now your problem can be split in two parts:

 1. checking if your arduino (via its own wifi shield) is correctly talking with remote HTTP server (invoking proper PHP script with related parameters);

 2. checking if your PHP script is correctly dealing with MySQL.

As for 1), my first suggestion is to check web-server log files. Unfortunately you didn't tell us which web server (Apache? IIS? Other) are you running, as well as which operating system are you relying on (Linux? Windows? Other?). With Apache running on linux, tipically log files are stored in `/var/log/apache` or `/var/log/httpd` folders. There are plenty of other troubleshooting approaches but... please, let's start checking log files, ensuring that PHP script is invoked;

As for 2), your PHP script is lacking basic error-handling: should the `insert` (launched by the `mysql_query` function call) fail, you'll never know. I **strongly** suggest you to add proper error-handling code.
Based on [official documentation][1] it's as easy as checking the result value of the `mysql_query` call: "*...For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error....*" so what you have to do to improve your code (...and being notified about errors raised by MySQL via PHP) is to use something like following code:

    $result = mysql_query($query);
    if (!$result) {
       die('Invalid query: ' . mysql_error());
    }

Having said all the above, let me add a couple of other notes.

 - in your OP, you wrote: "*I'm trying to add a second button but can't seem to make it work*". So it seems that previously you were testing with only one button and, in such a case, everything worked. Is it right? If yes, please, can you tell us what you changed to add proper handling of second button?

 - in your code I see following lines:

.

    [...]
    senseval=SensorVal+String(inPin_0);
    senseval=SensorVal+String(inPin_1);
    [...]

Please note that they are probably wrong, as the second line will override the assignment of the first one. So, with such lines, you'll surely/always loose the value related to `inPin_0` (in other words: the first line, is useless).

 - giving a look to the server-side PHP script, I noted that it has been built to handle only **one** parameter (`sensval` passed to PHP via GET/POST parameter; with PHP storing it in the `$sensval` variable). So... to change the behaviour so to handle two different values... it's not trivial (in other words: such a change require a minimun understanding of web-programming and... getting deep to analyze such requirement is out of scope --I think-- of this answer).

  [1]: http://php.net/manual/en/function.mysql-query.php

body:
    int inPin_0 = A0; // choose the input pin (sensor #1)
    int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON/

    ...

      senseval=SensorVal+String(inPin_0);
      senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

The above is wrong because you are sending the **pin numbers** and not the values read from those pins. You previously read them here:

      sensorSense_0=analogRead(inPin_0);
      ...
      sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//

It is `sensorSense_0` and `sensorSense_1` that you should be sending.

Also, as Damiano Verzulli pointed out, your second assignment to `senseval` clobbers the first. You want something more like:

      senseval  = SensorVal + String(analogRead(inPin_0)) + ", ";
      senseval += SensorVal + String(analogRead(inPin_1));

Even that may not be perfect, I didn't read your PHP side.

---

Looking at the PHP side now:

    $query = "INSERT INTO $tablename VALUES ($senseval,now())";

That isn't going to work too well for two values. I don't know your database schema, but that won't handle two values very well. A bit of tweaking and it might, or you could do two `INSERT` statements.


body:
I'm a newbie trying to control something through a relay. I've tried two relays with two different setups.

# Setup 1
External 12V dc input to the relay (SRD-12VDC-SL-C) and signal pin from arduino to the IN pin, GND of ext. power supply to the GND of the Arduino, NO and COM to the load object (i.e. an LED).

# Setup 2
Similar to setup 1, but using SRD-05VDC-SL-C, 5V from Arduino (Vin from Arduino also tested).

# Test program
Modified version of the 'blink' example.

# Symptom
1. The load object has been verified to be working before the testing.
2. Both setup can be verify the input is working, the power led and switch led of the two relay module are lighted as expected, and I can hear the click sound while switching.
3. No output can be obtained, both from the load object and using a multimeter.

# Update
[![relay setup][1]][1]
<br>
Sorry, I'm supposed to upload a Fritzing schematic, but I can't find a proper relay as I'm using.

1. The DC+ (red) of the relay is connected to the external ATX 12V.
2. The DC- (black) of the relay is connected to the external ATX ground.
3. The IN (blue) of the relay is connected to the Arduino pin 8.
4. The external ATX ground (white) is connected to the Arduino ground.
5. The NO (red) of the relay is connected to the load object Vcc.
6. The COM (black) of the relay is connected to the load object ground.

# Sketch

A simple modified version of Blink example is used for testing.

    const int relaySignalPin = 8;

    void setup() {
      // put your setup code here, to run once:
      pinMode(relaySignalPin, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(relaySignalPin, HIGH);
      delay(1000);
      digitalWrite(relaySignalPin, LOW);
      delay(1000);
    }

# Question
I have no idea on why there's no voltage can be obtain between NO and COM while the switch is on, what's wrong with my setup?

  [1]: https://i.stack.imgur.com/zQwqC.jpg

title: Arduino connecting relay has no power output

Answers: 2

body:
It sounds, from your textual description (*please* post a schematic or at least a photo of your setup) that you aren't providing power to the relay.

A relay doesn't have a *power output*.  It never *provides* power - it is merely a magnetically operated switch.  It is used to switch an external source of power on and off.

Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.

You can share the same power supply as you are feeding to the logic / drive side of the relays.

body:
So basically there are two wires connected to the same positive 12v source, one connected to VCC on the input side of the relay board and the other connected to the output side common terminal.
And there are three connections from the same negative 12v source, one connected to the ground of the relay board, one connected to the ground of the arduino, and the other connected to the ground of the load.
Then, of course, the connection to the relay to one of the digital pins of the arduino.

Well I'm pleased to report it works!

Now to discover what the jumpered COM/GND connection on my relay board does or does not do. I will report back.


body: Can a Ethernet USB Dongle be instead of Ethernet shield for arduino in order to cut costs?

title: Can a Ethernet USB Dongle be instead of ethernet shield for arduino?

Answers: 3

body: No.  Arduino can't behave as USB host.

body:
Possibly with an Arduino Due in USB OTG mode if you want to spend months and months (or even years) delving into the USB specs, reverse engineering the driver for the USB dongle and writing the software to get it working.

"Possible" but certainly not worth it when you can use a simple Ethernet shield and have it all working within a day.

And definitely not possible on anything like an Uno, etc.

Also it's possible on an Arduino that runs a full operating system (Linux) like the Edison or (possibly) the Yun (OpenWRT side of the operations, not the Arduino side).

body:
No, not directly. As @Majenko pointed out its possible but most likely over your head. I am not a big fan of the ethernet shield as I like to use my Arduino for prototyping and then build the project with the components. There are a 2 easy alternatives which are inexpensive options for accessing a network or internet via the Arduino

 - ENC28J60 Ethernet LAN Network Module
 - Esp8266 Serial Wifi Wireless Transceiver

Both are inexpensive (between $5 and $7 USD). There are tons of tutorials on line to get you up and running


body:
Can we use serial communication in arduino only for RX pin, so that I am free to use pin 1(TX) as digital I/O:

<!-- language: c -->

    Serial.write('a');
    pinMode(1,OUTPUT);
    digitalWrite(1,LOW);

Answers: 1

body:
<!-- language-all: lang-C++ -->

HardwareSerial takes over the Tx and Rx pins. However you can use SoftwareSerial.

Arduino forum user whiteglint143 made an adaptation of SoftwareSerial that does read-only.

<http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip>

See [Receive Only Software Serial  - Arduino Forum](http://forum.arduino.cc/index.php?topic=240741.0)

---

> You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Like this?

    const byte LED = 1;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      UCSR0B &= ~bit (TXEN0);  // disable transmit
      Serial.println ("Testing");
      pinMode (LED, OUTPUT);
      }  // end of setup

    void loop ()
      {
      digitalWrite (LED, HIGH);
      delay (500);
      digitalWrite (LED, LOW);
      delay (500);
      }  // end of loop

Gerben's suggestion works, in a sense. The pin flashes, but rather disconcertingly, the Tx LED on the board also flashes, out of sync with pin 1. Clearly the signal is making its way to the ATmega16U2 chip, which then flashes the indicator LED. This may not be desirable if you have something connected to the serial port, as it may be interpreted as low-speed serial communications.


body:
I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.

I tried this: `rsync -avz ./ root@192.168.100.177:/node_app_slot/`

But `rsync` is not installed on the board.

How would you do this?

title: How to rsync my node.js project to my intel edison board, through ssh?

Answers: 2

body: rsync works by talking to the rsync executable running on the remote target; without said executable you will need to drop to either scp or a tar pipe.

body:
You have few options:

 1. use the Yocto sdk to compile rsync and then deploy it
 2. switch to [Debian][1] and then use the standard way to deploy rsync
 3. use scp, like the OP wrote, using the [answer][2] from Rick

If you are already looking for a more typical Unix way of doing things, option 2 might be the most efficient for you, in the long run.
I have not tried it, but AFAIK it should be possible to revert easily, since Edison uses dfu for system upgrades, so you should be able to go back to the stock SW, in case you do not like the Debian installation.

  [1]: https://learn.sparkfun.com/tutorials/loading-debian-ubilinux-on-the-edison
  [2]: https://unix.stackexchange.com/questions/105140/how-to-copy-only-new-files-using-scp-command


body:
Arduino Uno based on 328p micro-controller board only works while I am inserting the serial cable between the board and the computer and I can control the speed of my two motors and every thing is work properly, but when I eject the serial cable it works badly and there is no control, is that some thing occurs like auto Reset?

There is always 5 volt feeding the Arduino, I get 5 volt regulated from the battery using "5v regulator", this regulated voltage is always connected to the Arduino board.

title: Why did my program stop working when I eject the serial cable like it did an auto reset?

Answers: 1

body:
Try increasing the voltage of the power supply. Maybe there might be a problem with the current. The Arduino has a 5V regulator on-board, try using a 9V battery. MAKE SURE THAT YOU CONNECT TO THE DC BARREL CONNECTOR.

Good luck!


body:
Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.
[![enter image description here][1]][1]

Just to confirm, the two XBee's do communicate if I use SoftwareSerial.   This is the code that works using SoftwareSerial:

    #include <SoftwareSerial.h>

    // XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
    // XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
    SoftwareSerial serial1(10, 11); // RX, TX
    boolean nextLine = false;
    void setup()
    {
      Serial.begin(9600);
      serial1.begin(9600);
    }

    void loop()
    {
       while(serial1.available()){ // there is data being sent from the xBee
        char read = char(serial1.read());
        if(read == 'A'){
          //Where ~ is the EOT character
          serial1.write("55.134~");
        }
      }
    }
How do I communicate using Serial1?

  [1]: https://i.stack.imgur.com/UyKUE.jpg

title: Communicating Via Serial1 on Arduino Mega

Answers: 2

body:
There is a good [example][1] on the Arduino site, but in short, you'd use the Serial1 (or -2 or -3) object the same way you use the Serial object:

    Serial1.begin(9600);
    if( Serial1.available() ){ ... }
etc.

  [1]: https://www.arduino.cc/en/Tutorial/MultiSerialMega

body: If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield *does not* connect to that header, therefore you *cannot* use `Serial1` through `Serial3` with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.


body:
I bought a 10 V Piezzo electric buzzer and I wonder how to connect it to an Arduino (in my case a Lilypad USB, but the question stands for any Arduino I guess...).
I hadn't realized this was a 10V buzzer, whereas the Arduino will support at most 5V.

I tried a simple layout such as below, with [the sample code from a sparksfun tutoral](https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-11-using-a-piezo-buzzer), but that's not working!

[![lilypad connected to buzzer][2]][2]

So, how can I do it? ... or should I use another buzzer ?

Thanks

  [2]: https://i.stack.imgur.com/PaTyG.png

title: Using Piezzo Electric buzzer 10V with an Arduino Lilypad USB

Answers: 1

body:
Your options:

 1. Try it anyway with 5V: the buzzer might still produce loud enough sounds for your needs.
 2. Use the line from the arduino to drive an "amplifying" stage (ex: 2N2222 in ON/OFF mode) - but this will also require a 10V source (like a step-up voltage converter)
 3. Get a piezo that is designed to operate at 5V


body:
I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.

The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).

Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?

title: 10k ohm Potentiometer vs 10k ohm Resistor on LCD Display

Answers: 2

body:
No, it would not be correct to use a single resistor to replace a potentiometer.

On an LCD the potentiometer is used to adjust the *bias level* of the LCD - that is the contrast.  You need to use it to set a voltage between Vcc and Vee, which you feed into Vo.  That is, a voltage somewhere between +5V and -5V.

You can't do that with one resistor.

You can, however, do it with two resistors.  Some experimentation will provide the right values to use.  Pick a pair of resistors which add up to around 10K (the exact value doesn't matter that much) and join them together end to end.  The two ends are the equivalent to the ends of the track of the potentiometer, and the join in the middle is the wiper.

To change the "value" of the potentiometer you then need to change the value of both resistors.  If you reduce one resistor you need to increase the other so that they still add up to around the same value.  What you are working with here is not the actual values of the resistors, but the ratio of the values of the two resistors.

body:
you can use the digital pin to do this instead of resistance or potentiometer. I used a delay 500 which gave me good readable display. a value of 100 was to bright

    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop()
    {
     digitalWrite(13, HIGH);
      delayMicroseconds(500);
    /* 100 gives Approximately 10% duty cycle @ 1KHz with 500 i get a good value for screen text brightness*/
      digitalWrite(13, LOW);
      delayMicroseconds(1000 - 500);

    /* now you can add your LCD code to print what ever you like.*/
    }


body:
I need to hard reset (or seriously breathe life into) a stuck Arduino clone (Sunfounder UNO) which doesn't get recognized by Windows (error 43) after installing the wrong sketch. I am using the latest Arduino toolset and, before today, the setup was functional.

The problem is probably that I am writing to the serial in the `setup()` section like this:

<!-- language: c -->

    void setup() {
      pinMode(a0, OUTPUT);
      pinMode(a1, OUTPUT);
      pinMode(a2, OUTPUT);
      pinMode(b1, OUTPUT);
      pinMode(m0, OUTPUT);
      pinMode(m1, OUTPUT);
      pinMode(m2, OUTPUT);
      pinMode(OK, OUTPUT);
      pinMode(KO, OUTPUT);

      pinMode(carry, INPUT);
      pinMode(result, INPUT);
      delay(1000);

      Serial.begin(9600);
      Serial.write("Arduino Tester v. 0.1\n");
    }

Arduino seems to be running the code. The problem is that Windows doesn't recognize it and doesn't set up a COM port for it.

So: i'd like to nuke it and restart from scratch.

How is this done?

title: Hard-resetting an arduino

Answers: 1

body:
The word "clone" immediately rings alarm bells.

Firstly, for a "normal" Arduino (like an Uno, etc) the sketch cannot influence whether Windows detects the board or not.  All that is handled by a completely separate chip.

A lot of the cheap clones these days are coming out of China with a really really cheap USB serial adapter chip.  These barely work at the best of times.  Looking at the pictures I have found of your clone (the manufacturer's site is considerably lacking in any information whatsoever) it doesn't look like it's one of those chips, but one never can tell.

If they have followed the reference designs for the Arduino then it will be an Atmel ATMega32U4 (IIRC) chip that deals with the interface to the computer.  That has firmware of its own on it, and if that has become corrupted (very unlikely) or damaged (possible) then it could cause it to not be recognised.  If that is the case the in the former instance (corrupted) you will need to replace the firmware on it. For that you will need either a hardware ICSP programmer or another Arduino.  In the latter instance you're stuffed, since you would need to replace the chip.

As I say that is unlikely.

Instead your problem is most likely actually with either Windows or the USB cable.  You may need to remove and reinstall the Arduino drivers, or try a difference USB cable.  Also try your "Arduino" on another computer.


body:
I recently bought a Smart Servo Shield controller from DFrobot to use with my new AX-12A Dynamixel servos. The shield is attached to an Arduino Uno. The shield itself works fine, but it does not support all of the functions that I need. The shield has an AtMega8 on board, and they also give you the slave code that it runs to look over. If I were to modify said slave code, is there a way for me to upload to the shield's controller? If so, how would I go about doing that?

Smart Servo Shield
http://www.dfrobot.com/index.php?route=product/product&product_id=958#.VfXqzxFVhBc

title: Smart Servo Shield: How to upload code to AtMega8

Answers: 1

body:
Like the wiki says, remove the solder jumpers from the "UART SELECT" jumpers and connect to the "UART FOR Atmega8" connector in order to program it via serial. Don't forget to replace the solder jumpers after.

If you want to use ISP instead then make sure to remove the shield from the Arduino first since the shield connects all the ATmega8 ISP lines directly to the Arduino ISP lines.


body:
Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?

I have a system with an ethernet port to connect to the internet. It works fine if I plug it into my switch at home. However, I would like this system to have its own cellular internet connection.

This is what I have found so far:

 1. I'm basically trying to replicate the following:
https://nimbelink.com/e2clink-ethernet2cellular/#parts

 2. If the following reddit post:
https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/
 is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.

title: Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino

Answers: 1

body:
No, it's not possible.

Chiefly because the normal Ethernet shield is not capable of routing.  The Arduino never talks to the ethernet - it talks to the chip on the shield and tells it how to handle the ethernet connection - everything else is then done by the ethernet chip and the results passed back to the Arduino.

Similarly with GSM - you make requests to it and it goes off and does the work.

To link the two together you would need raw access to the incoming ethernet packets, and you would then have to perform NAT (Network Address Translation) and maintain internal state tables for current streams and such, and pass reformatted packets on to a GSM modem that could accept raw data like that.

Way outside the scope of a lowly Arduino.

Maybe possible with one of the higher end Arduino-ish systems like the Edison, Galileo or Yun (just) since they run Linux and have a real Ethernet port and a proper USB port to communicate with a proper celular modem.


body:
I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage.
I get this in the Serial monitor:
[![Serial monitor output][1]][1]

  [1]: https://i.stack.imgur.com/ciBPt.png

My code:

    /*
      Web client

     This sketch connects to a website (http://www.google.com)
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 18 Dec 2009
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe, based on work by Adrian McEwen

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    IPAddress server(216, 58, 217, 206); // numeric IP for Google (no DNS)
    //char server[] = "www.google.com";    // name address for Google (using DNS)

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 0, 177);
    IPAddress dns(192, 168, 1, 122);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        // wait for serial port to connect. Needed for Leonardo only
      }
      delay(5000);
      // start the Ethernet connection:

      Ethernet.begin(mac, ip, dns, gateway, subnet);
      Serial.println("connected to ethernet");
      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");

      // if you get a connection, report back via serial:
      int ch = client.connect(server, 80);
      if (ch) {
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /search?q=arduino HTTP/1.1");
        client.println("Host: www.google.com");
        client.println("Connection: close");
        client.println();
      }
      else {
        // kf you didn't get a connection to the server:
        Serial.print("connection failed, error code ");
        Serial.println(ch);
      }
    }

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

Any help is greatly appreciated.

title: Client.connect galileo gen2 not working

Answers: 1

body: 6 months after figuring out the answer, I found this question again. I solved this question by adding `system("ifup eth0")` which completely solved the problem.


body:
Please help me with this code it's shows some error [but I can't be bothered to tell you what].

    #include <TimerOne.h>

    /**

     Analog Clock

     Paul Cox Dec 2010

    */

    #define    PI       3.141592653589793e-06;

    byte rows[8] = {9, 14, 8, 12, 1, 7, 2, 5};

    byte cols[8] = {13, 3, 4, 10, 6, 11, 15, 16};

    byte pins[16] = {5, 4, 3, 2, 14, 15, 16, 17, 13, 12, 11, 10, 9, 8, 7, 6};

    byte screen[8] = {0, 0, 0, 0, 0, 0, 0, 0};

    volatile byte screenRow = 0;

    volatile byte screenCol = 0;

    int iHour = 0;

    int iMin = 0;

    int iSec = 0;

    void setup()

    {

      Timer1.initialize(100);

      for (int i = 2; i <= 17; i++)

      {

         pinMode(i, OUTPUT);

      }

      Timer1.attachInterrupt(doubleBuffer);

      Serial.begin(9600);

      resetAnim();

    }

    void doubleBuffer()

    {

      digitalWrite(translatePin(rows[screenRow]), LOW);

      digitalWrite(translatePin(cols[screenCol]), HIGH);

      screenCol++;

      if (screenCol >= 8)

      {

         screenCol = 0;

         screenRow++;

         if (screenRow >= 8)

         {

           screenRow = 0;

         }

       }

       if((screen[screenRow] >> screenCol) & B1 == B1)

       {

         digitalWrite(translatePin(rows[screenRow]), HIGH);

         digitalWrite(translatePin(cols[screenCol]), LOW);

       }

       else

       {

         digitalWrite(translatePin(rows[screenRow]), LOW);

         digitalWrite(translatePin(cols[screenCol]), HIGH);

       }

    }

    byte translatePin(byte original)

    {

      return pins[original - 1];

    }

    void allOFF()

    {

      for (int i = 0; i < 8; i++)

      {

         screen[i] = 0;

      }

    }

    void on(byte row, byte column)

    {

      screen[column-1] |= (B1 << (row - 1));

    }

    void off(byte row, byte column)

    {

      screen[column-1] &= ~(B1 << (row - 1));

    }

    void resetAnim()

    {

      for (int i = 0; i < 8; i++)

      {

         screen[i] = B11111111;

         delay(25);

      }

      for (int i = 0; i < 8; i++)

      {

         screen[i] = B00000000;

         delay(25);

      }

    }

    void loop()

    {

      drawClock();

      iSec++;

      if (iSec == 60)

      {

        iSec = 1;

        iMin++;

        if (iMin == 60)

        {

           iMin = 0;

           iHour++;

           if (iHour == 12)

           {

              iHour = 0;

           }

        }

      }

      delay(10);

    }

    void drawClock()

    {

      allOFF();

      setHand(iHour,12,3);

      setHand(iMin,60,4);

      setHand(iSec,60,5);

    }

    // work out the pixel for a hand - val is out of a possible max val

    // radius is distance from the centre

    void setHand(int iVal, int iMax, int iRadius)

    {

      double  dAngle = (iVal * 2 * PI) / iMax;

      double  dPosX = 4.5 + (iRadius * cos(dAngle));

      double  dPosY = 4.5 + (iRadius * sin(dAngle));

      drawLine(5,5,constrain(round(dPosX),1,8),constrain(round(dPosY),1,8));

    }

    void drawLine(int x0, int y0, int x1, int y1)

    {

      int      iTemp;

      boolean  bSteep = abs(y1 - y0) > abs(x1 - x0);

      if (bSteep)

      {

         iTemp = x0; x0 = y0; y0 = iTemp;    // swap x0,y0

         iTemp = x1; x1 = y1; y1 = iTemp;    // swap x1,y1

      }

      if (x0 > x1)

      {

         iTemp = x0; x0 = x1; x1 = iTemp;    // swap x0,x1

         iTemp = y1; y1 = y0; y0 = iTemp;    // swap y0,y1

      }

      int deltax = x1 - x0;

      int deltay = abs(y1 - y0);

      int error = deltax / 2;

      int ystep = ((y0 < y1) ? 1 : -1);

      int y = y0;

      int x = x0;

      while(x <= x1)

      {
        if (bSteep)
        {
           on(y,x);
        }
        else
        {
           on(x,y);
        }
        error = error - deltay;
        if (error < 0)
        {
           y = y + ystep;
           error = error + deltax;
        }
        x++;
      }
    }

title: Problem with Arduino code

Answers: 1

body:
It's amazing the difference one character can make:

* You must NEVER terminate a #define with a `;` unless you absolutely know that you need one when it is expanded.

You have a macro defined:

    #define    PI       3.141592653589793e-06;

That macro is then used here:

    double  dAngle = (iVal * 2 * PI) / iMax;

Expand the macro PI and you get:

    double  dAngle = (iVal * 2 * 3.141592653589793e-06;) / iMax;

Which obviously is a syntax error - you have a rogue `;` in there where you really don't want one.

Oh, and one other thing - you shouldn't define PI - the Arudino core already defines it for you to a greater accuracy than you are:

    arduino/Arduino.h:#define PI 3.1415926535897932384626433832795

... though you seem to be working in microPi's whatever those are...


body:
I am a software engineer who is new(er) to electronics, I only started a couple of months ago. I've built a bunch of custom circuits, then some arduino nodes that are around my apartment that communicate with a C# server. So I've at least got the breadboarding part down.

So now I am working on a controller board that connects to my home automation system and determines the color on the LED light strips I installed into my bookshelf. So I want to transfer from working with pre-built Arduinos to building my own full node, there are some things I think I'm missing.

I've noticed that there are duplicate parts on the schematic for the [Arduino Mega2560 schematic][1] (such as there being 2 voltage regulators - one is replacement if the other is not available). I couldn't find any such description however for why there are 3 crystals located on the board. I see 3 different circuits for crystals (all of which are 16MHz).

Specifically, I am referencing the following
[![Crystal 1][2]][2]

[![Crystal 2][3]][3]

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
  [2]: https://i.stack.imgur.com/ylfe5.jpg
  [3]: https://i.stack.imgur.com/3vI1B.jpg

title: Why are there 3 crystals on the Mega2560 schematic?

Answers: 1

body:
One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.

The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal.

Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires.

---

As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.


body:
I want to create a LED Sunrise/Sundown alarm clock. Therefore, I will use a Raspberry Pi that is sending commands over serial to a Teensy 3.1. Like:

 - "30 Minute Sunrise starting with Color(255,140,0)"
 - "20 Minute Sundown with Color(255,140,0)"
 - "start something else with these 3 parameter.

But I don't even get the basic serial part working. E.g. I tried this:

    void setup() {
      Serial.begin(9600);
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      if (Serial.available() > 0) {
        if (Serial.read() == 'A'){
          int inte1 = Serial.parseInt();
          int inte2 = Serial.parseInt();
          int inte3 = Serial.parseInt();
          int inte4 = Serial.parseInt();
          int inte5 = Serial.parseInt();
          if (Serial.read() == '\n') {
            Serial.print(inte1);
            Serial.print(inte2);
            Serial.print(inte3);
            Serial.print(inte4);
            Serial.println(inte5);
          }
        }
      }
    }

I planned to do a `case` switch afterwards. `Inte1` should define sunrise/sundown, `Inte2` the minutes, 'Inte3-5' the rgb color.

However, when I enter "A 1 100 100 100" it is not printing anything at all.

What is the best way do get this working?

Thanks in advance!

title: How do I start a function with serial input?

Answers: 1

body:
Okay, as Majenko and Nick Gammon have suggested. The `\n` had not arrived in the serial buffer. That way the if clause was not fulfilled and nothing was printed. This code has worked for me now:

    if (Serial.available() > 0) {
     if (Serial.read() == 'A'){
      char inte1 = Serial.read();
      int inte2 = Serial.parseInt();
      int inte3 = Serial.parseInt();
      int inte4 = Serial.parseInt();
      int inte5 = Serial.parseInt();
      Serial.print(inte1);
      Serial.print(inte2);
      Serial.print(inte3);
      Serial.print(inte4);
      Serial.println(inte5);
     }
    }
Although i read quite a bit now, serial input is still a mystery to me.


body:
Does anyone know where I can get the potentiometer that comes with the Arduino kit? You can see them [here][1].

[They are sold out on their website][2].

  [1]: http://www.arduino.cc/documents/datasheets/Potentiometer.PDF
  [2]: https://store.arduino.cc/product/C000013

title: Where to get the potentiometer that comes with Arduino kit

Answers: 1

body:
It's just any old trimmer pot. It's nothing special. Why do you feel you need that specific one? Any pot (of the right value) will do.  What value is it? (That datasheet is a generic one for all values).

Visit your favourite electronics retailer (IRL or on line) and pick a pot that is a suitable value and jiffles your tipples.


body:
How can I evaluate a pulsed signal in Arduino? The signal comes from an car alarm system and is called (-) output 200 mA. Arduino and the car have the same GND. Can I attach the output through a resistor to PB0 (D8) or PD5 (D5)?
Alarm system is called Ampire. Probably the same as Viper. I just wanted to read these pulses, but I do not know exactly how I connect this output correctly with Arduino.
This is the description for this Output:

----------

 **HN1/9 BROWN/WHITE – 200mA (-) Horn honk output: This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit**.

----------

title: Looking for circuit diagram for evaluation of a pulsed signal

Answers: 1

body:
I found a user manual at [AMPIRE Car Alarm System for High-Speed CAN-Bus](http://www.ampire.de/Security-Systems/Security-for-CAN-Bus-System/AUDI/AUDI-A3/from-model-year-2013/AMPIRE-Car-Alarm-System-for-High-Speed-CAN-Bus.htm?shop=ampire_en&SessionId=&a=article&ProdNr=CAN3903V&t=2899&c=16941&p=16941).

> **N1/9 BROWN/WHITE – 200mA (-) Horn honk output:**
>
This wire supplies a 200mA (-) output that can be
used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed
and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the
vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used
to interface with the vehicle’s horn circuit.

> **IMPORTANT!**
 Never use this wire to drive anything but a relay or a low-current input! This transistorized output can only supply (-) 200mA and connecting directly to a solenoid, motor or other high current device will cause the module to fall

Judging by that this output will sink up to 200 mA. You could conceivably set an Arduino pin to INPUT_PULLUP and let this output drive it low to indicate it is active.

Personally I think I would use an optocoupler, in case there were unexpected voltages on that pin. You would need a series resistor to limit current through the LED in the optocoupler, say 1 k would be about right if you were connecting it to the 12V car system.

    Vf = 1.2V (say)
    Voltage over resistor = 12 - 1.2 = 10.8 volts
    Current through LED = 10 mA
    Limiting resistor = 10.8 / 0.01 = 1080 ohms

Now the output of the optocoupler can sink your Arduino pin, which you have configured as input pullup.

Write a test sketch to see what you are getting through it, but a multimeter should probably tell you, if it just flashes it slowly.

---

Suggested schematic:

[![Schematic for optocoupler][1]][1]

  [1]: https://i.stack.imgur.com/SiiN1.png


body:
After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.

What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.

Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.

title: Making servo spin and able to detect angle

Answers: 2

body:
The way I'd do it is the following:

 * use an optical encoder with an [endstop][1], they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
 * use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you
the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost.
So you could explore the DC option if it turns out that the stepper is not good enough.

  [1]: http://img.diytrade.com/smimg/1033354/32796591-447715-0/Optical_Endstop_for_3D_printer_use_together_with_RAMPS_1_4_controller/ed5e.jpg

body: As for Me the Best Way to To Use a Position Servo with the Feedback in it ( it comes with 6 wire ) then You put all Your Positions For the prizes in An Array and if Anytime You Land on An Index then You Should but it in an Array that Holds all the prizes angle visited Which you will use as a check Before Turning the Servo


body:
I've built a bareduino. The blink sketch that it came preprogrammed with worked. I was also able to program the ATmega328 by putting it into a arduino uno.

What I can't do is upload a sketch directly. I've tried both of the methods described here: https://www.virtuabotix.com/bareduino328-programming-guide/

I've used FTDI before and I know that my drivers work. I've tried suggestions from many forums and after 3 hours I'm running out of options.

The issue seems to be the reset pin. But the fixes here have not worked. I must admit I'm confused about how to un-ground the reset pin. I tried unplugging the power. When I tried to upload with FTDI I had a capacitor... so shouldn't that fix this error?

Verbose Error Code:

    Sketch uses 7,920 bytes (24%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 383 bytes (18%) of dynamic memory, leaving 1,665 bytes for local variables. Maximum is 2,048 bytes.
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1d11 -b115200 -D -Uflash:w:/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build7068227750495702499.tmp/webclient.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/futurebird/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbmodem1d11
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

title: Can't program bareduino. "avrdude: stk500_recv(): programmer is not responding"

Answers: 0


body:
I'm trying to get the potentiometer seen at the top left of the photo to work, essentially as a dimmer. I've managed to upload the Arduino sketch, but it isn't working. Any help would be greatly appreciated!
NB: I have little-to-no electronics experience so my understanding of jargon is limited.

Thanks!

    /*
     SENSOR_LIGHTS: Potentiometer >> LED (Single Channel Script)

     This example dims light levels using an LED on pin 11
     and a potentiometer on A0.

     Created by Ryan Achten | SOMA | somavisions.com

     This example code is in the public domain.
     */

    int potentLevel;
    int ledLevel;

    //*************************CHECK*****************************

    int led = 11;           // the pin that the LED is attached to
    int inputPin = A0;      // the pin that the potentiometer is attached to

    //*************************CALIBRATE*************************

    const int numReadings = 1;  //change this to alter the number of values to be averaged
    int potentMin = 280;
    int potentMax = 700;        //maximum output from potentiometer
    int loopDelay = 100;       //delay time between loops. Too low may cause overclocking
    //                            while too high may cause delayed sensor response

    //***********************************************************

    int potentAve = 0;
    int readings[numReadings];
    int index = 0;
    int total = 0;

    // the setup routine runs once when you press reset:
    void setup()  {

      //*************************POTENT >> LED SETUP CODE*************************

      Serial.begin(9600);

      pinMode(led, OUTPUT);

      //***************************SMOOTH SETUP CODE*****************************
      // initialise all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++)
        readings[thisReading] = 0;

    }

    //****************************SMOOTH LOOP CODE****************************

    void loop()  {

      total= total - readings[index];
      readings[index] = analogRead(inputPin);
      total= total + readings[index];
      index = index + 1;

      if (index >= numReadings)
        index = 0;

      potentAve = total / numReadings;
      Serial.print("Average Potentiometer Readings: ");
      Serial.println(potentAve);

      //*************************POTENT >> LED LOOP CODE*************************

      ledLevel = map(potentAve, potentMin, potentMax, 0, 255);
      Serial.print("LED Level: ");
      Serial.println(ledLevel, DEC);
      analogWrite(led, ledLevel);

      Serial.println();
      delay(loopDelay);

    }

[![Electronics Schematic][1]][1]

[![Photo of electronics][2]][2]

  [1]: https://i.stack.imgur.com/9idR0.jpg
  [2]: https://i.stack.imgur.com/Oq9U7.jpg

title: Potentiometer won't work

Answers: 1

body:
Assuming the brown board in your drawing is stripboard, I have to as the question:

What is this?

[![enter image description here][1]][1]

If those five wires in that column are all ground, that link is basically short circuiting your MOSFET via the green wire next to it, thus rendering your whole circuit pointless.  The LEDs will just be on full brightness permanently since the current just flows from the input power, through the LED strip, through the red/white wire, through that little white link wire, then through the green/white and/or the brown/white wires to ground.

  [1]: https://i.stack.imgur.com/dVdT7.png


body:
I make simple code to read web page by [ITEAD Gboard][1]. Here is my code:

      Serial.write("\nStarting..........\n");
      mySerial.print("AT+CSQ");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----1-----\n");

      mySerial.println("AT+CGATT=1");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----2-----\n");

      mySerial.println("AT+CGATT?");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----3-----\n");

      mySerial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----4-----\n");

      mySerial.print("AT+SAPBR=3,1,\"APN\",\"internet\"");
      delay(2000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----5-----\n");

      mySerial.print("AT+SAPBR=1,1");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----6-----\n");

      mySerial.print("AT+HTTPINIT");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----7-----\n");

      mySerial.print("AT+HTTPPARA=\"URL\",\"xx.xx.xx.xx/my/web/site\"");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----8-----\n");

      mySerial.print("AT+HTTPDATA=100,1000");
      delay(10000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----9-----\n");

      mySerial.println("AT+HTTPREAD");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\nend.\n");

Which i get the following output:

    Starting..........
    AT+CSQ
    -----1-----
    AT+CGATT=1

    ERROR

    -----2-----
    AT+CGATT?

    +CGATT: 1

    OK

    -----3-----
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    -----4-----
    AT+SAPBR=3,1,"APN","internet"
    -----5-----
    AT+SAPBR=1,1
    -----6-----
    AT+HTTPINIT
    -----7-----
    AT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"
    -----8-----
    AT+HTTPDATA=100,1000
    -----9-----
    AT+HTTPREAD

    ERROR

    end.

AT+HTTPREAD return error. What wrong with me?

**Note**

xx.xx.xx.xx/my/web/site is my web page. The error is still there for all web page.

  [1]: http://imall.itead.cc/gboard.html

title: Problem in SIM900 GPRS connection

Answers: 1

body:
The problem (I believe) is that half way through your program you switched from using `println()` to using `print()`, thus the commands from that point on aren't being executed until right at the end where you switch back to `println()`, so the whole of the text you send from point 3 onwards is being run as one single command - which of course is in the wrong format:

> AT+SAPBR=3,1,"CONTYPE","GPRS"AT+SAPBR=3,1,"APN","internet"AT+SAPBR=1,1AT+HTTPINITAT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"AT+HTTPDATA=100,1000AT+HTTPREAD