body:
I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?

    long num = 0;
    long startTime = 0;
    long endTime = 0;
    int duration = 0;
    String buffer;

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

    void loop(){
      startTime = millis();
      benchmark();
      endTime = millis();
      duration = endTime - startTime;
      Serial.print(startTime);
      Serial.print(", ");
      Serial.print(endTime);
      Serial.print(", ");
      Serial.println(duration);
    }

    void benchmark() {
      num = 0;
      for(num = 0; num < 1000000; num++);
    }

I'm using an Uno, if that matters.

title: How do you benchmark an Arduino?

Answers: 3

body:
No.

That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.

Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).

body:
First of all, compiler will just remove your loop, unless you disable compiler optimization, witch will invalidate your test.
Also don't worry about clock drift; as clock also run instruction, a faster clock will also mean a faster instruction cicle, so in the end if you calculate instruction/s the value will be valid.

Also serial communication slowness is not a problem as you calculate the value BEFORE sending anything.

Now, exactly what you want benchmark? In your case, you should put some instruction the for, like a variable++, and then print that sum (if you don't use it, again compiler will optimize all away)

But the you are bancharking for and ++. You may use a NOP() instruction, and then a float, a bitshift, a function call, and so on; you will find very different result, sometimes, sometimes compilator will trick your code.

Then when you'll have banchamark, against what will you compare your result?

body:
Quite simply, you cannot measure the stability of a device using routines that themselves depend on the device clock.

 To do this properly you need an external measuring device that has a clock source at least 10 times more stable than the Arduino xtal. Most frequency counters would qualify.
Just set up a timer to provide a constant output frequency, and attach the counter to the pin.


body:
How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?

If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

title: MHz Sampling Rate for Arduino

Answers: 1

body:
The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.

The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.


body:
I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.

Here is the sketch:
<!-- language-all: lang-cpp -->

    /*
     SMS receiver

     This sketch, for the Arduino GSM shield, waits for a SMS message
     and displays it through the Serial port.

     Circuit:
     * GSM shield attached to and Arduino
     * SIM card that can receive SMS messages

     created 25 Feb 2012
     by Javier Zorzano / TD

     This example is in the public domain.

     http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

    */

    // include the GSM library
    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER ""

    // initialize the library instances
    GSM gsmAccess;
    GSM_SMS sms;

    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

    void setup() {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("SMS Messages Receiver");

      // connection state
      boolean notConnected = true;

      // Start GSM connection
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY)
          notConnected = false;
        else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop() {
      char c;

      // If there are any SMSs available()
      if (sms.available()) {
        Serial.println("Message received from:");
        // Get remote number
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);
        // An example of message disposal
        // Any messages starting with # should be discarded
        if (sms.peek() == '#') {
          Serial.println("Discarded SMS");
          sms.flush();
        }

        // Read message bytes and print them
        while (c = sms.read())
          Serial.print(c);
        Serial.println("\nEND OF MESSAGE");

        // Delete message from modem memory
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }
      delay(1000);
    }

The issue is this line:

    if (gsmAccess.begin(PINNUMBER) == GSM_READY)

The serial monitor outputs everything until that line.

It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.

This seem to be the same question, yet no answer:
http://forum.arduino.cc/index.php?topic=270551.0

title: Arduino GSM shield GSM_READY not ready ever

Answers: 3

body:
You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement

What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."

body:
I Have The Same Problem.
But First Of All you have to set your modem Network Band according to your cellular Network Band.

    GSMBand band;
    String newBand= "GSM_MODE_EGSM_DCS";// Your Band In My case That was
      band.begin();
      Serial.println("Modem restarted.");
      String bandName = band.getBand(); // Get and print band name
      Serial.print("Current band:");
      Serial.println(bandName);

    band.setBand(newBand);

Band Help:

      GSM_MODE_EGSM                ---- E-GSM(900)
      GSM_MODE_DCS                 ---- DCS(1800)
      GSM_MODE_PCS                 ---- PCS(1900)
      GSM_MODE_EGSM_DCS            ---- E-GSM(900)+DCS(1800) ex: Europe
      GSM_MODE_GSM850_PCS          ---- GSM(850)+PCS(1900) Ex: USA, South Am.
      GSM_MODE_GSM850_EGSM_DCS_PCS ---- GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

Then You Have To use

    gsm.access.begin();

body: I had the same problem. Then I used `gsm.shutdown();` before `gsm.begin(PINNUMBER)`. After that it goes past `gsm.begin(PINNUMBER)` but not always. I don't know if this is the right way to do it, but it works for me.


body:
At first I am sorry for my bad English.

I am making robot which can do a lot of things...

If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?

Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

title: Arduino works bad when powered by 9V battery

Answers: 1

body:
I got a fresh 9 V out of a packet and measured it.

     9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:

     7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.

And that was with a fresh battery, testing for a few seconds.

Those 9 V batteries are just not designed to drive motors.

I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


body:
I'm successfully running a stepper from my Arduino via a ULN2003A and a secondary power supply. It uses the first four of the seven Darlington Pairs on the chip, leaving three spare.

A) Is there any reason I wouldn't be able to use one of the remaining pairs to drive a standard DC hobby motor? (For the sake of helping future visitors .. what about running three motors off the remaining three pairs?)

B) Do I need anything other than to connect the motor to the chip? (The chip's board has LEDs and resistors on each of pins 1 - 4, but I don't believe they're in series and thus my guess is they can be left off.)

C) The DC motor is on a PWM Pin. Is that the correct way to control its speed?

The image attached shows the setup in case I haven't been clear.

![enter image description here][1]

*(I could probably just build it and see, but I'm new to Arduino and still scared of the blue smoke if I get something wrong!)*

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

title: Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor?

Answers: 1

body:
Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.

Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.

PWM is the easiest way to (somewhat) control the speed of a DC motor.


body:
I had problems with Arduino uno and reseted firmware. Followed this [tutorial][1]. Now I can't upload my code Arduino IDE says:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

I tried loop-back mode, everything is fine.

Firmware was located in this location:

    /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

  [1]: http://bartruffle.blogspot.fr/2013/09/dfu-programming-atmega16u2-on-arduino.html

title: Not in sync: resp=0x00

Answers: 1

body:
There are two processors on the Uno board.

* The Atmega328P which is the "main" processor with your sketches on it
* The Atmega16U2 which handles the USB interface

> Firmware was located in /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

Hopefully you reflashed the **Atmega16U2** with that file. Did you?

>  I tried loop-back mode, everything is fine.

Therefore the Atmega16U2 is OK. The problem may be with the Atmega328P.

---

> I had problems with Arduino Uno and reseted firmware.

You shouldn't need to do this, I never reflash the firmware on my Atmega16U2.

What problems did you have? Did it involve motors? LEDs? High voltages? Sparks? Flames? Screaming?

Please see the steps described here, run through them, and see if that fixes the problem: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board


body:
I have a simple sketch running on a BE Leonardo-compatible board.

It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.

Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)

When the board is powered by USB, everything works.

When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.

If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.

Can anyone offer a possible explanation for (and solution to) this fault?

title: Arduino hangs after 3-4 minutes on battery power, but not on USB

Answers: 1

body:
As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.

Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.


body:
I am trying to write one code that takes data from serial
ie. `0x4E`, `0x20`, `0x--`, `0x0D`.

`0x--` may be any hex in `--`

The user will input these hex one by one and raspi will take all of them in buffer.
Whenever 1st, 2nd and 4th data is matched, the 3rd one will be printed in serial
ie.

    Serial.print(3rd); //Decimal value
    else Serial.print() // may be 00

I was trying with this code:

    byte buffer[4];
    int cnt = 0;

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Start");
    }

    void loop(void)
    {

     // read max 12 bytes
     if ((cnt <= 4) && Serial.available()) buffer[cnt++] = Serial.read();

     if (cnt == 4)  // all bytes read...
     {
       // assume the arrays are the same
       boolean same = true;

       // the ans array holds the right answer
       byte ans[]={0x4E,0x20,0x01,0x0D};

       for (int i=0; (i<= 4) && same; i++) same = (buffer[i] == ans[i]);

       if (same)
       {
         Serial.println("Yes");
       } else {
         Serial.println("Enter another number");
       }
       Serial.flush();
       cnt = 0;
     }
      //Serial.print("Done");
     // do something
    }

But I was not able to do it. Anyone have a suggestion?

**Edit: I have tried this state machine in Arduino :**
It accepts those data and according to it, it should bi color LED light. But not working properly. Not lighting up anything

    //int currState;
    //int reChk, data, confirm;
    const int pingPin = 13;
    int inPin = 12;

    void setup()
    {
      Serial.begin(9600);
        // initialize digital pin 13 as an output.
      pinMode(32, OUTPUT);
      pinMode(34, OUTPUT);

      digitalWrite(32, LOW);
      digitalWrite(34, LOW);
      //currState = 0;
      //reChk = 0;
      //confirm = -1;

    }

    void loop() // run over and over
    {
      static int currState = 0, reChk = 0, confirm = -1;
      int data;
      if(reChk == 0)
      {
        //ultrasonic();
        if(Serial.available())
        data = Serial.read();
        else
        currState = 5;
      }

      switch(currState)
      {

        case 0:
        reChk = 0;
        if(data == 78)
          currState = 1;
        else
          currState = 0;
        break;

        case 1:
        reChk = 0;
        if(data == 32)
        currState = 2;
        else
        {
          currState = 0;
          reChk = 1;
        }
        break;

        case 2:
        reChk = 0;
        switch(confirm)
        {
          case -1 :
          confirm = data;
          currState = 3;
          break;
          case 0 :
                digitalWrite(32, LOW);
                digitalWrite(34, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          case 1 :
                digitalWrite(34, HIGH);
                digitalWrite(32, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          case 2 :
                digitalWrite(32, HIGH);
                digitalWrite(34, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          default :
          confirm = -1;
          reChk = 1;
          currState = 0;
        }

        case 3:
        reChk = 0;
        if(data == 20)
        {
          reChk = 1;
          currState = 2;
        }
        else
        {
          confirm = -1;
          currState = 0;
        }
        break;

        default:
        reChk = 0;
        currState = 0;
        confirm = -1;
      }
      delay(10);
    }

    void ultrasonic () //ultrasonic
    {
          const int pingPin = 13;
          int inPin = 12;
          //raw duration in milliseconds, cm is the
          //converted amount into a distance
          long duration, cm;

          //initializing the pin states
          pinMode(pingPin, OUTPUT);
          //pinMode(greenLed, OUTPUT);
          //pinMode(redLed, OUTPUT);

          //sending the signal, starting with LOW for a clean signal
          digitalWrite(pingPin, LOW);
          delayMicroseconds(2);
          digitalWrite(pingPin, HIGH);
          delayMicroseconds(5);
          digitalWrite(pingPin, LOW);

          //setting up the input pin, and receiving the duration in
          //microseconds for the sound to bounce off the object infront
          pinMode(inPin, INPUT);
          duration = pulseIn(inPin, HIGH);

          // convert the time into a distance
          cm = microsecondsToCentimeters(duration);

          if(cm > 50)
          {
          //printing the current readings to ther serial display
          Serial.print("5");
          }
          else
          {
          Serial.print("0");
          }
          //Serial.print("cm");
          //Serial.println();

          //checking if anything is within the safezone, if not, keep
          //green LED on if safezone violated, activate red LED instead
          //if (cm > safeZone)
          //{
          //  digitalWrite(greenLed, HIGH);
          //  digitalWrite(redLed, LOW);
          //}
          //else
          //{
          //  digitalWrite(redLed, HIGH);
          //  digitalWrite(greenLed, LOW);
          //}

    delay(1000);
    }

    long microsecondsToCentimeters(long microseconds)
    {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
       return microseconds / 29 / 2;
    }

title: Arduino Serial buffer

Answers: 1

body:
It's unclear how the users input the hex numbers.

If i assume a simple serially attached terminal the user doesn't enter hex numbers but characters.

As an example when the user types `0`, `x`, `4`, `E` the user has only typed one hex number but already four bytes or characters. Instead the user has to type `N`, ` `, `whatever letter`, `Enter`. (Depending on the OS or terminal you will get "CR", "LF" or "CR+LF" when you press enter)

I'm not familiar with C, but your code seems to have also a coding flaw: The 3rd byte will be checked for equality too. You would need something like:

    boolean same = true;

    if (buffer[0] == ans[0]) { same = false }
    if (buffer[1] == ans[1]) { same = false }
    if (buffer[3] == ans[3]) { same = false }

Only three tests not four.


body:
I'm using an Atmega168 in a project that involve using the ISRs from multiple sources. I have an ISR hooked up to an external button and a timer, to use it as a reset button after a predetermined hold time.

I'm also using an ISR hooked upto UART. The UART is connected to an external Linux based SoC. Upon receiving specific commands from the linux machine, the atmel will perform certain functions.

In very rare occasions, the linux hangs up during tranmission and is always sending out the UART commands. This saturates the ISR and it also prevents the reset button ISR to function.

Although this happens rarely, I would like to take measures for this. As far as I know, there are no way to set priority in avr ISRs. So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

EDIT:
I think the problem arises when the linux machine sends an empty string to the atmel.
the UART_receive() on the atmel gets stuck at: `while ( !(UCSR0A & (1<<RXC0)) );`

Any way I can avoid this?

    unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
    {
 unsigned char i = 0;

 if (size == 0) return 0;            // return 0 if no space

 while (i < size - 1) {              // check space is available (including additional null char at end)
  unsigned char c;
  while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
  c = UDR0;
  if (c == '\0') break;           // break on NULL character
  x[i] = c;                       // write into the supplied buffer
  i++;
 }
 x[i] = 0;                           // ensure string is null terminated

 return i + 1;                       // return number of characters written
    }

title: Atmega168 interrupt error handling

Answers: 2

body:
> Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.

Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

> So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".

body:
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received

The comment hits the nail on the head.

It'll wait forever, but it's so because it has been "designed" in such a way.

You've got 2 options:

 - Re-think your "design":

Do not make your UART wait for an n-amount of characters. You could buffer the received characters, and handle/clear the buffer. There should be a lot of info about this on the web.

 - Quick and dirty fix:

Add a timeout to the waiting.

    for (unsigned int timeout = 16000; (!(UCSR0A & (1<<RXC0))) && timeout > 0; timeout-- );

This isn't very efficient, but should work.
Be sure to check for what reason the waiting stopped (if the timeout ran out, or if you actually received something), to avoid pushing in nonesense that's in the UDR0 at that moment (when you timeout).


body:
I've been working on a project where I want to transmit data from one arduino to another using an Xbee network and then parse it to update some PWM outputs accordingly (Building a system which controls some LED lamps).

The thing is I wanted to debug the receiver using a number of Serial.print() but it appears a lot of them are "ignored" by the Serial Monitor. For instance, if you take a look at the image below you will notice there is a "Zone:" that should be displayed somewhere on screen. It isn't. I also got a Serial.print("Coucou") in the loop() that is never displayed.

Has anyone ever encountered a bug of this kind ?

![Strange Bug][1]

As asked, the code that is producing the output

    #include <EEPROM.h>
    #include <Dispositif.h> // Custom class i wrote.

    // how much serial data we expect before a newline
    const uint8_t MAX_INPUT = 196;

    //zone = 1, id = 1, idNode = 2
    Dispositif dispositif;

    void setup ()
    {
      Serial.begin(9600);
      //delay(1000);
      Serial.println("Cool");
    } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data, unsigned int input_pos)
    {
      uint8_t value = 0;
      uint8_t i = 1;
      uint8_t currentZone;
      char c;

      if(data[0] != '<')
      {
        i = peekNextP(data);
      }
      while (data[i] != '>' && i < input_pos - 3)
      {
        // zone
        value = 0;
        i = peekNextDigit(data, i);
        do{
          c = data[i];
          i++;
          if(c >= '0' && c <= '9')        // is c a digit?
            value = value * 10 + c - '0';
        } while(c >= '0' && c <= '9');
        currentZone = value;
        Serial.print(currentZone);
        Serial.print(F("("));

        // 1st order
        value = 0;
        i = peekNextDigit(data, i);
        do{
          c = data[i];
          i++;
          if(c >= '0' && c <= '9')        // is c a digit?
            value = value * 10 + c - '0';
        } while(c >= '0' && c <= '9');
        Serial.print(value);
        Serial.print(F(","));

        if (currentZone == dispositif.zone) {
          dispositif.setBrightness(0, value);
        }
        // 2nd order
        value = 0;
        i = peekNextDigit(data, i);
        do{
          c = data[i];
          ++i;
          if(c >= '0' && c <= '9')        // is c a digit?
            value = value * 10 + c - '0';
        } while(c >= '0' && c <= '9');
        Serial.print(value);
        Serial.print(F(","));

        Serial.print(F("Zone:"));
        Serial.print(dispositif.zone);
        if (currentZone == dispositif.zone)
          dispositif.setBrightness(1, value);

        // 3nd order
        value = 0;
        i = peekNextDigit(data, i);
        do{
          c = data[i];
          ++i;
          if(c >= '0' && c <= '9')        // is c a digit?
            value = value * 10 + c - '0';
        } while(c >= '0' && c <= '9');
        Serial.print(value);
        Serial.println(F(")"));

        if (currentZone == dispositif.zone)
          dispositif.setBrightness(2, value);
      }

    }  // end of process_data

    uint8_t peekNextDigit(const char* data, uint8_t i)
    {
      int c;
      while (1) {
        c = data[i];
        if (c >= '0' && c <= '9') return i;
        ++i;
      }
    }

    uint8_t peekNextP(const char* data)
    {
      uint8_t c;
      uint8_t i = 0;
      while (1) {
        c = data[i];
        ++i;
        if (c == ')') return i;
      }
    }

    void processIncomingByte (const byte inByte)
    {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
      {
        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line, input_pos);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

      }  // end of switch

    } // end of processIncomingByte

    void loop()
    {

      Serial.println("Coucou");
      // if serial data available, process it
      if (Serial.available () > 0)
        processIncomingByte (Serial.read ());

    }  // end of loop

The Serial output is :

    <o>1(255,255,255)<o>
    <o>1(0,0,0)<o>
    <o>1(255,255,255)<o>

What I am aiming for :

    Cool
    Coucou
    <o>1(255,255,Zone:1255)<o>
    Coucou
    <o>1(0,0,Zone:10)<o>

My library :

    #include <Dispositif.h>
    #include <EEPROM.h>

    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    #define pin1 5
    #define pin2 6
    #define pin3 9

    Dispositif::Dispositif()
    {
      pinMode(pin1, OUTPUT); // absolutely necessary because we use a custom PWM
      pinMode(pin2, OUTPUT);
      pinMode(pin3, OUTPUT);

      setBrightness(0, 50);
      setBrightness(1, 50);
      setBrightness(2, 50);

      last_value[0] = 50;
      last_value[1] = 50;
      last_value[2] = 50;

      zone = EEPROM.read(0);
      id = EEPROM.read(1);
      idNode = EEPROM.read(2);
    }

    Dispositif::Dispositif(uint8_t zone, uint8_t id, uint8_t idNode)
    {
      zone = zone;
      id = id;
      idNode = idNode;

      pinMode(pin1, OUTPUT);
      pinMode(pin2, OUTPUT);
      pinMode(pin3, OUTPUT);

      setBrightness(0, 50);
      setBrightness(1, 50);
      setBrightness(2, 50);

      last_value[0] = 50;
      last_value[1] = 50;
      last_value[2] = 50;

      EEPROM.write(0, zone);
      EEPROM.write(1, id);
      EEPROM.write(2, idNode);
    }

    void Dispositif::setBrightness(uint8_t number, uint8_t value)
    {
        if (!Serial)
          Serial.begin(9600);
        unsigned long currentMillis = millis();
        unsigned long lastMillis = 0;

        while(value - last_value[number] > 25)
        {
          currentMillis = millis();
          if (currentMillis - lastMillis > 1000)
          {
            Serial.println("At least i'm here");
            Serial.println(last_value[number]);
            last_value[number] += 25;
            setPWM(number, last_value[number]);
            lastMillis = currentMillis;
          }
        }
        setPWM(number, value);
        last_value[number] = value;
    }

    void Dispositif::setPWM(uint8_t number, uint8_t val)
    {
        if (1 == number) // pin 6
        {
          sbi(TCCR0A, COM0A1);
          OCR0A = val; // set pwm duty
        }
        else if (2 == number) // pin 9
        {
          sbi(TCCR1A, COM1A1);
          OCR1A = val; // set pwm duty
        }
        else // pin 5
        {
          sbi(TCCR0A, COM0B1);
          OCR0B = val; // set pwm duty
        }
    }

    void Dispositif::changeZone(uint8_t newZone)
    {
      zone = newZone;
    }

The code is not really pretty, because at one point I was using the SD library and had to reduce program space.

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

title: Serial.prints ignored

Answers: 0


body:
I'm totally new to Arduino, and microcontrollers for that matter, so I'm having a hard time figuring out how to connect LEDs to multiple pins, but using a common external power supply...

I've created a starting light that's connected to pin A0-A4 + A5 (turn all LEDs on). I hooked each LED to its own pin directly (A0-A4) for the countdown part ("5, 4, 3, 2, 1, ..."), and then 5 additional LEDs to pin A5 ("GO!").

For the countdown part, when only one LED is on at a time, there's enough power. But if I were to light them all up at the same time, there won't be. So I figured that I should put a relay into the mix for that part, and have them draw power from an external 12 V power supply.

I did manage to make the relay work in the circuit - switching all LEDs on/off, and getting power from the external power supply, but only through one pin.

I'm not sure how to have the start lights use an external power supply, and at the same time get signals from multiple pins. How do I do that?

I'm sorry if my description is unclear. So please let me know if you need more information.

 - The LEDs are 3.4 V 20 mA.
 - The power supply I'm planning to use is 12 V.

I'm planning to have this start light - which is built in its own casing - use its own power supply, while the Arduino is running of the power from USB. So all I want to do, is to have the signals sent over to this starting light unit, and not power and ground.

UPDATE:

Here's a quick overview of how I'm testing this whole thing at the moment:

![Friting diagram of Arduino and LEDs][1]

The 5 red countdown LEDs (red) is getting powered by the board itself through the pins, while the 5 "GO!" LEDs (green) are getting powered from a 12 V power supply since they're all are going to be turned on simultaneously.

My question is how I can get both the 5 red LEDs, that uses separate pins, to get powered from the external power supply as well?

Since all the LEDs are built in its own casing, apart from the microcontroller because that also handles other stuff...

Did that make any more sense at all?

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

title: Using external power supply to power leds on multiple pins (A0-A5)

Answers: 3

body:
**Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.**

Current in your Arduino:

* A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
* The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.

Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

* This question was [answered nicely over at the electronics stack exchange][1].
* Here's a [PDF tutorial on using transistors as switches][2].
* Found a nice [reference on figuring out the transistor / resistor relationship][3].

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.

![Power five LEDs from one digital pin][4]

  [1]: https://electronics.stackexchange.com/questions/65996/turning-on-multiple-leds-with-arduino-using-transistor
  [2]: https://www.techhouse.org/~dmorris/projects/tutorials/transistor.switches.pdf
  [3]: http://www.sqlskills.com/blogs/paulselec/post/arduino-figuring-out-transistors-and-associated-resistors.aspx
  [4]: https://i.stack.imgur.com/NAsTa.png

body:
I think one of the best way for you would be to use 74HC595 chip. You will learn a lot while developing board with this chip. It is well documented [Serial to Parallel Shifting-Out with a 74HC595][1]. Using 3 pins you will be able to turn on & off as many LED's as you wish, use external power supply and so on.

Also there is MAX7219 chip. [The MAX7219 and MAX7221 Led drivers][2]. And there are a lot more ways to do this.

  [1]: http://arduino.cc/en/tutorial/ShiftOut
  [2]: http://playground.arduino.cc/Main/MAX72XXHardware

body: If you really want an external power supply, you can use ULN2003 / ULN2803, which are 7/8 darlington 500 mA each transistor


body:
I just began following the projects in the Arduino Projects Book included in the Arduino Starter Kit.

While using LEDs, as in the first few examples of the book, I am having a difficult time keeping them in contact with the breadboard. I can usually move the LED around until it turns on, but even a push of a button can make it lose contact with the board. I haven't used much more than switches, jumpers, LEDs and resistors, so I don't know if any of the other components behave the same. For the more complex projects, it seems like it would be hard to tell if you have it setup properly if you can't be sure the components are making a connection with the breadboard.

Is there a particular way to get all the components to sit nicely in the breadboard, or to modify them to do so?

title: How to ensure electronic components make good connection with breadboard

Answers: 1

body: Sounds like you may not be pushing the leads into the board,I find long nose pliers handy for components with thicker leads.


body:
I'm using an 3 axis Accelerometer(GY-521) to get the acceleration data and also the gyroscope to get the gyro data. I want to segment the signals at the idle points so that i can get the segmented signal at the idle points.

![enter image description here][1]

Is there any algorithm or example code that i could use to segment this kind of signal?

Any help would be appreciated.

Thank You.

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

title: How to Segment Accelerometer Signal at idle points

Answers: 1

body:
There are many algorithms you can use. I would advise you to look carefully at the data and the "idle state" and see what is always different. Try everything you can think of and see what works best, or if one does everything you need just stop there.

It might be that you can just calculate if the accelerometer values go over a certain threshold, but that requires that either the orientation be know or the threshold being over 1g.

You could also calculate the rate at which the accerometer value is changing by subtracting the last value (the derivative if you are up on your calculus) and threshold that value, which might produce better results.

You could also calculate a running average and then compare the current value with that. If the numbers match (or are very close) then you can say the accelerometer has been idle. This has the effect of making a changing threshold relative to the most recent activity tuned by the average's response.

I doubt any of these will be perfect, so you might require the algorithm to say "idle" multiple times in a row before changing state from "active" to "idle", or something to that effect.


body:
I am trying to learn how to make a shift register work. I have been working off of the [Arduino ShiftOut tutorial](http://arduino.cc/en/tutorial/ShiftOut).

My issue is that the shift register isn't working when the circuit is powered and I am not sure what is wrong. I suspect the issue is with pins 10-13 on the 74HC595?

I have done this with an actual board and the 123d.circuits.io simulator with the same result:

http://123d.circuits.io/circuits/444111-shift-register

![enter image description here][1]

The code is very simple and taken from [the tutorial](http://arduino.cc/en/Tutorial/ShftOut12):

    // SH_CP; 11
    const int clockPin = 9;
    // DS; 15
    const int dataPin = 8;
    // ST_CP; 12
    const int latchPin = 10;

    void setup() {
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      Serial.begin(9600);
      Serial.println("reset");
    }

    void loop() {
      for (int number = 0; number < 256; number++) {
        Serial.println(number);
        digitalWrite(latchPin, LOW);
       shiftOut(dataPin, clockPin, MSBFIRST, number);
       digitalWrite(latchPin, HIGH);
       delay(500);
      }
    }

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

title: Shift Register 74HC595 not working

Answers: 1

body:
Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.

Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.

What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:

![enter image description here][1]

  [1]: https://i.stack.imgur.com/JYzEK.gif


body: I don't know what wires to get for my first Arduino project. I am planning on getting a pre-made light strip that I would control with an Arduino from across my room. Is there any specific type of wire to get? It needs to be about 15 feet. There are so many choices, but I don't know what I need. Does anyone else know?

title: Arduino Wire Types?

Answers: 1

body:
Choosing wire all depends on what you're going to do with it, and most of the choice is based on how much current it will carry and how durable it needs to be. Generally, you're going to use insulated copper wire - aside from that, your answers are mostly here: https://electronics.stackexchange.com/questions/16948/choosing-the-right-type-of-wire

For experimentation - which you will need to do a lot of before attempting your goal project - you can use the little wires which come in the Arduino starter kit. They are "jumper wires" designed for use on a bread board - they can not carry large amounts of electricity.

This product here: https://www.sparkfun.com/products/8431 - these have "male" ends designed to be stuck into the holes in the breadboard, and connect to the holes on the headers of the Arduino.

Here's an example of a project laid out on a breadboard:
![Compass Project][1]

None of those wires carry a lot of current. If you're hooking up 50 LEDs that might be almost a full 1-AMP of current, so I would use thicker wire. Do yourself a favor and start with a kit like in this video, learn the basics, then attempt a 'real' project. Every Arduino user should be able to do all the experiments in the training book and understand them. You will be lost if you jump in deep right away...

https://www.youtube.com/watch?v=pf4qosqpv3A

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


body: Is it possible to create a infrared based interruption counter with an Arduino Uno? If yes, then what additional hardware would be necessary?

title: Infrared interruption counter

Answers: 1

body:
You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter.
Don't forget serial resistor to limit current.

Search e.g. "photo interrupter Schmitt" at Farnell.


body:
I'm working on a small project for a presentation. My goal is to read the UID of multiple Mifare Classic cards and compare it to a hardcoded list for different actions. All is well (the reading and comparing part that is) but 2 small problems that I have encountered are:

- The first (maybe up to three, since the reader is a little bit on the fast side) read after uploading my code will return a UID of just 0s and a wrong PICC type.

- After reading a PICC and then trying to read another, the reader prints the UID / PICC Type of the reader before, which is kinda not helpful when trying to light LEDs based on UID.

Here is my sketch:

    /*
    HEADER TEXT
    GOES HERE
    */
    #include <SPI.h>
    #include <MFRC522.h>
    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN);

    void setup()
    {
      // Serielles Interface initialisieren
      Serial.begin(9600);
      // SPI initialisieren
      SPI.begin();

      mfrc522.PCD_Init();

      // Für später
      // pinMode (2, OUTPUT);
    }

    void loop()
    {
      // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
      String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

      // PICC Typen
      byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

      // Nach neuen Karten suchen.
      delay(250);
      if ( mfrc522.PICC_IsNewCardPresent())
      {
        delay(250);
        mfrc522.PICC_ReadCardSerial();

        // Debug Ausgabe
        Serial.println();
        Serial.print("Die Kartennummer lautet: ");
        Serial.print(uID);
        Serial.println();
        Serial.print("Picc Type: ");
        Serial.println(mfrc522.PICC_GetTypeName(piccType));
        Serial.println();

        // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
        if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
          Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
          return;
        }

        // Den UID String Verglichen und eine entsprechende Aktion ausführen
        if(uID=="myUIDforStuff") {
          Serial.println("Access granted");
        }
      }
    }

title: MFRC522 minor problems

Answers: 1

body:
    /*
    HEADER TEXT
    GOES HERE
    */
    #include <SPI.h>
    #include <MFRC522.h>
    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN);

    void setup()
    {
      // Serielles Interface initialisieren
      Serial.begin(9600);
      // SPI initialisieren
      SPI.begin();

      mfrc522.PCD_Init();

      // Für später
      // pinMode (2, OUTPUT);
    }

    void loop()
    {
      // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
    // String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

      // PICC Typen
    // byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

      // Nach neuen Karten suchen.
      delay(250);
      if ( mfrc522.PICC_IsNewCardPresent())
      {
        delay(250);
        mfrc522.PICC_ReadCardSerial();
         // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
     String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

      // PICC Typen
     byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

        // Debug Ausgabe
        Serial.println();
        Serial.print("Die Kartennummer lautet: ");
        Serial.print(uID);
        Serial.println();
        Serial.print("Picc Type: ");
        Serial.println(mfrc522.PICC_GetTypeName(piccType));
        Serial.println();

        // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
        if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
          Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
          return;
        }

        // Den UID String Verglichen und eine entsprechende Aktion ausführen
        if(uID=="myUIDforStuff") {
          Serial.println("Access granted");
        }
      }
    }


body:
I have just got the [Blend Micro][1] board.
After following the [getting started tutorial][2] I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices

- Blend
- Blend Micro 3.3V/8Mhz
- Blend Micro 3.3V/16Mhz (Overclock) as in this picture:

![enter image description here][3]

While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.

But if I open the Android BLE application BLE Controller, after tried to upload the __BLEControllerSketch__ (from RBL_nRF8001 libraries) it finds the board but print the error __No Response from the BLE Controller sketch__. If I try with __SimpleChat__ example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.

Any kind of advice?

EDIT

I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the `/dev/tty.usb*` in the listed ports

  [1]: http://redbearlab.com/blendmicro/
  [2]: http://redbearlab.com/getting-started-blendmicro
  [3]: https://i.stack.imgur.com/pzKcF.png

title: Blend Micro uploading sketch

Answers: 2

body:
Did you follow the setup exactly? In particular, did you modify `main.cpp` to have this:

    #if defined(BLEND_MICRO_8MHZ)
        // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
        // But the external xtal is 16000000Hz, so correct it here.
        PLLCSR |= 0x10;             // Need 16 MHz xtal
        while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
    #elif defined(BLEND_MICRO_16MHZ)
        // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
        CLKPR = 0x80;
        CLKPR = 0;
    #endif

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see `/dev/tty.Bluetooth-Serial-1` in the port list.

1. Modify `main.cpp` according to http://redbearlab.com/getting-started-blendmicro

2. Press the reset button on the Blend Micro, then quickly select *Tools* -> *Serial Port* in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like `/dev/tty.usb????????`

3. Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

**Update: The Timing Tricks**

Note: Blend Micro is basically the same as Arduino Leonardo.

This is the timing:

1. The reset button is pressed.

2. The ATMega32u4 restarts. It jumps to the bootstrap loader code.

3. The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)

4. If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.

5. The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.

body: For anyone else who is having an issue with this. What worked for me, was replacing the cable with a shorter cable. I could of been using a charging only usb cable or the cable was long enough to not upload correctly.


body:
Actually I'm using the RF24 Library mantained by TMRh20 (https://github.com/TMRh20/RF24).
I'm trying to get some type of direct communication between multiple modules working, but I don't want to use the RF24Network Library (https://github.com/TMRh20/RF24Network) which creates a mesh of connections.

I currently have several arduinos that have to communicate between them. Every arduino has its own address starting from 0x0001 (0x0000 is for a main module that manages everything) and finishing to 0xFFFF.
I want to directly communicate between the two NRF24L01+ modules without any intermediator, because I don't have problems of distance.

The main thing that I want to be able to do is communicate directly not with just one module, but choose if I want to broadcast to all the modules in an area (I know that it can be done with range power modifications in the code) or talk with just one module.

What is the best way to do this type of communication?

title: NRF24L01 Direct Communication Library Logics

Answers: 3

body:
If you set pipe 1 to a common address (let's call it the broadcast address) anytime you send a packet to that address all the modules will receive it on that pipe!
It's as simple as that, but you will not be able to use auto-ack (you will receive multiple acks, one per each receiver) and you can't also use ack payloads.

I wrote a series of [blog posts][1] on this modules and I'm going to keep writing on the topic.

  [1]: https://rlogiacco.wordpress.com/2015/09/21/nrf24-walk-through-introduction/

body:
Both of the Libraries you mentioned are well written. I've used both, but decided to write my own based those libraries. For me, the network libraries were written for their project and didn't really fit my needs. So I decided to write my own. I combed the internet for a bare bones NRF24 Library and found this [one][1]. This was my starting point. It didn't need the Arduino Core Library and handled all the SPI functions. Then I read the NRF24L01 datasheet several times, then read it again.

With that said, you can broadcast up to 6 radios at a time. Per the datasheet, the receiver knows which radio sent the packet. The STATUS register (0x07), should tell you who sent the packet:

[![STATUS Register 0x07][2]][2]

I was unable to get this working (I am still working on it), so for now, I send my packet as a struct:

    typedef struct  {

 uint8_t id;
 uint32_t data;

    }
    Packet;

    Packet pck;
    pck.id = 2; // id of my second radio

Keep in mind when you program your Arduino as the receiver, you have to tell it who it will be receiving from. The transmitter and receiver have to be on the same RF channel, speed and same pipe. To choose who receives the packet may not work the way you think, but as I mentioned you can program the receiver to know who the transmitter was and code around it.

I would suggest you dig into the datasheet.

  [1]: https://github.com/kehribar/nrf24L01_plus
  [2]: https://i.stack.imgur.com/ZwL67.png

body:
You need to dig into the [datasheet][1] and read about ESB (Enhanced ShockBurst).  This is technology that is integrated into the radios and allows for broadcasting and direct pipes.  One of the limitations is that the mesh only works for up to 6 pipes, so be aware that this limits the number of devices that will be able to hear your transmission.

Another option is to have all the nodes listening on the same pipe, and then when node x wants to talk, he stops listening on pipe 1234 and starts writing to it.  You would put some sort of addressing header in the payload section of the packet, then when all of the nodes receive that packet, they can check that address and see whether or not to process it.  This might work well in your situation.

For example, if you have a packet that is sent on the communal pipe with a payload of [broadcast address,data] then your receiving nodes (those within "earshot") can receive the packet, see that it is a broadcast, then process the data.  If you want to send to a single node, create a packet that has a payload of [destination node id,data].  When each node receives that packet on the communal pipe, they will check the destination, and when it doesn't match either their own address or the broadcast address, then they dump it.  Only the intended receiver will actually process the data.

  [1]: https://www.sparkfun.com/datasheets/Wireless/Nordic/nRF24L01P_Product_Specification_1_0.pdf


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

I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.

The basic code example:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);
    void setup() {
      mySerial.begin(4800);
    }
    void loop() {
        mySerial.println("HELLO");
        delay(100);
    }

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.

title: Arduino SoftwareSerial library basic example doesn't work

Answers: 2

body:
If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call `Serial.begin(..)` and `Serial.println(..)`, instead of `mySerial...`.

`SoftwareSerial` is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.

body:
Addition to `Peter R. Blommfield`

What is your problem?

Connect your device, run this sketch and you are good to go :)

    /* TEST */
    #include <SoftwareSerial.h>

    /* Connect device Rx - 10, Tx - 11 */
    SoftwareSerial mySerial(10, 11);

    void setup() {
      Serial.begin(9600);   // This will communicate with PC via USB
      mySerial.begin(4800); // This will communicate with device via 10,11 pins with 4800 baud rate
    }
    void loop() {
        Serial.println("HELLO");   // Sends string to PC to Serial Monitor
        mySerial.println("HELLO"); // Sends string to device
        delay(100);                // Waits here 100ms and then goes on
    }


body:
I have been following http://arduino.cc/en/Tutorial/Fade to fade and LED. But I don't know why they are using a 220 Ohm resistor.
According to Ohms law if LED is of 2.2 V and it runs on 0.025Amps and is connected to 5V pin of Arduino then the resistor should be of 120 Ohms but why we are using 120 Ohm resistor ?
One more thing. How can I collect value of resistor to be used with different output and input devices ?

Thanks in advance

title: how to calculate correct resistor value to use with LEDs Potentiometer and other devices?

Answers: 1

body:
If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)

It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.

Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:

 * http://led.linear1.org/led.wiz

For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.


body:
I bought the [standard 1.77" TFT screen][1] months ago and It has never worked. I follow the wiring diagram shown for Uno on [the guide on the Arduino website][2] and the best result I have ever got is it seeming like the screen itself is broken. I must have rewired the whole thing many times now and quadruple checked each time.
As I have never used this screen before I do not know what is correct any further than the tutorial.

![enter image description here][3]

I say that because it seems to understand instructions but does not display them correctly.

I have tried multiple examples and tests on it that all yield weird results.

The tests I have tried are:

 - The SD demo that loads the Arduino icon off SD and fills the screen
   with it. The serial connection says that it has successfully read the
   image but just displays black lines
 - Setting the background colour with random colours which seems to work fine apart from the black bars
 - Drawing random colour, positioned and sized rectangles. Result is image below. Colours seems to prefer pink, purple and white.

![Random rectangles test][4]

As you can see it looks like the image is 1D, no rectangles stop across the x axis so I did a test for that, it just draws a 1x1 pixel red dot going down the screen's left side, if it drew a red line moving down then my thought that it was stretching the first column would be correct, it didn't, just white and black bars still, so I modified it to test every column in case it wasn't column 0, same result...weirdly only when I made the 1x1px rectangle 5x5 my idea was correct.

![Another completely different test looks the same> Black lines not changed][5]

As you can see on both the images, the black bars are a persistent factor, their colour cannot be changed and they appear once TFT.begin has been called.

After looking around the only help I could find is someone mentioned that Arduino the company updated the TFT library but not the software but he/she didn't provide a download link. In the time I've had this I'm sure I'm redownloaded/updated the Arduino software a few times too.

Are the glitches normal for wrong pin connections? Is there some pin wrong on the website?

  [1]: http://arduino.cc/en/Main/GTFT
  [2]: http://arduino.cc/en/Guide/TFTtoBoards
  [3]: https://i.stack.imgur.com/2e2p3.jpg
  [4]: https://i.stack.imgur.com/6VZkD.jpg
  [5]: https://i.stack.imgur.com/ux51n.jpg

title: Is my TFT screen defective?

Answers: 1

body:
I ran into the same problem, looked around the net a bit.
Someone found a solution from the Italian forums translated + posted how to help this.

In short there was something wrong with the TFT library
https://forums.adafruit.com/viewtopic.php?f=25&t=45289#p228908

I installed the nightly build, currently 1.6.0 and the screen is working now.


body:
I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.

However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.

**My question is**: How do I burn such a bootloader (such as [micronucleus][1] for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like [this?][2])? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.

Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.

EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use: ![enter image description here][3]

  [1]: https://github.com/micronucleus/micronucleus
  [2]: http://littlewire.cc/downloads.html
  [3]: https://i.stack.imgur.com/5U8Nr.jpg

title: ATtiny85. How do I burn a bootloader? What is the process?

Answers: 4

body:
True, if you use the reset pin as IO then you need <strike>a special programmer that I believe provide high voltage (12v if i remember) or something like that</strike> to apply a 12v source to that pin to force it into programming mode then program using a normal programmer (or another arduino). However, what you are looking for is something like what is being done in the Arduino. The arduino is programmed with a special bootloader through ISP so when you power the microcontroller that bootloader will execute first and for few milliseconds will check the UART pins for activities and if it sees something valid it switched into programming mode where it waits for the new code to come through UART (not ISP) and write that into the program location, otherwise the bootloader will simply hand the code execution to the existing program if any.

**Here is a simple explanation of how it works:**
Let say your microcontroller flash size is 1KB, and the bootloader is 100B so your program can be stored at location 101B+, and its max size is (1KB-100B).
So when the bootloader starts and there is no activitiy on the UART pins it jumps to the location of your program (at 101B) while if programming activity is detected it starts reading the new code and overwrites the flash starting at 101B (so it won't over write itself).

And you will need the USBASP to program the bootloader for the first time. And you don't program the ATtiny85 through usb since that chip doesn't support USB, however, you use a USB to serial chip/module that emulates serial protocol over the USB. Some atmel microcontrollers have built in serial support and others can be done through software emulation.

* And as Chris suggested, don't disable the reset pin until you test and validate that your bootloader works.

body:
 - Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. [Digispark](http://digistump.com).
 - An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
 - I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
 - HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try [ScratchMonkey](http://microtherion.github.io/ScratchMonkey/index.html), which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.

body:
I have just finished my Arduino-Plugin with full integration of TinySafeBoot (TSB) for ATtiny84A, ATtiny85 and ATmega328P.

The project can be found here:
https://mesom.de/atflash/index_english.html
https://mesom.de/atflash/tinysafeboot/index_english.html

You could use it as it is now, and then use the Reset Pin as an analog in. Only watch for the voltage never to go below `0.6 * VCC`.

As an alternative you could modify the fuses in `boards.txt` to have this pin available:
Go to Arduino Preferences and click on the link to `preferences.txt` (Mine: `/Users/stefan/Library/Arduino15/preferences.txt`). In this folder navigate to `/packages/atflash/hardware/avr/0.1.0`. Open the `boards.txt` and go to the section
`ATTSB85.name=ATtiny85 (TSB)(Int. 8 MHz)`

Change the line
`ATTSB85.bootloader.high_fuses=0xdf`
to
`ATTSB85.bootloader.high_fuses=0x5f`

Restart Arduino and burn bootloader via Arduino menu.

---------------------------

If you even then want to get another Pin from ATtiny85: you can change the bootloader to use just one Pin for RX and TX (see the TSB website). But why all the effort? Simply take the ATtiny84A. It has 14 Pins instead of 8 and costs nearly the same.

Stefan

body:
> I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

it is infinitely better than your arduinoisp.

google avrdude / avrdudess.


body:
Currently I'm working on a project using an [ATmega 2560 microcontroller card][1] with a 10 MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.

Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)

I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up [the proper bits to change][2] and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.

I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).

I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.

    BODLEVEL = DISABLED
    OCDEN = [ ]
    JTAGEN = [X]
    SPIEN = [X]
    WDTON = [ ]
    EESAVE = [ ]
    BOOTSZ = 4096W_1F000
    BOOTRST = [X]
    CKDIV8 = [ ]
    CKOUT = [ ]
    SUT_CKSEL = INTRCOSC_6CK_0MS
    EXTENDED = 0xFF (valid)
    HIGH = 0x98 (valid)
    LOW = 0xC2 (valid)
    LB = NO_LOCK
    BLB0 = NO_LOCK
    BLB1 = NO_LOCK

    LOCKBIT = 0xFF (valid)

    Detected device
    Device name       ATmega2560
    Device signature  0x1E9801

  [1]: http://www.tme.eu/en/details/mikroe-229/atmel-development-kits/mikroelektronika/mcu-card-atmega2560/#
  [2]: http://www.avr-developers.com/bootloaderdocs/index.html

title: How do I change fuse bits - not communicating?

Answers: 1

body: If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.


body: Tried to upload my Arduino Uno sketch that writes to serial UART at 9600 baud rate onto my ATtiny2313 running at 1MHz. Not getting the signal on the ATtiny, does this have to do with my clock frequency of the MCUs being 16 vs 1MHz?

title: Does porting code to different MCU clock frequency affect serial baud rate?

Answers: 1

body: Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both *fosc* (aka `FCPU`) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.


body:
Today I ordered a 2x16 character LCD with white characters on black background.

Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.

Did anyone do this before?
Is it even possible that way?

I've seen RGB negative LCDs from Adafruit and Sparkfun.

title: Change the backlight of 2x16 LCD

Answers: 2

body:
The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.

When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.

body:
The backlight led ([sample](http://www.adafruit.com/product/1622)) is just a simple led with a large transparent panel, the size of the lcd, attached to it. This panel is diffused on the top in such a way that it distributes the light evenly. If you get a rgb led, file the top flat, and glue it to the side of this panel (where the leads get out of the plastic) you should get a pretty good effect.

I tested it on my white-on-blue lcd, by holding and led to the side of this panel, and it worked. Just note that you need a very bright led. Mine was pretty bright but the letters didn't light up that much.


body:
I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini).
As far as I can see it requires FTDI or similar circuit to program it.

Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?

Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)

Thanks in advance
Petar

title: How to connect Arduino Pro Mini with PC?

Answers: 2

body:
V-USB can be used to create a low-speed USB device in software, but you will need to program the chip before you can use it. It also has a number of caveats that must be adhered to regarding electrical and software specifications, so it not the best choice for an absolute beginner.

A USB-UART bridge (not necessarily a FTDI chip, although that is (was?) the most popular solution) will allow you to program and communicate with the chip over its serial port, but any AVR ISP programmer can also be used to program it without requiring a preexisting bootloader in place.

body:
The "Arduino Pro Micro" has its own USB interface so you don't need extra stuff for it to work. However, a number of existing libraries that deals with Arduino shields do not support the new chip inside the Arduino Pro Micro (ATmega32U4) so check first to make sure it will work with what you need.

For the "Arduino Pro Mini" (which I use a lot since it is very very cheap, about $3 from ebay) to program it I use "USPASP" (also cheap ~$3) so I have three of them but you only need one to program as many Pro Minis as you like. And for communication I use a "USB to TTL UART" (based on the "CP2102" chip which works with Linux, Windows and Mac) they are also super cheap (about $2) and you connect it to the serial pins on your Pro Mini.

(Just search ebay for the terms I put in quotes and you will find many of them at low prices, they ship from china so it will take about a month to get to you which is why I ordered more than I need for future projects, or for a little extra you might find local sellers with same products)


body:
I'm doing a program who get a line from the SD and shows it, this function is called *getData()*

FULL CODE:

    #include <SD.h>
    #include <MemoryFree.h>

    File myFile;
    int stringIndex = 0;
    int cursorPosition = 0;
    char inputString [25];
    char inputChar;
    boolean endOfLine;
    char fullPath[11];

    void setup(){

      Serial.begin(9600);

      Serial.print("Initializing SD card.");
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

    }

    void loop(){

      Serial.println(getDataSD());

      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    }

    String getDataSD(){

      memset(inputString, 0, sizeof(inputString));

      getFileNameSD();

      myFile = SD.open(fullPath);

      if(myFile){
        myFile.seek(cursorPosition);

        endOfLine = false;

        while(myFile.available() && endOfLine == false){
          inputChar = myFile.read();

          if(inputChar == '*'){
            while(inputChar != '\n'){
              inputChar = myFile.read();
            }
          }else{
            cursorPosition = myFile.position()-1;

            if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

            while(inputChar != '\n'){
              if(stringIndex < 25){
                inputString[stringIndex] = inputChar;
                stringIndex++;
                inputChar = myFile.read();
              }
            }
            inputString[stringIndex-1] = '\0';
            stringIndex    = 0;
            endOfLine      = true;
          }
        }
        myFile.close();
      }
      return inputString;
    }

    void getFileNameSD (){

      char folder[] = "/ACC";

      checkFolderSD(folder);

      myFile = SD.open(folder);
      myFile = myFile.openNextFile();

      if(!myFile) myFile.rewindDirectory();

      if(myFile){

        strcpy(fullPath,folder);
        strcat(fullPath,"/");
        strcat(fullPath,myFile.name());

        myFile.close();
      }
    }

I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called *getFileNameSD()*

I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory

I've included the [memory Free library][1] to see where is the problem. When I call the *getDataSD* and write the file manually I dont have problem.

    myFile = SD.open("/ACC/11001");

Serial monitor

    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
the memory always is the same.

but not when I call the *getFileNameSD()*

    myFile = SD.open(getFileNameSD());

Serial monitor

    freeMemory()=6571
    /-27/-26/-56/
    freeMemory()=6540
    /-27/-26/-56/
    freeMemory()=6509
    /-27/-26/-56/
    freeMemory()=6478
    /-27/-26/-56/
    freeMemory()=6447
    /-27/-26/-56/

I know I'm doing something wrong with *getFileName()* but I don't know what is, can anybody help/explain me?

  [1]: http://github.com/maniacbug/MemoryFree

title: releasing memory in sub-function

Answers: 2

body:
Ok,

I don't know, why your memory is leaking, but anyway, your program won't work safely.
You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.

Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.

body:
Well, finally someone found where was the problem.
In the *getFileName()* function, I open two instances of the file but I close just one.

here is the answer:

    #include <SD.h>
    #include <MemoryFree.h>

    File myFile;
    int stringIndex = 0;
    int cursorPosition = 0;
    char inputString [25];
    char inputChar;
    boolean endOfLine;
    char fullPath[11];

    void setup(){

      Serial.begin(9600);

      Serial.print("Initializing SD card.");
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

    }

    void loop(){

      Serial.println(getDataSD());

      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    }

    void getDataSD(){

      memset(inputString, 0, sizeof(inputString));

      getFileNameSD();

      myFile = SD.open(fullPath);

      if(myFile){
        myFile.seek(cursorPosition);

        endOfLine = false;

        while(myFile.available() && endOfLine == false){
          inputChar = myFile.read();

          if(inputChar == '*'){
            while(inputChar != '\n'){
              inputChar = myFile.read();
            }
          }else{
            cursorPosition = myFile.position()-1;

            if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

            while(inputChar != '\n'){
              if(stringIndex < 25){
                inputString[stringIndex] = inputChar;
                stringIndex++;
                inputChar = myFile.read();
              }
            }
            inputString[stringIndex-1] = '\0';
            stringIndex    = 0;
            endOfLine      = true;
          }
        }
        myFile.close();
      }
    }

    void getFileNameSD (){

      char folder[] = "/ACC";
      File myDir = SD.open(folder);

      memset(fullPath, 0, sizeof(fullPath));

      if (myDir){
        myFile = myDir.openNextFile();

        if(myFile){
          strcpy(fullPath,folder);
          strcat(fullPath,"/");
          strcat(fullPath,myFile.name());
          myFile.close();
          myDir.close();
        }else{
          // Handle file not found
          myDir.close();
          fullPath[0] = '0';
        }
      }else{
        // Handle directory not opened
        fullPath[0] = '0';
      }
    }


body:
I am trying to send a floating point number from a python script to an Arduino.  I am not sure how to do this, especially in a pythonic way.

A little bit of research brought me to this very similar question:
https://arduino.stackexchange.com/questions/3753/how-to-send-numbers-to-arduino-uno-via-python-3-and-the-module-serial
I vaguely understand why this would work for an int but don't know how to modify it.

1) In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

2) Why do they convert to a Char anyway?

3) What code do I run on the arduino to get this back into a float?

4) Can I use bitwise operators on floating point numbers?

I'm new to python and also to low level programming. I am also aware that python and low level don't mix to well. I am using Linux but ideally I need a cross platform solution. Although I would prefer to get it working then worry about cross platform later.

title: Sending a floating point number from python to arduino

Answers: 2

body:
> In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

Instead of using a format specifier of `B` for an unsigned byte, use `f` for a single-precision float. AVR-GCC doesn't support double-precision floats, so don't bother with `d`.

> Why do they convert to a Char anyway?

You don't. You convert it to bytes (hence the `b` prefix on the representation of the value) so that the byte-oriented serial protocol can transmit it. On Python 2.x `str` is already bytes, so no prefix is required there.

> What code do I run on the arduino to get this back into a float?

Use `Serial.readBytes()` to dump the bytes from the serial connection into a `float` variable.

    float f;
     ...
    if (Serial.readBytes((char*)&f, sizeof(f)) != sizeof(f)) {
       ...

> Can I use bitwise operators on floating point numbers?

... Well... no... because they may not necessarily remain valid floating point numbers afterwards.

body:
Floating point numbers are (should) be stored in [IEEE 754 format][1].

If you simply write the binary bytes of a floating point number down the serial line, it should be possible to unpack them at the other end.

To do this (Arduino C/C++), make a pointer from your variable, by casting the address of it to char*. Void* would probably work too.

     float my_value = 22.812;
     my_port.write((const char *)&my_value, sizeof(float)/*4*/);

And the unpacking - there's a few ways to do this, but I like:

     float incoming_value;
     unsigned char buffer[4];

     // If we read enough bytes, unpacked it
     if (my_serial.readBytes(buffer, sizeof(float)) == sizeof(float))
         memcpy(&incoming_value, buffer, sizeof(float));
     else
         // I/O error - no data, not enough bytes, etc.
         incoming_value = 0

On the other end (python), bytes are best handled with the **struct** module.  This will handle the packing and unpacking for you.

    import struct
    ...

    try:
        ieee754_data = my_serial.read(4)
        my_float = struct.unpack('f', ieee754_data)
    catch:
        # I/O Error, or junk data
        my_float = 0.0

And packing:

     ieee754_data = struct.pack('f', my_float)
     try:
         my_serial.write(ieee754_data)
     catch:
         pass #TODO - I/O Error

One more note - You might consider using doubles instead of floats for extra precision.  Python floats have the precision of a C/C++ double already.

  [1]: https://en.wikipedia.org/wiki/IEEE_floating_point


body: I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?

title: Ideas for setting I2C device IDs

Answers: 2

body:
You could use the analog input on pin 1.

Have a table in your code to map voltage thresholds to I2C IDs.

Then build a voltage divider circuit as input that you can adjust with switches or by installing different resistors.

body: Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.


body:
I am trying to use this example code from the [RCSwitch library](https://github.com/sui77/rc-switch):

    /*
      Simple example for receiving

      https://github.com/sui77/rc-switch
    */

    #include <RCSwitch.h>

    RCSwitch mySwitch = RCSwitch();

    void setup() {
      Serial.begin(9600);
      mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
    }

    void loop() {
      if (mySwitch.available()) {
        Serial.print("Is avail");
        int value = mySwitch.getReceivedValue();

        if (value == 0) {
          Serial.print("Unknown encoding");
        } else {
          Serial.print("Received ");
          Serial.print( mySwitch.getReceivedValue() );
          Serial.print(" / ");
          Serial.print( mySwitch.getReceivedBitlength() );
          Serial.print("bit ");
          Serial.print("Protocol: ");
          Serial.println( mySwitch.getReceivedProtocol() );
        }

        mySwitch.resetAvailable();
      }
    }

It seems like the mySwitch.available() is returning false, but since there seems to be no documentation for the library I don't know what it means.

So why is that?

I am trying to use this code on a A-Star 32U4 Micro, which supports Arduino code.

title: Why does the RCSwitch.available return false?

Answers: 2

body: I think that the value of available just determine if there is a message to receive or not.

body:
Your code is OK. It seems that the transmitter's remote control frequency is different from the receiver. Both transmitters and receivers must have the same frequency.
433MHZ - TX with 433MHZ - RX
315MHZ - TX with 315MHZ - RX


body:
I have an [AD5685R DAC](http://www.analog.com/static/imported-files/data_sheets/AD5686R_5685R_5684R.pdf) that I am trying to communicate with over SPI. Per the datasheet,

> ...These [24] bits are transferred to the input register on the 24 falling edges of `SCLK` and are updated on the rising edge of `/SYNC`

where `/SYNC` is used as chip-select.

I believe Arduino's [`SPI.transfer`](http://arduino.cc/en/Reference/SPITransfer) waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?

title: How do I transfer more than 1 byte at once via SPI bus?

Answers: 4

body:
> I believe Arduino's `SPI.transfer` waits to receive 8 bits after sending 8 bits.

Incorrect. With SPI, a byte is clocked in *at the same time* as a byte is clocked out. It may be that this byte is simply a dummy byte though, if the slave has nothing to say.

So for 24 bits, simply clock out 3 bytes without deasserting the select. Since SPI is a synchronous protocol there should be no issue with having a delay in between bytes provided the select is maintained.

body:
Looks like it just set cs low and do three byte transfers then bring it high.   Here's someone's example on how to do it:

http://www.reigndesign.com/blog/controlling-a-10-bit-digital-potentiometer-via-spi-with-arduino/

Code below taken from above page.

    #include <SPI.h>

    const int csPin = 10;

    void setup() {

     SPI.begin();
     SPI.setBitOrder(MSBFIRST); //We know this from the Data Sheet

     pinMode(csPin,OUTPUT);
     digitalWrite(csPin, HIGH);
    }

    void loop() {
     for(int i=0; i<1023; i++) {
      digitalPotWrite(0,i);
      delay(10);
     }
    }

    void digitalPotWrite(int address, int value) {
     digitalWrite(csPin, LOW); //select slave
     byte command = 0xB0; //0xB0 = 10110000
     command += address;
     SPI.transfer(command);
     byte byte1 = (value >> 8);
     byte byte0 = (value & 0xFF); //0xFF = B11111111
     SPI.transfer(byte1);
     SPI.transfer(byte0);
     digitalWrite(csPin, HIGH); //de-select slave
    }

body:
In the SPI protocol, you get one byte back for every one you send.  If you are not interested in the response from a device, you can just ignore the return bytes.

SPI has no handshaking.  You just must send no faster than the slave device can handle.  In the case of the AD5685R, that is 50 MHz.

For multibyte transfer, you keep the chip select asserted (low) between every byte by setting the transferMode to SPI_CONTINUE in the SPI.transfer call.  For the last byte, you will deassert the chip select (set it high) by setting the transferMode parameter to SPI_LAST in the SPI.transfer call..

body:
Note that there is also a version of [`SPI.transfer`](https://www.arduino.cc/en/Reference/SPITransfer) for multi-byte (buffer) transfers:

    SPI.transfer(buffer, size)

I used the buffer transfer in my [library](https://github.com/ulrichstern/Tlc59711/wiki) for the TLC59711 (see [code](https://github.com/ulrichstern/Tlc59711/blob/v1.0.1/Tlc59711.cpp#L91)) and found the buffer transfer faster than transferring bytes individually using `SPI.transfer(val)`; the switch to buffer transfers is _one_ of the reasons my library is about 3.5 times faster than a previous library for the TLC59711.


body:
I am planning to build a LED polar clock, so it will need about 181 LEDs (12 Month, 31 Day, 7 Day-of-week, 12 Hour, 60 Minute, 59 Second) and I need to control each one individually. I will be buying everything from scratch so I ask for help on:

 - Which arduino to use
 - How to make it keep time
 - How to control the LEDs

The LEDs need to stay on once they're lit, e.g. at 5 o'clock, the 1-5 LEDs would be on.
This is why I don't know that multiplexing or charlieplexing will work, as I read that it is better if the LEDs wont be remaining on/only a few are on. The most that could be on is 179 (Friday, December 31, 11:59:59 [Won't happen until 2021]).

Thanks in advance.

title: Individually control ~200 LEDs

Answers: 4

body:
Multiplexing will work fine in this case (Charlieplexing isn't practical here).

You create an array of leds, and light up only one row at a time. If you rotate through all the rows at more than 50 times a second your eyes won't notice it.

In the case of 181 leds, you'd need and array of e.g. 13x14. This will mean you need a minimum of 27 IO-pins. More than the regular Arduinos provide.

So you probably need some additional ICs. You could use simple shift registers, or dedicated led-matrix drivers like the max7219 or some other IC. The Max7219 is probably the easiest, as you don't have to do the multiplexing yourself. The can light upto 64 leds (8x8), so you'd need 3 of them.

PS I get a different number though; 12 (month) + 31 (day) + 7 (weekday) + 23 (hours) + 59 (min) + 59 (sec)= 191

body:
Instead of a multiplexer you can use a "shift register"; the difference is that it keep the last state of the pin, while the multiplexer goes unconnected (and this is because you need at least 30fps, and even so you'll get low light as you are PWMing the leds).
This is why shift register are also called "led driver".

Official tutorial can be found here http://arduino.cc/en/Tutorial/LEDDriver

body:
Check out the TLC5916. It has two advantages over the HC595:

- it can sink a lot of current
- it only needs one resistor

I use it with seven-segment displays. Basically, you tell it "I'm about to send a command." Then you send it, say, "01010101" to turn on every other light. Then you say "okay, make that live." You can chain them together.

Many use the MAX7219 but for me the cost is a drawback.

I might come back and edit this post later to add a Github link to demonstrate...

body:
If the cost is allowed to be moderately higher, your simplest solution could be to use WS2012b individually-addressable LEDs. Since longer chains sometimes have timing problems with the serial communication, I’d probably split them into three groups, attached to three digital pins.

Multiplexing probably requires some flip-flops or other buffers; else, the LEDs may not be bright enough.


body:
I have connected mc to a pc using USB. I need data on hyperterminal through serial to USB connection, hence I connected TX, RX and gnd pins of the Leonardo to the rs232 pins and one other side of rs232 to USB to pc. However, the data is still transmitting on serial monitor, but not on hyperterminal.

    int count = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(3,INPUT); // This is the pin to which we have connected the button
      attachInterrupt(0, IRsensor, CHANGE);
    }

    void loop() {
      if (Serial.available()) {
        /* read the most recent byte */
        /*ECHO the value that was read, back to the serial port. */
        Serial.write(count);
      }
    }

    void IRsensor() {
      if(digitalRead(3) == 1) {
        count++;
        Serial.println(count);
      }
    }

title: how to serially communicate the arduino leonardo to pc through hyperterminal

Answers: 1

body:
To be sure, please add code.

You can use usb on Arduino to communicate with pc. You don't need RS232/USB converter. Just open hyperterminal with the port of arduino. Arduino port can be found in:

 1. Arduino IDE Tools>Port
 2. My Computer>Properties>Device manager>Ports

If you really need `SoftwareSerial` then connect Rx,Tx and don't forget GND!

**UPDATE**

To communicate with RS232/USB converter you have to add RS232/TTL converter to Arduino side. The schematic would look like PC <-> USB/RS232 <-> RS232/TTL <-> Arduino:

1. PC - your computer
2. [USB/RS232][1] to convert from usb to RS232. On RS232 side the voltage is -5V to +5V
3. [MAX232][2] RS232/TTL. To convert the voltage
4. Arduino - your MCU

**UPDATE 2**

As i said, connect your arduino to PC like you do while programming.

![enter image description here][3]
Next, upload this sketch:

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

    void loop() {
      if(Serial.available()){
       Serial.print("\nReceived: ");
       Serial.write(Serial.read());
      }
    }

Open HyperTerminal: choose port with Arduino,

![enter image description here][4]

Connect to arduino, **Serial Monitor has to be closed**

![enter image description here][5]

  [1]: https://www.sparkfun.com/products/11304
  [2]: http://www.ti.com/lit/ds/symlink/max232.pdf
  [3]: https://i.stack.imgur.com/PG9JV.jpg
  [4]: https://i.stack.imgur.com/fA2Pp.png
  [5]: https://i.stack.imgur.com/L1moo.png


body:
I use simple LED blinking code on an [Arduino MEGA 2560][1]. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?

My code:

    // Set up the DATA direction
    void setup()
    {
      for(int i = 1; i<9; i++)
        pinMode (i, OUTPUT);
    }

    // The main program
    void loop()
    {
      for(int j=2; j<=10; j++)
      {
        digitalWrite(j, HIGH);
        delay(100);
        digitalWrite(j, LOW);
      }

      for(int j=9; j>=2; j--)
      {
        digitalWrite(j, HIGH);
        delay(100);
        digitalWrite(j, LOW);
      }
    }

And the circuit is:

![Enter image description here][2]

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: https://i.stack.imgur.com/DeHzm.png

title: Why doesn't pin 9 blink?

Answers: 1

body:
It looks like your main problem is the loop in `setup()`:

    for(int i = 1; i<9; i++)
        pinMode (i, OUTPUT);

This will call `pinMode()` with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to **`i<=9`**.

However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely **must** have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.