# Question
Title: How does arduino fetch instruction string from sms and execute?
I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.

P.S. I am a total beginner at arduino coding so please help me out.

# Answer
> 1 votes
Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.

Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.

The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).

Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!

"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.

Look up the function `sscanf()` \[oops: not sprintf()\] for one way to parse the incoming strings and collect their data.

Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:

```
/*
 * sscanf example - Uses sscanf to test and collect data from a
 * a command string.
 */

#include <WProgram.h>

void test_sscanf(const char *sms);

// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
   "motor,1,5",
   "Hello World,3,2",
   "motor 123 456",
   "moto, 7, 13",
   "motorized, 4, 11"
};

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

   delay(1000);     // delay for user to launch a terminal (if you're quick)

   // Test each SMS example in the SMS array
   for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
      test_sscanf(SMS[s]);  // test one SMS string
   }
}

void loop() {
   ;            // nothing to do here
}

// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
   int16_t assigned, values[2];

   // Print the SMS and convert it.
   Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
   assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

   // Display the results
   Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
   if( assigned > 0 ){
      for( uint8_t i = 0; i < assigned; ++i){
     Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
     Serial.println(values[i]);
      }
   }
}

```

---
Tags: arduino-uno, gsm, string
---


title: Simple Arduino Code Not Working

text:
# Question
Title: Simple Arduino Code Not Working
When I upload this code LED at pin 13 goes HIGH and that's it. My goal is to make it blink in the order specified in the array. What am I doing wrong?

```
int Array[] = {1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0};
int Data = 13;
int i = 0;

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

void loop() {
    int x = Array[i];
    delay(200);
    digitalWrite(Data, x);
    i = i+1;
    if (i==23) {
        i=0;
    }
}

```

# Answer
> 1 votes
What you're doing wrong is living your life at a normal speed.

The LED will be blinking, but so fast you can't see it change.

Without adding some delays in there you will just see the LED light up.

---
Tags: arduino-uno, c++, led
---


# Question
Title: Why doesn't the LED turn on in this circuit?
I'm experimenting with buttons and LEDs and I would like my code to change a LED's brightness once a button is pressed. I connect the LED to the PWD digital pin.

My circuit looks like this one:

This is the code I'm using:

```
int switchPin = 8;
int ledPin = 11;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup() {
    pinMode(switchPin, INPUT);
    pinMode(ledPin, OUTPUT);
}

boolean debounce(boolean last) {
    boolean current = digitalRead(switchPin);
    if (last != current) {
        delay(5);
        current = digitalRead(switchPin);
    }
return current;
}

void loop() {
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH) {
        ledLevel = ledLevel + 51;
    }
    lastButton = currentButton;

    if (ledLevel > 255) ledLevel = 0;
    analogWrite(ledPin, ledLevel);
}

```

Though, the LED never turns on, but the light on the Arduino is on. I made sure the leads of the LED were in the right spot. Why doesn't the LED turn on?

# Answer
Because you don't actually *have* a circuit? One side of the LED doesn't connect to anything.
> 2 votes

---
Tags: c++, led, electronics
---


title: Not waking up more than once?

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

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

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

int pin2 = 2;

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

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

  Serial.println("Initialisation complete.");

}

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

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

void enterSleep(void)
{

  sleep_enable();

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

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_mode();

  /* The program will continue from here. */

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

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

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

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

```

# Answer
For a `RISING` interrupt you never need to disconnect the interrupt to prevent repeat triggering.

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

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

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

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

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

```

See Interrupts.

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

---

Example code:

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

const byte LED = 13;

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

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

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

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

```

Tested and works OK.

---

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

---
Tags: c, interrupt, sleep
---


title: Arduino Pin won't go LOW

text:
# Question
Title: Arduino Pin won't go LOW
I have something strange going on with an output. When the following code is called the LED goes on, but it stays on, there is no blinking. If I comment out the set HIGH statement the LED never comes on (as expected).

```
#define devicePin 10

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

void loop() {
    digitalWrite(devicePin, HIGH);
    delay(2000);
    digitalWrite(devicePin, LOW);
}

```

Could I have damaged the board in some way?

# Answer
After you drive the pin low, you immediately go to the beginning of the loop and set the pin high (if you have an oscilloscope, you might see a very short downward pulse).
So, add another delay after `digitalWrite(devicePin, LOW)`.
> 5 votes

# Answer
you forgot to add a delay after digitalWrite(devicePin, LOW);

```
#define devicePin 10

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

void loop() {
    digitalWrite(devicePin, HIGH);
    delay(2000);
    digitalWrite(devicePin, LOW);
    delay(2000);
}

```
> 3 votes

# Answer
Yes, the pin is going low. I tested it for you:

It went low for 6 µs, once every 2 seconds. :)

---

Overall, this is the effect:

As you can see, high for most of the time.
> 2 votes

---
Tags: c++, led, digital
---


# Question
Title: Can I automatically loop inside a library?
I want to write a little library;
the unlibrarized functionality does:

checking in every loop-cycle some inputs,
doing some calculations with it
and finally setting a boolean to either true or false.

**How do I periodically check the inputs inside the library?**
I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

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

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

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

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

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

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

What's the difference?

In the `loop` you can call something like:

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

```

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

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

---
Tags: programming, c++, library
---


title: Storing array in PROGMEM

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

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

Use the following macro to retrieve them (untested):

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

```

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

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

# Answer
As noted in Ignacio's answer, you can pack your bits of data into bytes and access them via `pgm_read_byte()` calls. If (for coding convenience, not for efficiency) you prefer to pack the bits into larger units, you can use `word` and `dword` access functions, as listed in AVR pgmspace.h documentation. The `_near` and `_far` suffixes denote 16 or 32 bit pointers, respectively; for an Uno with its 32K flash memory, `_near` is always suitable. See PROGMEM documentation at arduino.cc for further discussion.

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

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

```

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

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

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

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

```

Here is what the program produces:

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

```

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

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

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

output = 0
bit = 0

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

print ""

```

Output from above:

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

```

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

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

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

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

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

void loop ()
  {
  }  // end of loop

```

Output from above:

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

```
> 1 votes

---
Tags: arduino-uno, progmem
---


# Question
Title: nRF24L01 module using Mirf library was working and then stopped
I have two nRF24L01 modules, they are both attached to a sensor shield that has special ports for this type of module, on Arduino Unos.

I have this code on the Arduino that is sending the signal:

```
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <SPI.h>
#include <Wire.h>

//0 = stop, 1 = left, 2 = right, 3 = forward, 4 = backwards
long command;
long last_command;

long Joystick_1_X;
long Joystick_1_Y;
long Joystick_1;

void setup() {
  // put your setup code here, to run once:
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setTADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
}

void loop() {
  Joystick_1_X = analogRead(A0);
  Joystick_1_Y = analogRead(A1);

  if(Joystick_1_X < 450){
     command = 1;
  }else if(Joystick_1_X > 600){
    command = 2;
  }else if(Joystick_1_Y > 600){
    command = 3;
  }else if(Joystick_1_Y < 400){
    command = 4;
  }else{
    command = 0;
  }
  if(command == last_command){
  }else{
    Mirf.send((byte *)&command);
    last_command = command;
   }
  }

```

and this code on the Arduino that is receiving

```
#include "SPI.h"
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"

int TN1= 3;
int TN2 = 4;
int ENA = 9;

int TN4 = 5;
int TN3 = 6;
int ENB = 10;

long data;

void setup() {
 pinMode(TN1, OUTPUT);
 pinMode(TN2, OUTPUT);
 pinMode(TN3, OUTPUT);
 pinMode(TN4, OUTPUT);
 pinMode(ENA, OUTPUT);
 pinMode(ENB, OUTPUT);

 Mirf.spi = &MirfHardwareSpi;
 Mirf.init();
 Mirf.setRADDR((byte *)"serv1");
 Mirf.payload = sizeof(long);
 Mirf.config();
 Serial.begin(115200);
 Serial.print("begin");

}

void loop() {

  // put your main code here, to run repeatedly:
  receiveCommand();
  if(data == 1){
    left();
  }else if(data == 2){
    right();
  }else if(data == 3){
    forward();
  }else if(data == 4){
    backwards();
  }else if(data == 0){
    stop_rover();
  }
}

void receiveCommand(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
    Serial.print(data);
  }else{
    Serial.println("No data to be recieved");
  }
}

void forward(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, HIGH);
  digitalWrite(TN2, LOW);
}

void backwards(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, HIGH);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, HIGH);
}

void left(){
   digitalWrite(ENA, HIGH);
   digitalWrite(TN1, HIGH);
   digitalWrite(TN2, LOW);
}

void right(){
  digitalWrite(ENB, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
}

void stop_rover(){
  digitalWrite(ENB, LOW);
  digitalWrite(ENA, LOW);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, LOW);
}

```

This was working, and the rover did spin its wheels when the remote broadcasted a signal, but then it just stopped. The sensor shield says that they are plugged into the 3V port, I tried using the RF24 library and that did not work either.

Any help would be greatly appreciated.

# Answer
Using the MIRF Library that I got from here, and then using this code to send

```
 Mirf.send((byte *)&command);
    while(Mirf.isSending()){
        }

```

and this code to receive

```
 if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
else(){
}

```

I was able to get it to work
> 1 votes

---
Tags: arduino-uno, c++, nrf24l01+
---


# Question
Title: Unable to set up Intel Edison on Windows
I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.

My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.

I am using an Edison with an Arduino breakout board.

Here is the sequence of steps I followed:

1. I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
2. I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

3. I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
4. Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

5. I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
6. I went to Windows Device Manager and found the connected device on COM6
7. I installed Putty and connected to COM6 with a baud of 115200.
8. The console showed a blank screen with a green cursor in the top left.
9. I waited 30 seconds for it to boot.
10. I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

```

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

```

I have no idea what to do next.

# Answer
> 0 votes
I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)

I am using Windows 8.1, 64 bit edition.

1. Download the Edison firmware from https://software.intel.com/en-us/iot/hardware/edison/downloads. For me it was http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip.
2. Extract the zip file.
3. Start the Windows Command Prompt as Administrator.
4. The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.
5. Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.
6. Follow the steps in my question until the output on the console (also from my question) appears.
7. Run "flashall --recovery"
8. Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.
9. Wait about 5 minutes for the rest of the process to run automatically.

At this point everything should work again.

You should see this on the command line in Windows:

```
C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download        [=========================] 100%      4194304 bytes
Download done.
Download        [=========================] 100%      4194304 bytes
Download done.
Flashing U-Boot
Download        [=========================] 100%       237568 bytes
Download done.
Flashing U-Boot Environment
Download        [=========================] 100%        65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download        [=========================] 100%        65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download        [=========================] 100%      6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download        [=========================] 100%    566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.

C:\Users\_\Desktop\edison-image-ww25.5-15>

```

---
Tags: edison
---


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

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

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

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

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

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

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

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

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

  delay(5000);              // wait for 5 seconds

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

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

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

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

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

```

# Answer
> 4 votes
You are attempting to use IO pins that are already in use by the MP3 shield.

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

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

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

---
Tags: arduino-uno, c++, shields, relay, system-design
---


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

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

# Answer
> 6 votes
No, it is not true.

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

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

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

# Answer
> 1 votes
According to the datasheet:

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

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

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

> would you know what would the UART be?

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

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

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

---

This is related to your other thread Can Arduino Uno's serial handle to foward push through 1-wire protocol? isn't it? Your end objective, I am guessing, is to try to implement 1-wire reading/writing via sending each bit via serial. This is just not the right way to achieve that objective.

In fact this thread in particular is coming across as an X-Y problem \- your stated objective of wanting high-speed serial, is not really the problem you are trying to solve, is it?

---
Tags: arduino-uno, serial
---


title: AVR+Arduino ADC problem

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

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

 uint16_t ReadADC(uint8_t ch)
 {

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

     //Start Single conversion

     ADCSRA|=(1<<ADSC);

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

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

     return(ADC);
}

int main()

  {

uint16_t adc_value;

InitADC();

while(1)

{

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

  }

   return 0;

  }

```

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

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

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

```

---

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

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

---

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

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

```
const byte adcPin = 0;  // A0

bool working;

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

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

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

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

  // do other stuff here

  }  // end of loop

```

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

See ADC conversion on the Arduino (analogRead) for more details.
> 1 votes

---
Tags: arduino-uno, sensors, c++, analogread, avr
---


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

avr/power sketch:

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

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

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

  // Power-down board
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();

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

  // Power down functions
  PRR = 0xFF;

  // Enter sleep mode
  sleep_mode();
}

void loop()
{
}

```

rocketscream/Low-Power sketch:

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

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

```

# Answer
I tried your first sketch on my "bare-bones" board.

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

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

```
  Serial.begin(9600);

```

That reduced consumption to 122 nA.

See Power saving techniques for microprocessors.

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

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

---
Tags: power, arduino-pro-mini, sleep
---


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

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

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

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

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

# Answer
> 1 votes
Ok, so there's two issues at stake here.

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

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

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

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

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

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

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

# Answer
> 1 votes
Your idea seems wrong-headed, if I may say so without giving offence.

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

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

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

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

# Answer
> 1 votes
It certainly is possible for an Arduino to do this. For example, source code for Atmel's implementations of 1-Wire protocol via bit-banging, via polling UART, and via interrupt-driven UART, is available at github.com.

There is a 21-page PDF file, doc2579.pdf, available at Atmel. It documents how the different implementations work.

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

---
Tags: serial
---


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

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

```

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

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

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

See Receive Only Software Serial - Arduino Forum

---

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

Like this?

```
const byte LED = 1;

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

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

```

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

---
Tags: serial
---


# Question
Title: How to rsync my node.js project to my intel edison board, through ssh?
I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.

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

But `rsync` is not installed on the board.

How would you do this?

# Answer
You have few options:

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

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

# Answer
rsync works by talking to the rsync executable running on the remote target; without said executable you will need to drop to either scp or a tar pipe.
> 1 votes

---
Tags: uploading
---


# Question
Title: Can a Ethernet USB Dongle be instead of ethernet shield for arduino?
Can a Ethernet USB Dongle be instead of Ethernet shield for arduino in order to cut costs?

# Answer
> 2 votes
No. Arduino can't behave as USB host.

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

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

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

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

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

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

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

---
Tags: ethernet, hardware
---


# Question
Title: Communicating Via Serial1 on Arduino Mega
Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.

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

```
#include <SoftwareSerial.h>

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

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

```

How do I communicate using Serial1?

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

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

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

```

etc.
> 0 votes

---
Tags: serial, arduino-mega, xbee, softwareserial
---


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

I tried a simple layout such as below, with the sample code from a sparksfun tutoral, but that's not working!

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

Thanks

# Answer
> 1 votes
Your options:

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

---
Tags: usb, voltage-level, piezo, buzzer
---


title: Hard-resetting an arduino

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

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

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

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

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

```

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

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

How is this done?

# Answer
> 2 votes
The word "clone" immediately rings alarm bells.

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

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

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

As I say that is unlikely.

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

---
Tags: serial, reset
---


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

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

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

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

---
Tags: servo
---


# Question
Title: Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino
Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?

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

This is what I have found so far:

1. I'm basically trying to replicate the following: https://nimbelink.com/e2clink-ethernet2cellular/#parts
2. If the following reddit post: https://www.reddit.com/r/arduino/comments/3azxs6/create\_gsm\_cellular\_ethernet\_modem\_with\_arduino/ is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.

# Answer
No, it's not possible.

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

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

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

Way outside the scope of a lowly Arduino.

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

---
Tags: ethernet, gsm
---


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

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

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

Good luck!
> 1 votes

---
Tags: arduino-uno, motor, arduino-ide, reset
---


title: Problem with Arduino code

text:
# Question
Title: Problem with Arduino code
Please help me with this code it's shows some error \[but I can't be bothered to tell you what\].

```
#include <TimerOne.h>

/**

 Analog Clock

 Paul Cox Dec 2010

*/

#define    PI       3.141592653589793e-06;

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

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

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

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

volatile byte screenRow = 0;

volatile byte screenCol = 0;

int iHour = 0;

int iMin = 0;

int iSec = 0;

void setup()

{

  Timer1.initialize(100);

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

  {

     pinMode(i, OUTPUT);

  }

  Timer1.attachInterrupt(doubleBuffer);

  Serial.begin(9600);

  resetAnim();

}

void doubleBuffer()

{

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

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

  screenCol++;

  if (screenCol >= 8)

  {

     screenCol = 0;

     screenRow++;

     if (screenRow >= 8)

     {

       screenRow = 0;

     }

   }

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

   {

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

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

   }

   else

   {

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

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

   }

}

byte translatePin(byte original)

{

  return pins[original - 1];

}

void allOFF()

{

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

  {

     screen[i] = 0;

  }

}

void on(byte row, byte column)

{

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

}

void off(byte row, byte column)

{

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

}

void resetAnim()

{

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

  {

     screen[i] = B11111111;

     delay(25);

  }

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

  {

     screen[i] = B00000000;

     delay(25);

  }

}

void loop()

{

  drawClock();

  iSec++;

  if (iSec == 60)

  {

    iSec = 1;

    iMin++;

    if (iMin == 60)

    {

       iMin = 0;

       iHour++;

       if (iHour == 12)

       {

          iHour = 0;

       }

    }

  }

  delay(10);

}

void drawClock()

{

  allOFF();

  setHand(iHour,12,3);

  setHand(iMin,60,4);

  setHand(iSec,60,5);

}

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

// radius is distance from the centre

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

{

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

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

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

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

}

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

{

  int      iTemp;

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

  if (bSteep)

  {

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

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

  }

  if (x0 > x1)

  {

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

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

  }

  int deltax = x1 - x0;

  int deltay = abs(y1 - y0);

  int error = deltax / 2;

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

  int y = y0;

  int x = x0;

  while(x <= x1)

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

```

# Answer
> 3 votes
It's amazing the difference one character can make:

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

You have a macro defined:

```
#define    PI       3.141592653589793e-06;

```

That macro is then used here:

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

```

Expand the macro PI and you get:

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

```

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

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

```
arduino/Arduino.h:#define PI 3.1415926535897932384626433832795

```

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

---
Tags: arduino-uno, c++, timers
---


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

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

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

Specifically, I am referencing the following

# Answer
> 1 votes
One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.

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

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

---

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

---
Tags: arduino-mega
---


title: Bluetooth Stream to USB

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

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

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

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

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

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

---
Tags: bluetooth, usb
---


title: Servo - Serial communication problem

text:
# Question
Title: Servo - Serial communication problem
I am sending data from an Arduino Uno to an Arduino Mega via serial communication.

The data is analog value. I'm getting that data and converting it to an int. There is no problem there. However, when I connect the servo to the attached pin, the serial communication on mega becomes disconnected. When I remove the PWM pin, the serial communication is working again. Why does the servo stop serial communication?

Wiring: Mega-- 5v and gnd pins linked to servo ( 13kg/cm ), PWM 2 pin is linked to servo's pwm input, rx2 pin is linked to uno's tx pin

# Answer
If you draw too much current from an Arduino microcontroller it can reset itself (brownout), that results in it not responding. To solve this do not power your servo directly from the Arduino, use an external power supply.
> 2 votes

# Answer
If you are using delay function then I guess the problem is due to that. Just try once using millis function to generate PWM signal at Mega.
> 0 votes

---
Tags: serial, servo
---


# Question
Title: Where to get the potentiometer that comes with Arduino kit
Does anyone know where I can get the potentiometer that comes with the Arduino kit? You can see them here.

They are sold out on their website.

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

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

---
Tags: potentiometer
---


# Question
Title: How do I start a function with serial input?
I want to create a LED Sunrise/Sundown alarm clock. Therefore, I will use a Raspberry Pi that is sending commands over serial to a Teensy 3.1. Like:

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

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

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

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

```

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

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

What is the best way do get this working?

Thanks in advance!

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

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

```

Although i read quite a bit now, serial input is still a mystery to me.

---
Tags: serial
---


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

---

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

---

# Answer
I found a user manual at AMPIRE Car Alarm System for High-Speed CAN-Bus.

> **N1/9 BROWN/WHITE – 200mA (-) Horn honk output:**
>
> This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit.
>
> **IMPORTANT!** Never use this wire to drive anything but a relay or a low-current input! This transistorized output can only supply (-) 200mA and connecting directly to a solenoid, motor or other high current device will cause the module to fall

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

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

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

```

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

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

---

Suggested schematic:
> 1 votes

---
Tags: signal-processing
---


title: Potentiometer won't work

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

Thanks!

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

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

 Created by Ryan Achten | SOMA | somavisions.com

 This example code is in the public domain.
 */

int potentLevel;
int ledLevel;

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

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

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

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

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

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

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

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

  Serial.begin(9600);

  pinMode(led, OUTPUT);

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

}

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

void loop()  {

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

  if (index >= numReadings)
    index = 0;

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

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

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

  Serial.println();
  delay(loopDelay);

}

```

# Answer
> 1 votes
Assuming the brown board in your drawing is stripboard, I have to as the question:

What is this?

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

---
Tags: potentiometer
---


title: Problem in SIM900 GPRS connection

text:
# Question
Title: Problem in SIM900 GPRS connection
I make simple code to read web page by ITEAD Gboard. Here is my code:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

Which i get the following output:

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

ERROR

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

+CGATT: 1

OK

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

ERROR

end.

```

AT+HTTPREAD return error. What wrong with me?

**Note**

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

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

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

---
Tags: gsm, arduino-duemilanove
---


title: Buttons and LED

text:
# Question
Title: Buttons and LED
I am creating a program that turns on and off an led. When two buttons are considered "high". But there is a twist, The first button needs to stay "high" until the second button is pressed and the led turns on. Here is my code so far.

```
// Boolean logic for Button Switch
boolean currentState = LOW;    //stroage for current button state
boolean lastState = LOW;      //storage for last button state
boolean ifcondState = LOW;    //storage for the current state of the ifturn  (off/on)

// set pin numbers:
const int buttonPinA = 3;     // the number of the pushbutton pin
const int buttonPin1 = 4;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
const int ifcond =  12;      // the number of the ifcond pin
const int ifturn =  11;      // the number of the ifturn pin

// variables will change:
int buttonStateA = 0;         // variable for reading the pushbutton status
int buttonState1 = 0;         // variable for reading the pushbutton status
int buttonStateIf = 0;         // variable for reading the If Condition status

void setup() {
//initialize Serial connection
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPinA, INPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin1, INPUT);
// If Condictional Pin
pinMode(ifcond, OUTPUT);
// If Turnon Pin
pinMode(ifturn, INPUT);

}

void loop() {
  // read the state of the pushbutton values:
  currentState = digitalRead(buttonPinA);
  buttonState1 = digitalRead(buttonPin1);
  buttonStateIf = digitalRead(ifturn);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (currentState == HIGH && lastState == LOW){    //  if button has just been pressed
    Serial.println("pressed");
    //delay(1);

    //toggle the state of the ifcond
    if (ifcondState == HIGH){
      digitalWrite(ifcond, LOW);
      ifcondState = LOW;
    }
    else {
      digitalWrite(ifcond, HIGH);
      ifcondState = HIGH;
    }
  }
  lastState = currentState;

  if (ifturn == HIGH && buttonState1 == HIGH) {
    digitalWrite(ledPin, HIGH);
  }
  else ();
  digitalWrite(ledPin, LOW);
}

```

I have Pin 12 (ifcond) And pin 11(ifturn) Jumped together. Pin 12 acts like a button to pin 11, When it goes high pin 11 reads the change.

The code works like this, When ButtonpinA goes high pin 12 goes high and stays high until the next button push. This is the part that doesn't work Pin 11 should read if pin 12 if high or not. If it reads high and Button1 is also high it should turn on ledpin which it does not.

I am sorry for any confusion Thanks

# Answer
```
if (ifturn == HIGH && buttonState1 == HIGH) {
  digitalWrite(ledPin, HIGH);
}
else ();
digitalWrite(ledPin, LOW);

```

I think you have made a small mistake here.

What you are saying there is "If both these inputs are high then turn on the LED - otherwise don't do anything", and immediately after that "Turn off the LED".

So the LED is turned on when they are both high, and immediately turned off again, so fast you never see the LED lighting up at all.

I think what you meant to have was:

```
if (ifturn == HIGH && buttonState1 == HIGH) {
  digitalWrite(ledPin, HIGH);
} else {
  digitalWrite(ledPin, LOW);
}

```

That way it will turn the LED on if both are HIGH, otherwise it will turn the LED off *only if the test for both being high fails*.
> 1 votes

---
Tags: arduino-uno, led, button
---


# Question
Title: Corrupted output from HC-05 Bluetooth module
I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

```
void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

```

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?

# Answer
> 2 votes
First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation. And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:

Notice that the Key pin is connected to 3.3v. That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable. Upload the following sketch:

```
/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;

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

  mySerial.begin(38400);
  mySerial.println("AT");
}

void loop() {
  while (mySerial.available()) {
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    mySerial.print(myChar);
  }
}

```

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

```
AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

```

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before. Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it. The name probably will have changed. Hopefully it works correctly now.

Cheers

# Answer
> 0 votes
I have the same problem with arduino pro mini and HC-06, only change the baud rate of your BTserial port... try diferent baud rates in my case:

```
Serial.begin(9600);
Serial.println("AT");

BTSerial.begin(2400);
BTSerial.println("AT");

```

Works fine, it happens because the arduino try to "understand" the module, but if the module speaks other leanguage, the arduino will never understand the command.

like me... sorry for my bad english. se ya.

# Answer
> -1 votes
Add the module as software serial then add these lines to setup() these line tell us the Bluetooth to turn into data mode:

```
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);

```

---
Tags: arduino-pro-mini
---


# Question
Title: How to connect this motor driver board to Arduino to drive bidirectional motor?
I am familiar with using PWM on Arduino and have done so with simple 3-pin interfaces: e.g. PWM, DIR (direction) and GND pins. Choose a direction with DIR, set speed with PWM in software (0 - 255), simple stuff.

But this board I'm buying seems different:

http://www.ebay.com/itm/DC-43A-Double-BTS7960B-Stepper-Motor-Driver-H-Bridge-PWM-for-Arduino-Smart-Car-/141485439094

There seems to be 6 control pins:

`R_IS, R_EN, RPWM, L_IS, L_EN, LPWM`

But from what I understand this board would only be used for controlling one motor bidirectionally, so why is there a distinction between left and right?

So how would I go about using this motor driver board in a similar way to my `PWM, DIR, GND` boards that I've used before to control the motor direction and speed?

Thanks!

# Answer
> 2 votes
I guess you have used DC Motor for your earlier cases? Or Step Motor with a logic on the stepper controllers?

Here you have two H Bridges which drives one Step Motor. So as I understand it, you have two PWM Inputs, one for each output channel to the coil windings of the stepper motor. Like an encoder signal you can set the direction with setting one pwm before the other. So the step motor is controlled via unipolar stepping.

For further help you need to say which motor you want to use with this card. But first I would look at the different stepping modes (unipolar and the two bipolar and maybe microstepping).

Greets

---
Tags: current, motor
---


title: Transistors to switch monitor inputs

text:
# Question
Title: Transistors to switch monitor inputs
I am using the following setup on my Arduino UNO to measure cpu fan RPMs:

The code is set to bring the trigger pin for each transistor high when it is checking that fan's RPM and FreqMeasure.h is then used to check the frequency of the signal on pin 8 which is then translated to RPM and sent to the LCD display.

I am experiencing reading issues and suspect that the signal is remaining on the measuring bus during the subsequent reads, however before revamping my code I simply wonder:

Is my circuit logic sturdy? I am just getting my feet back under me with microprocessors and have always found transistors to be a tricky subject, thanks in advance for your help!

If you'd like to see more info all can be found on GitHub.

# Answer
I have simulated your circuit and it seems sound enough to me.

It is a little confusing having the transistors there though. I would prefer to convert the three open drain outputs to logic level outputs (each having its own pullup resistor) then use a digital 3:1 MUX (or discrete logic gates) to select the signal to sample.
> 0 votes

---
Tags: frequency, transistor
---


title: USB mini type B port on Arduino Uno

text:
# Question
Title: USB mini type B port on Arduino Uno
I bought today an Arduino Uno R3, and I'm looking forward to make it an HID device. I have seen many projects using a serial USB type B port. As I want to build a little gamepad, I would like to use the smaller USB mini type B port to achieve similar results. Looking it up did not seem to bring significant results.

Am I missing anything? Do I have to use a serial port similar to the one used by Arduino or can I reproduce the project using the aforementioned port?

# Answer
It sounds like you are going to be attempting software "bit-banged" USB. That, while possible, is severely frowned upon, especially when you have the resources to do it properly at your fingertips.

In answer to your question, yes, you can use a USB mini B connector. It is no different to a USB B connector except it is much smaller and contains one extra pin - USBID - which you can completely ignore (it's only used on USB On-The-Go devices).

USB is quite a heavy protocol to do in pure software - it won't leave much "room" for you to do much else. Better would be to re-program the ATMega16U2 chip that is used for the current USB interface. You will need some form of hardware programmer for it - you can use another Arduino Uno, and once done you won't be able to directly program the ATMega328P chip through the USB, so you would need some other method for connecting that (external USB serial adapter cable, or another Arduino), but the ATMega16U2 chip is specifically designed to work with the USB. Offloading the USB portion of your project onto that chip and using the serial interface that is already wired up to communicate commands and instructions to/from the ATMega328P would be a much more powerful (and reliable) system. There's plenty of tutorials and links around to show you how to reprogram that chip.
> 2 votes

# Answer
As an alternative to Majenko's suggestion you can implement Virtual USB as described at Virtual USB Keyboard. You just need:

* 3 resistors
* 2 zener diodes
* a bit of wire
* a suitable USB socket

The advantage is you haven't modified your Uno's USB chip (the ATMega16U2) so you can continue to upload sketches in the normal way.

The disadvantage is that the software USB may be more flaky than a hardware-implemented one.

Personally I don't like reprogramming my ATMega16U2 because I may as well have used one of the chips with a ATmega32U4 chip on it in the first place (like the Micro) which is designed for easy reprogramming.
> 2 votes

---
Tags: arduino-uno, usb, arduino-mini
---


title: Basics with DHT11

text:
# Question
Title: Basics with DHT11
I just bought the sensor DHT11 and trying to test it with the library code provided by the IDE, but I always get the same error on `.read()` . Code -2

```
/*####################################################################
FILE: dht11_functions.pde - DHT11 Usage Demo.
VERSION: 2S0A

PURPOSE: Measure and return temperature & Humidity. Additionally provides conversions.

LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
GET UPDATES: https://www.virtuabotix.com/

  --##--##--##--##--##--##--##--##--##--##--
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ## DHT11 SENSOR ##  ##  ##  ##
  ##  ##  ##  ##  ##FRONT ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  --##--##--##--##--##--##--##--##--##--##--
      ||       ||          || (Not    ||
      ||       ||          || Used)   ||
    VDD(5V)   Readout(I/O)          Ground

HISTORY:
Joseph Dattilo (Virtuabotix LLC) - Version 2S0A (27 May 12)
-Rewritten to with more powerful Versalino functionality
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.5 (11/11/11)
-Made Library Arduino 1.0 Compatible
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.0 (06/11/11)
-Fixed bugs (squish)
Mod by Rob Tillaart - Version 0.3 (28/03/2011)
Mod by SimKard - Version 0.2 (24/11/2010)
George Hadjikyriacou - Original version (??)
#######################################################################*/

#include <dht11.h>

dht11 DHT11;

void setup()
{
    DHT11.attach(2);
    Serial.begin(9600);
    Serial.println("DHT11 TEST PROGRAM ");
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHT11LIB_VERSION);
}

void loop()
{
    Serial.println("\n");

    int chk = DHT11.read();

    Serial.print("Read sensor: ");
    switch (chk)
    {
        case 0: Serial.println("OK"); break;
        case -1: Serial.println("Checksum error"); break;
        case -2: Serial.println("Time out error"); break;
        default: Serial.println("Unknown error"); break;
    }

    Serial.print("Humidity (%): ");
    Serial.println((float)DHT11.humidity, DEC);

    Serial.print("Temperature (°C): ");
    Serial.println((float)DHT11.temperature, DEC);

    Serial.print("Temperature (°F): ");
    Serial.println(DHT11.fahrenheit(), DEC);

    Serial.print("Temperature (°K): ");
    Serial.println(DHT11.kelvin(), DEC);

    Serial.print("Dew Point (°C): ");
    Serial.println(DHT11.dewPoint(), DEC);

    Serial.print("Dew PointFast (°C): ");
    Serial.println(DHT11.dewPointFast(), DEC);

    delay(2000);
}

```

And this is my ouput:

```
DHT11 TEST PROGRAM
LIBRARY VERSION: 2S0A

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

```

The wiring:

-left pin: 5v

-right pin: gnd

-middle pin: 5v - digital2 - through 10kO resistor

**UPDATED:** I found a library that works. I also changed the wiring because I found out the sainsmart dht11 switches the pins:

-left: signal with 10kO and to 5v

-middle: 5v

-right: GND

Now just a question. What is the difference between these two dht11 sensors. Dht11 basic dht11 with board

The one from sainsmart has a piece of circuit I don't know what it is.(I have a lack on electronics I try to fix step by step...)

**It is a resitor, capacitor?** it says 103.

How does this affect to the wiring?

# Answer
> 2 votes
The DHT11 sensor is available as-is and integrated on a break-out board. The break-out board shows following differences:

* the order of PINs is changed, e.g. in one version: 1 -\> signal, 2 -\> `+`, 3 -\> GND (left-to-right, pins down, looking at the front)
* the unused pin is not connected
* the board already has a 10 KOhm pull-up resistor connected

Thus, when you have a DHT11 on a break-out board you have to adjust schematics that use it as-is - e.g. in this example you have to remove the external pull-up resistor and connect the pins in the correct order.

Be aware that there may be different versions of DHT11 breakout boards available - i.e. ones where the order of pins is different. You can look out for PIN markings like `S` (-\> signal) and `-` (-\> GND). Also, you can look at both sides of the breakout board to trace the connections.

The resistor usually comes as SMD on such a board - and if it has a marking it uses a special code. For example, `103` means `10 * 10^3` Ohm, i.e. 10 KOhm.

The adafruit DHT library comes with an example sketch that prints the sensor values over serial.

# Answer
> 0 votes
It seems you wiring is ok, although I think you already have pull-up resistor on breakout board (look for a small 103 resistor).

Maybe you can try another library for DHT? I have used one made by adafruit (https://github.com/adafruit/DHT-sensor-library) and everything worked just fine.

Regards, Ian

---
Tags: sensors, wires, temperature-sensor
---


title: Comparators for digital input mode

text:
# Question
Title: Comparators for digital input mode
I've asked another question in electronics about what to use to compare 2 input voltages, the answer was to use comparators.

Digging around a bit, turns out most of the comparators outputs are pull-up, which makes it quite difficult to translate (probably due lack of general electronics knowledge, self-learned) and I'm not able to distinguish from maker's PDFs which comparators have pull-up or pull-down outputs. I've figured PD comparators illustrate in PDF a resistor right after the output... but many illustrations I've seen doesn't clarify PD / PU, or I'm just missig that.

But my question is, are there any PD comparators (well known) where it's output can be connected to the digital pins or arduino (while those are defined as INPUT mode)?

I appreciate any guidance on this topic.

Just a side note, I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V...

# Answer
> 2 votes
You can't put 12 volts into a Uno input pin in any case.

You could run it into a voltage divider and divide it down to somewhere on the range 0 to 5 V, and then do an analogRead to see exactly (or almost exactly) what the resulting voltage is.

I don't really see where comparators come into it in this particular case. I mean, you could use a comparator to turn the LED on, but then where does the Arduino come into it?

---

> I've actually tried with voltage divider, I went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly.

You need a voltage divider like this:

Those values give you 4 V on the Arduino pin if there is 12 V on the input.

Vout = (R2 / (R1 + R2) ) * Vin

So:

```
(1000 / 3000) * 12V = 4V

```

# Answer
> 0 votes
Many comparators come with open collector output. OC output means, it can pull down a potential, but cannot generate a voltage higher than ground.

If you have a high impedance input like your Arduino has, and you connect a OC output to it, nothing will happen unless you add a pullup resistor providing a positive voltage. Otherwise there won't be a closed electric circuit where any measurable voltages can be generatet.

Lucky you: Arduino input pins can generate a positive voltage by providing an internal pullup resistor. Read the documentation on input pins and pin direction to make use of this. This way you can connect an open collector output to your input pin without additional components.

But beware: This doesn't work with a comparator with a pullup output (I guess these are rather rare). In this case you have to provide an additional pulldown resistor to ground.

Caveat: You can use a comparator with totem pole or tristate output without pullup or down as long as its output swing does not exceed maximum allowable voltages of the input pin. I.e. you cannot connect a comparator supplied with 15 V and a totem pole output to the input of an arduino, because the high level will exceed 5 volts (I assume an Arduino Uno).

Now. How to learn from a datasheet, if the output is pulldown, pullup, totempole or tristate? If a device features a pulldown stage, you will find a value for something called "Output Sink Current" in the section "electrical characteristics". For a pulldown stage this will likely be named "Output source current". A tristate output will be denominated somewhere in the datasheet for sure, because this is an extra feature.

Have a look at lm339!

---
Tags: arduino-uno, digital-in
---