title: cu port always busy on Mac

text:
# Question
Title: cu port always busy on Mac
I'm going bonkers here. I'm using a Macbook Pro with Yosemite. Connected to the MKS Gen-2Z V1.1 reprap board (ATmega 2560).

The Arduino IDE only shows the cu port being available and not the tty.

Any attempts at opening the CU port show it as being busy. This is also true when I open the port using PronterFace (3d printer software). Yet, the PronterFace shows the tty port and gladly opens it and communicates. I downloaded Arduino 1.0.6 and the tty is available in the dropdown menu and it will open the port. But my 3D printer firmware will fail building on any Arduino IDEs prior to 1.6.0.

I found a few suggestions on creating a file "lock" in /var/ and then changing the r/w permissions. Also doing the same for /var/spool/uucp. Changing both of those permissions did nothing for me.

I may just have to build it and use AVRdude directly so I can use the tty port, but I have no idea why the cu would be busy all the time. Any suggestions?

Here's the Arduino output when I try to upload:

> avrdude: ser\_open(): can't open device "/dev/cu.usbserial-AL00YS9R": Resource busy
> ioctl("TIOCMGET"): Inappropriate ioctl for device
> ioctl("TIOCMGET"): Inappropriate ioctl for device
> avrdude: ser\_send(): write error: Bad file descriptor
> Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

# Answer
Can't you see what's hooking the serial port with `sudo lsof -n | grep cuaU0` ? If so, `sudo kill -9 12345`, where 12345 is the offending PID. Your FTDI chip may need a driver, try `sudo dmesg` after pluggibg it in, or use systemprofiler.
> 1 votes

# Answer
JRobert - I'll have to try the csrutil suggestion. The problem I see with that is the board I am trying to interface with has a genuine FTDI chip, the 232RL. The answer posted was to install a driver for a chinese USB chip.

Gerben - I do have a /dev/tty.usbserial-AL00YS9R. The Arduino IDE is only showing the cu ports.
> 0 votes

---
Tags: serial
---


title: Arduino Nano stuck on uploading

text:
# Question
Title: Arduino Nano stuck on uploading
I recently bought an Arduino Nano ( a clone actually), I installed the CH340G drivers for it and got it working perfectly fine... Played around with it for a while and then kept it aside...

Now after sometime I get time to play with it again, I was actually trying to power it with my 11.1V 2200mAh 8C LiPo battery. So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Now I move on to my computer to program it but the Arduino IDE is stuck at uploading. It was working fine before, when I hit upload, the RX LED glows *VERY* dimly and the board just stays like that. Only the power LED glows up, not even the LED on pin 13 glows up.
Uploading to a UNO works perfectly fine.

This is the error I get after a while-

> avrdude: stk500\_recv(): programmer is not responding
> avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x7d

Did I burn my board? Or is it just a bootloader issue?

# Answer
> 1 votes
> So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Unfortunately Vin on an Arduino Nano does not have a reverse polarity protection diode such as the Arduino Uno PWRin

> Did I burn my board?

Very probable. For more details please see "10 Ways to Destroy an Arduino".

Cheers!

---
Tags: arduino-ide, arduino-nano
---


# Question
Title: Understanding memory fragmentation due to char arrays in functions
This is similar to: Is this function subject to memory fragmentation?

I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.

Currently I have a function in a `__lcdAux__` Class which is responsible for doing basic operation on the lcd. One of the members of the class is a char array `double2StrBuff1` which is used with `__dtostrf()__` to create a double which is then passed to `sprintf`. So the following function (`__lcdAux::UpdatePosition__`) is responsible for updating the position on the lcd.

```
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

```

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.

However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.

```
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char double2StrBuff1[10];
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

```

To sum up:

* by putting the declaration for variable `__char double2StrBuff1[10];__` inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

* is the fact that `__double2StrBuff1__` is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that `__"X: %s"__` is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string `__"X:%s"__` I use a `_PROGMEM` const `char_ array` and `__strcpy_P()_`, but to simplify the question I replaced it with the literal string , since I feel that is another problem.

# Answer
> by putting the declaration for variable char double2StrBuff1\[10\]; inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function

This is correct.

> is the fact that double2StrBuff1 is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

No, `double2StrBuff1` is not a pointer, it's an array. In C and C++, when you use an array identifier, it decays to a pointer in many situations. However, for the purpose of memory allocation, an array is *very different* from a pointer.

Heap allocation only happens when using `malloc()` and `new`.
> 3 votes

# Answer
The examples in the question above use 1) global and 2) local aka stack allocation and do not give heap fragmentation. The heap is not involved.

Below is a version that may give heap fragmentation (though a very low risk):

```
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char* double2StrBuff1 = (char*) malloc(10);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
    free(double2StrBuff1);
}

```

Please not that heap allocation is very slow compared to stack allocation.

C/C++ does not have any implicit heap allocations (in the language). A local array in a function is allocated on the stack and removed when the function returns. The only library functions that can generate stack fragmentation are setjmp and longjmp if used to create a spaghetti stack.
> 2 votes

---
Tags: string, memory
---


title: Arduino Wire.h send double to lcd

text:
# Question
Title: Arduino Wire.h send double to lcd
I'd like the double number 200.00 shown as `200.00` on my LCD screen.

For instance, when I pass just a number (`int`) like 40 to the LCD, it uses it as an ASCII code to show a character on the display.

Now I want to send a `double` to it and it should be displayed as a double.

```
#include <Wire.h>

void setup() {
   Wire.begin(0x63);
}

double f;
void loop() {

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(f); //<- How to do this?
  Wire.write("Hz");
  Wire.endTransmission();
}

```

# Answer
> 2 votes
The Arduino Wire class does only support write() of byte, string and vector of bytes. To write a double it must first be converted to a string. This can be done with the standard C library function dtostrf().

```
double f;

void loop() {
  char buf[10];

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(dtostrf(f, 0, 2, buf));
  Wire.write("Hz");
  Wire.endTransmission();
}

```

The class inherits from Print (via Stream) so that the overloaded member function print() for double can be used. In that case:

```
double f;

void loop() {
  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.print(f);
  Wire.write("Hz");
  Wire.endTransmission();
}

```

Please note that the maximum number of bytes to write (between beginTransmission and endTransmission) is limited to 32 in the standard configuration of the Arduino core.

Cheers!

# Answer
> 1 votes
Use `Wire.print()`, instead of `Wire.write()` which is intended only to output single bytes or byte arrays.

---
Tags: programming, lcd, wire-library
---


# Question
Title: Arduino Due ( Atmel Microcontroller) IC Heat up and led goes off
I was connecting L293d Motor Driver IC with an Arduino Due Board. May be due to wrong connections, but when I made the grounds common, the Arduino LED goes off and Atmel IC heats up. When I reconnect my Due board with my PC anytime, the LED turns on and slowly dims to off and Atmel IC fries up.

I wanted to repair it. What should I do?

I have checked the input voltage of the **AMS1117 3.3V regular IC** as 3.8 V, while the output is 2.2 V. If I externally give 5 volt at input again, the input voltages drops. The regulator is loading.

*I thought of replacing the regular IC? Will that work?*

Also I externally powered the Board with 3.3V by its pin labeled "3.3V" . The LEDs glow on and did not go off. But the Atmel Microcontroller IC becomes very hot.

What should I do?

# Answer
Motor driver boards exist to allow an MCU to *control* a motor without having to supply its power. If you try to power motors from the Arduino as well, they draw too much current and things get hot or damaged.

The 3.3v pin is only for supplying modest amounts of current at 3.3v *from* a 5v Arduino. You can not back-power the board with it. I don't know what happens if you try, but I bet it isn't good...
> 1 votes

---
Tags: arduino-due, hardware, debug
---


# Question
Title: Controlling a digital 12V addressable RGB led strip with Arduino?
I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

# Answer
~~The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.~~

---

Judging by this link you still just send 5V digital switching to the strip.

> The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.

Connect the Din (data in) to your Arduino pin directly. Of course, *also connect the Arduino ground to the ground pin*.

---

Also see this Youtube video. On the comments he says:

> These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.
> 4 votes

---
Tags: arduino-uno, led, rgb-led
---


# Question
Title: Best way to assign value to lot of variables
I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post. For some settings, I need to transfer 30 or so, different values over a single post request. And assign it to different type of variables.

```
so, from this:
192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

i need this:

uint8_t brightness = 100;
bool randomOrder = true;
uint16_t Delay = 1800;
uint8_t Position = 125;

```

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument. Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//values i need to set in a single post.
uint8_t settings0;
bool brightness;
uint16_t randomOrder;
uint8_t Delay;

void setup {
//relevant code that handels post request.
server.on("/testpost", HTTP_POST, []() {

String ZeroValue = server.arg("lenght");

int lenght = ZeroValue.toInt();

//this doesnt really work, but its a starting idea.
int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

for( int i = 0; i < lenght; i++) {

     String PresetSettings = server.arg(i);
     SettingsArray[i] = PresetSettings.toInt();
    }
});
}

```

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.

```
brightness = SettingsArray[1];
randomOrder = SettingsArray[2];
Delay = SettingsArray[3];
Position = SettingsArray[4];

```

# Answer
The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:

```
192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

```

And parse with:

```
brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

```

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.

```
String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

```

Or simply:

```
String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

```

Cheers!
> 1 votes

---
Tags: esp8266, variables, array
---


# Question
Title: Uploading a sketch causing an error message in Arduino Uno
avrdude:

> no programmer has been specified on the command line or the config file Specify a programmer using the -c option and try again

# Answer
On the "Tools" menu choose "Programmer:" and specify AVRISP mkII; be sure that you've also chosen the appropriate "Board:" entry for the Uno.
> 1 votes

# Answer
I fixed it. I just reinstalled the drivers.
> -1 votes

---
Tags: arduino-uno
---


title: MKR1000 not showing up on OSX

text:
# Question
Title: MKR1000 not showing up on OSX
I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also ➜ ~ csrutil status System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing

# Answer
> 2 votes
Double click the reset button on the board. Then it will show in the Port list :-)

# Answer
> -1 votes
See if this answers your question: https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-strarted-08bb4a

If not, go to your Board Manager (this happened to me too) and search MKR1000. There should be another install to do. Install that one and you should be good.

---
Tags: osx
---


title: GSM GPRS for sending an sms

text:
# Question
Title: GSM GPRS for sending an sms
I want to know if it is possible to send an SMS from a SIM900 using Arduinos to another SIM900.

**Problem**: When the gsm is connected to the network, it does not send an sms; my airtime balance remains the same.

Here is the code I used:

```
#include <SoftwareSerial.h>
SoftwareSerial SIM900 (9,10);

void setup()
{
   serial.begin(9600);
   SIM900.begin(9600);
   delay(5000);
}

void loop()
{
   sendSMS();

   while(SIM900.available()!=0)
     {
        Serial.println(SIM900.read());
     }
}

void sendSMS()
{
    SIM900.println("AT+CMGF=1\r");
    delay(100);
    SIM900.println("AT+CMGS=\"+27769384488"\r");
    delay(100);
    SIM900.println("Hello");
    delay(100);
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

}

```

# Answer
Yes, it is possible.

Your code doesn't show any sign of board powering on and initialization.

SIM900 has some LED that show status - make sure you are connected to GSM network.

Please check this tutorial: https://www.youtube.com/watch?v=RUGV\_64lQX8
> 1 votes

# Answer
I had worked on GSM long back ago and sometimes it becomes very difficult to debug the problem. However u need to just check whether the AT commands are being sent properly to the GSM module. I had tried using Software Serial but it did not work for me but when I switched to the usual Serial port it worked like a charm. Few things that you need to check are:

1. Check the baud rate of GSM module. Does it match with the baud rate of Software Serial.
2. Do a if-else check to see whether the commands are actually being sent to the GSM module. The println() returns the number of bytes written so you can do like this in your sendSMS() function.

> `int a; //To store the number of bytes written
>  a=SIM900.println("AT command to be sent");
> if(a)
> {
> Serial.println("Command sent");
> }
> else
> {
> Serial.println("Command not sent");
> }`

Now upload the code and open the serial monitor to see whether the command is actually being sent to the GSM module or not.

3. You also need to check whether the format of your AT command is correct. Because you need to send **\n(newline) and\r(carriage return)** at the end of every AT command to ensure proper operation. For this you need to read the response sent back by the GSM module after every command. This can be done by reading the Software serial port and the printing the response onto the Serial monitor.
4. You also need to check whether your GSM module has detected the SIM card. Usually this is indicated by an onboard LED that blinks after every **3 seconds**.

I think your code is pretty much correct but try to ensure that everything is setup properly as I said. Here is my code but I used Serial port instead:

> `void setup()
>  {
> Serial.begin(9600);
> delay(10000); \\For initialization purpose
> }
> void sendSMS()
> {
>  Serial.println("AT+CMGF=1");
> delay(5000);
>  Serial.println("AT+CMGS=\"Phone number with international code\"");
> delay(5000);
>  Serial.print("Hello");
> delay(5000);
>  Serial.println((char)26);
> delay(5000);
> }
> void loop()
> {
> sendSMS();
> do
>  {
> }while(1);
> }`

This code will send the SMS once so you need to reset the board for sending another SMS or you can remove the do while loop for continuous operation.You can adjust the delay accordingly.
> 1 votes

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


# Question
Title: A more elegant way to deal with timers without using delay()?
I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the `delay()` function because other tasks are supposed to run in the background which should not be affected by the delay.

```
  int sensorPin = A0;
  int ledPin = 13; //  pin for the LED
  int sensorValue = 0; // variable to store the value coming from the sensor
  unsigned long timer;
  int interv = 50;
  unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
  unsigned long millisaver;

  void setup ()
  {
    pinMode (ledPin, OUTPUT);
    Serial.begin (9600);

  }

  void loop ()
  {

    if (millis() > 2000) {
      if (millis() < 2050) {
        millisaver = millis();
        timer = (int) millisaver;
        Serial.println(timer);
      }
      if ( millis() > timer && millis() < timer + interv ) {
        sampleArray[0] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
        sampleArray[1] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
        sampleArray[2] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
        sampleArray[3] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
        sampleArray[4] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*5) {
        unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
        Serial.println(averageVal);
        millisaver = millis();
        timer = (int) millisaver;
      }
    }
  }

```

# Answer
> 2 votes
For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure ADC with Timer 0 Overflow and use every 20 measure only. But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.

As an auto trigger source can be used one of these:

* Free Running Mode
* Analog Comparator
* External Interrupt 0
* Timer/Counter 0 Compare Match A
* Timer/Counter 0 Overflow
* Timer/Counter 1 Compare Match B
* Timer/Counter 1 Overflow
* Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:

```
void setup() {
    Serial.begin(57600);

    // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
    ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
    ADCSRA |= _BV(ADATE); // enable auto trigger mode
    ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

    analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
}

int8_t sample_count = 0;
int8_t sample_index = 0;
uint16_t  samples[] = {0, 0, 0, 0, 0};
uint16_t sample_sum = 0;

void loop() {
    if (ADCSRA & _BV(ADIF)) {
        ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
        if (++sample_count == 20) {
            sample_count = 0; // reset sample_count, as we wan't every 20th

            sample_sum -= samples[sample_index];
            samples[sample_index] = ADC; // read value
            sample_sum += samples[sample_index];

            if (++sample_index == 5) { // reset index and count and send average
                sample_index = 0;
                Serial.println(sample_sum);
            }
        }
    }
}

```

# Answer
> 1 votes
You need to make a function which is pretty much completely self contained. Within the function should be a counter so it knows which sample it is on, and a timestamp to know when it should next run. The function should also inform the caller when it has a full sample set to process.

I haven't tested this (don't know if it even compiles) but something like this might work:

```
bool getSample(uint8_t pin, unsigned long *samples) {
    static uint32_t ts = millis();
    static uint8_t sampleNumber = 0;

    if (millis() - ts >= 50) {
        ts += 50;
        samples[sampleNumber++] = analogRead(pin);
        if (sampleNumber == 5) {
            sampleNumber = 0;
            return true; // We have 5 samples
        }
    }
    return false; // We don't have 5 samples yet.
}

// ... later ...

if (getSample(sensorPin, sampleArray)) {
    // Process Samples
}

```

# Answer
> 1 votes
You didn't say what you want to do with those samples. If you want to estimate the level of sound intensity, your whole approach is completely wrong. First, your sampling rate (20 Hz) is way too low: you should sample at least at twice the frequency of interest, typically at 8 kHz or more. Then you have to subtract the DC offset added by the microphone module, then square the result in order to get an instantaneous intensity, then low-pass filter to get a usable intensity reading. As Majenko said, if you average (or low-pass filter) the samples *before* squaring, you would detect zero sound.

I've written a sound meter program for an Arduino Uno that does exactly that, and it's available as a GitHub Gist: sound-meter.ino. It uses the auto-trigger mode as explained by KIIV, but with free running mode instead of a timer. This gives 9.6 kHz sampling rate.

---
Tags: sensors, arduino-nano, code-optimization
---


# Question
Title: Why am I always getting 48 with serial communication?
So I want to send some data from Matlab to Arduino. To verify that I am getting the correct data I am sending the data back to Matlab (since I get errors if I open the serial monitor, if there's an easier way to print debug messages let me know).

The problem is that I always get 48 back.

My matlab code:

```
arduino = serial('COM3','BaudRate',115200);
fopen(arduino);
fprintf(arduino,'%f',1);
fclose(arduino);

fopen(arduino);
disp(fscanf(arduino, '%f'))
fclose(arduino);

```

and my arduino code:

In the setup:

```
Serial.begin(115200);

```

In the loop:

```
delay(100);
myFunction();

```

In myFunction:

```
while(!Serial.available()>0)){}
int data = Serial.read();
Serial.println(data,DEC);

```

It seems like the 48 is an ascii code for something but it doesn't ever change when I change the 1 is the 3rd line of the matlab code to anything else.

# Answer
> Why am I always getting 48 with serial communication?

Your Arduino sketch (snippet) is reading a byte and writing the value, not the character. The value 48 in ASCII is the character '0'.

The below loop() function will echo all the characters received.

```
void loop()
{
  while (Serial.available()) {
     char c = Serial.read();
     Serial.println(c);
  }
}

```

This could be a good starting point when debugging what is actually written from MATLAB.
> 1 votes

# Answer
I don't know much about maylab, but you are sending a float to the Arduino where you read bytes and send characters back to matlab and read it as a float.

Try sending a single character from matlab and reading a single character back, %c.
> 0 votes

# Answer
May I recommend that you take a look at the data stream that MatLab produces? That will *show* you what it is producing, and therefore what code you should write in the Arduino to process it.

> If you had a second COM port on the PC, and a cable to connect your PC's MatLab port (COM3) to that port, you could use Arduino's Serial Monitor to show the data - make the Arduino Serial Monitor "pretend" to be the Arduino listening to MatLab.

But on the assumption that you don't have a second port or a NULL Modem serial cable, another alternative is to use a PC program such as "Serial Port Monitor" (I've heard good things about this program, although I've never used it). Apparently you can use it for 14 days to trial it.

Basically it presents a window (you'll want the Window called "Terminal", not any of the others) that shows what is being sent and received on the COM port - even data generated by another program. Shut down MatLab, start this program, tell it to listen to COM3, set the baudrate etc, press Go - then start MatLab again.

When MatLab sends data, you'll see whether it's sending "0.125" or "0y@/" - and assuming that you don't want to decode the latter, how to change your MatLab code so that it looks like the former! Then you can change the Arduino code to understand values like "0.125".
> 0 votes

---
Tags: serial, communication
---


title: Can I use a DAC with an L293D driver?

text:
# Question
Title: Can I use a DAC with an L293D driver?
I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot). It send values between 0 to 255 So I'm thinking... Whether this flow down here will work?

Joystick app --\> Bluetooth Rx --\> DAC --\> Vs pin of L293D. Or motor?

Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?

# Answer
> 0 votes
No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).

A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.

You *could* feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.

After all, that is the kind of job that small microcontrollers are designed for...

---
Tags: arduino-uno, motor
---


# Question
Title: Using softwareserial with a TFT, how can I use a variable to position cursor?
I have tried several different ways to do this, but in the line:

`myTFT.println("DS32(32,g,'Hello!',4);");`

where `g` is an int, it simply doesn't print. If I just replace the `g` with a value of any kind, all is well.

I'm using an Uno (well, an Orion board from Makeblock) and the Makeblock TFT.

All my other print lines work fine but of course, none contain variables.

# Answer
> 1 votes
Just split the print into three parts:

```
myTFT.print("DS32(32,");
myTFT.print(g);
myTFT.println(",'Hello!',4);");

```

---
Tags: arduino-uno, softwareserial
---


title: LED pin 13 not flashing properly

text:
# Question
Title: LED pin 13 not flashing properly
This is my first program on Arduino Uno (the starter kit), although I do have prior experience with programming (JavaScript, coding class last year 7th grade). It blinks the internal led (pin 13) in a Morse Code message:

> **.... . .-.. .-.. --- .-- --- .-. .-.. -..**
>
> ```
> . = dit();
>
> - = dah();
>
> (interval between parts of letter) = wip();
>
> (interval between letters/words) = wah();
>
> ```

Here's my code:

```
/*
 * Roman's first program
 * Decipher the message!
*/

int ledPin = 13;
int index = 0;

void setup() {
  //initialize pins as outputs
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
  int arrLength = sizeof(sequence)/sizeof(int); //however THIS works?!
  if (index < arrLength-1) { //0-based array
    index++;
  } else {
     index = 0; //restart the sequence once finished
  }
  if (sequence[index] == 0) {
    wip();
  } else if (sequence[index] == 1) {
    dit();
  } else if (sequence[index] == 2) {
    dah();
  } else if (sequence[index] == 3) { //because sometimes I the values are screwed past arrLength...
    wah();
  }
  //Serial.println(String(sequence[index])+" , "+String(index));
}

void dit () {
  digitalWrite(pinMode, HIGH);
  delay(300);
  digitalWrite(pinMode, LOW);
}

void dah () {
  digitalWrite(pinMode, HIGH);
  delay(900);
  digitalWrite(pinMode, LOW);
}

void wip () {
  delay(900);
}

void wah () {
  delay(2100);
}

```

Yet nothing is happening, except for the four/five startup flashes on the led when I restart it (red button). And yes, I saved and compiled.

# Answer
Well, mainly `digitalWrite(pinMode, HIGH);` looks suspicious. I though you called LED pin as `ledPin`

If you fix this, it should be working. As this one is working too, it's just simplified a little:

```
int ledPin = 13;
int index = 0;
const int8_t sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
int arrLength     = sizeof(sequence);

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
}

void loop() {
  Serial.println(String(sequence[index])+" , "+String(index));
  switch (sequence[index++]) {
    case 0: wip(); break;
    case 1: dit(); break;
    case 2: dah(); break;
    case 3: wah(); break;
  }
  if (index == arrLength) {
    index = 0;
  }
}

void dit () {
  digitalWrite(ledPin, HIGH);
  delay(300);
  digitalWrite(ledPin, LOW);
}

void dah () {
  digitalWrite(ledPin, HIGH);
  delay(900);
  digitalWrite(ledPin, LOW);
}

void wip () {
  delay(900);
}

void wah () {
  delay(2100);
}

```
> 6 votes

---
Tags: arduino-uno
---


title: Arduino Accessing a web page

text:
# Question
Title: Arduino Accessing a web page
Folks, I want to use my arduino with ethernet shield to access the following webpage "http://www.met.ie/forecasts/sea-area.asp" and take some information.

On the website it has a line "Small Craft Warning"- This is always either "In Operation" or "Nil".

Basically i want to hook up a RGB LED to the duino and if "Small Craft Warning" is "in Operation" i want LED to be Red, and if "Nil" LED can be green.

My issue is i cant figure out hot to go about getting the information from the webpage.- Can the arduino read this directly?

I am confident with arduino but this is my first web based project!

Any Tips or advice would be savage helpful Thanks

# Answer
As I commented on deltaray's answer, a regular expression library is overkill for finding a fixed string. There is a standard avr-libc function for that called strstr():

```
char * strstr(const char *haystack, const char *needle);

```

where `haystack` is the Web page and `needle` is the fixed string you are searching for.

There is an issue with this function though: in order to use it, you need to have the whole haystack in RAM. For a non-trivial Web page, this may not be doable on a small Arduino.

Below is a custom solution based on a finite state machine: the parser can be in a number of different states:

* state 0 = waiting for the 'S' of "Small Craft"
* state 1 = waiting for the 'm' of "Small Craft"
* etc...

The state is actually an index in a character array representing the string we are looking for. Each time the parser finds the expected character, it moves to the next state. Otherwise it moves back to state 0. There is a small kludge though: when in the state *waiting for the 'N' of "Nil"*, if it doesn't get an 'N', it moves to the state *waiting for the 'I' of "In Operation"* and tries the match again. This way it can look for both the possible strings at once. Also, once it got the full preamble "Small Craft Warning: \</b\>", if it gets something invalid, it moves to an extra state called *INVALID* instead of state 0.

Here is the code:

```
// Possible return values of parse_forecast().
// The last three are sticky.
enum parse_state {
    NO_PREAMBLE,        // no complete preamble seen yet
    PREAMBLE_COMPLETE,  // preamble just completed
    PARTIAL_NIL,        // received preamble and start of "Nil"
    PARTIAL_IN_OP,      // received preamble and start of "In Operation"
    COMPLETE_NIL,       // result = Nil
    COMPLETE_IN_OP,     // result = In Operation
    INVALID             // valid preamble followed by invalid data
};

parse_state parse_forecast(char c)
{
    // position:      0                        25   29            42
    const char T[] = "Small Craft Warning: </b>Nil\0In Operation\0";
    static size_t i;  // T[i] is the character we expect next

    if (T[i]) {  // non-sticky state
        if (i == 25 && c != T[i])
            i = 29;      // switch to "In Op" branch
        if (c == T[i])   // found expected char
            i++;         // wait for the next one
        else {
            if (i < 25)
                i = 0;   // reset to start of the string
            else
                i = 42;  // invalid state
        }
    }
    return i <  25 ? NO_PREAMBLE :
           i == 25 ? PREAMBLE_COMPLETE :
           i <  28 ? PARTIAL_NIL :
           i == 28 ? COMPLETE_NIL :
           i <  41 ? PARTIAL_IN_OP :
           i == 41 ? COMPLETE_IN_OP :
           INVALID;
}

```

With this you do not need to store the Web page in RAM. Instead, you feed the parser one character at a time and, at the end, check the return value. You expect it to be either `COMPLETE_NIL` or `COMPLETE_IN_OP`.

Implementation detail: there are three NUL characters in the template string, at positions 28, 41 and 42 (the last one is implicit). They correspond to the three possible "sticky" states.
> 1 votes

# Answer
Unfortunately that text is delivered as part of the complete web page and not, for example, an AJAX request.

> Do you supply an RSS feed of your forecasts?
>
> *This is not something we provide at present, although we hope to do so in the future.* Source.

Your only option is to scan through the whole page looking for the text strings.

This is a little dangerous as the page could, for example, contain the phrase as part of a help file and give you an incorrect status reading. I wouldn't set to sea on the basis of your LED.

Bí cúramach!
> 0 votes

# Answer
To add to Transitor's answer, while not guaranteed to work perfectly, you can always try to narrow down the page's source by only searching the component the text is in which should hopefully work. (unless they redo their website)
> 0 votes

# Answer
I think this can be accomplished with the use of a few libraries. Also, I'd recommend the use of a third color to let you know when your program has encountered an unexpected condition, such as couldn't retrieve the webpage or couldn't find "Small Craft Warning" in the page or if the value for that attribute is something unexpected.

So first you'd want to use the Ethernet library that comes with the Arduino IDE. There is even an example sketch that shows you how to use it to download a webpage. Make sure you parse the status returned from the webserver to ensure its giving you a 200 HTTP status code and produce an error if it does not or if the connection fails.

As for parsing the webpage itself, you might try this regular expression library that Nick Gammon wrote. Just have it search for the line with Small Craft Warning and then parse that line as a string as test for matches against the strings you are expecting to find or erroring out. Or you can use additional regular expressions to match your expected values once you find the right line. Remember to make the LED show an error color if it doesn't find the line or an expected value.

Just talking about this makes me want to try it. ;-)
> 0 votes

---
Tags: ethernet
---


# Question
Title: use more no of batteries for more current for servos,why using motor shield?
motor driver is for current amplification.for that we could connect more batteries to servos to get more current.but why are we using motor shields?

# Answer
> 2 votes
The motor shield is useful because you cannot pass the required amount of current through Arduino's microcontroller without blowing it up.

Of course you don't need to use the motor shield if you create a similar circuit of your own that performs the same task.

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: Reading an MCP23S17 I/O expander port with the Arduino SPI library
I am trying to read an MCP23S17 I/O expander port B with the Arduino SPI library. The following example is simple as possible, and I still can not get it to work.  The setup is an MCP23S17 I/O expander on a Teensy LC controller. MCP23S17 port B pins are alternately grounded and energized. I confirmed the pin voltages with a multi-meter. Variable portBState is a bitwise reading of port B, and printed.

Expected output is:

```
10101010

```

Actual output is:

```
11111111

```

Sketch:

```
#include <SPI.h>

const uint8_t ADDR = 0x20;      //MCP23S17 address, all 3 ADDR pins are grounded
const uint8_t OPCODE_READ  = (ADDR << 1 | 0x01); //MCP23S17 read command

const uint8_t IODIRB = 0x01;
const uint8_t GPIOB  = 0x13;

uint8_t portBState = 0;                 //bit wise

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

    pinMode(SS, OUTPUT);                //configure controller's Slave Select pin to output
    digitalWrite(SS, HIGH);             //disable Slave Select
    SPI.begin();

    //IODIRB register is already configured to input by default

    SPI.beginTransaction(SPISettings (SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE0));
    digitalWrite(SS, LOW);              //enable Slave Select
      SPI.transfer(OPCODE_READ);        //read command
      SPI.transfer(GPIOB);              //register address to read data from
      portBState = SPI.transfer(0);     //save the data (0 is dummy data to send)
    digitalWrite(SS, HIGH);             //disable Slave Select
    SPI.endTransaction();               //release the SPI bus

    Serial.println(portBState, BIN);    //should print 10101010
}

void loop() { }

```

Why is the output not "10101010"?

The controller is Teensy LC (3.3 volts) on Arduino 1.6.7.
SPI library: https://www.arduino.cc/en/Reference/SPI
More links in the comments below (I don't have enough reputation points to post more links in the question).

# Answer
It's working now. Here is what was missing: A yellow jumper from the micro-controller MOSI pin to the MCP23S17 SO pin. So the read command can travel from micro-controller to MCP23S17.
> 0 votes

---
Tags: sketch, spi
---


title: Arduino project feasibility

text:
# Question
Title: Arduino project feasibility
*<sup>**Question completely rewritten**</sup>*

Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.

However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

* a non-latching Hall sensor is to be connected to Analog 0, `analogRead()` to return a \[0,1023\] value, used as a proximity sensor. This should be straight forward.

Question →

* while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

# Answer
It's perfectly doable. As Chris Stratton puts it, it's all about implementing *non-blocking* serial communication:

* whenever you receive a character, you store it in a buffer
* whenever you have a complete command in the buffer, you process it and reset the buffer

For a line-oriented protocol, it may look something like:

```
/* Process incoming characters if any. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];  // incoming command
    static int length = 0;           // command length

    int data = Serial.read();
    if (data == '\r') {              // complete command
        buffer[length] = '\0';       // terminate the string
        if (length)
            exec_command(buffer);    // process
        length = 0;                  // reset buffer
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;     // buffer incoming character
}

```

For a more complete example, you may want to take a look at this simple Arduino command line interpreter. You connect a terminal emulator to the Arduino at 9600/8N1, type the "help" command and it displays:

```
mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

```

You can use it as a template, replace existing commands or add new ones (the interpreter is just a long `if ... else if ...`) and – since it's all non-blocking – add whatever you want to `loop()`.
> 3 votes

---
Tags: sensors, usb, arduino-motor-shield
---


# Question
Title: How can I replace pulseIn with interrupts?
I have an HC-SR04 sensor and I need to get the distance from it. I use this code:

```
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration=pulseIn(echo, HIGH, 24000L);
cm=duration/2/29.1;

```

Pulsein takes too much time and I would like to use interrupts to prevent code from being blocked. From the beginning, I had no idea how to do it. I did not want to ask this question without trying on my own so here is my miserable attempt:

```
 while(digitalRead(echo)==LOW){
 }
if(digitalRead(echo)==HIGH){
      lowTimer=millis();
}
while(digitalRead(echo)==HIGH){

}

if(digitalRead(echo)==LOW){
   duration=millis()-lowTimer;
}

```

Obviously, this does not work. I don't know if I am on the right track, but I do know that even if this worked, it would still block my code for a long time. Can someone help me, point me in the right direction? Please don't just write it for me - I want to learn. I would like someone to point me to the right direction till I get it. Thank you!

EDIT:

I tried on of the suggestions:

```
unsigned long duration;
int cm;
const int echo = 24;
const int trig = 22;
bool doPing=true;

void setup()
{
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    if(doPing){
        ping();
        doPing=false;
    }
    read_pulse();
    if(duration!=0){
        cm=duration/29.1/2;
        Serial.println("cm: "+cm);
        doPing=true;
    }
    delay(2);
}
void ping(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
}

void read_pulse()
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(echo);      // current pin state
    duration = 0; // default return value

    // On rising edge: record current time.
    if (last_state == LOW && state == HIGH) {
        rising_time = micros();
    }

    // On falling edge: report pulse length.
    if (last_state == HIGH && state == LOW) {
        unsigned long falling_time = micros();
        duration = falling_time - rising_time;
    }

    last_state = state;
}

```

This does not print anything to my serial monitor. Is there something I am missing?

# Answer
You do not want the reading of the incoming pulse to **block** your program execution. This is the very key requirement: you want a *non-blocking* pulse reading. You can write a non-blocking replacement for `pulseIn()`, but you will have to use it differently. You cannot expect a non-blocking `pulseIn()` to return the pulse length whenever you call it: instead, it would return that value *only* when you call it right after the pulse falling edge. On all other circumstances it will return a dummy value meaning “the pulse is not finished yet, thus I cannot give you its length right now, please call me later”.

Below is an example of a function implementing this approach. You have to call it on every loop iteration: the more often you call it, the better resolution you will have. This function uses 0 as the dummy value meaning “no answer available right now”:

```
/*
 * Non-blocking pulseIn(): returns the pulse length in microseconds
 * when the falling edge is detected. Otherwise returns 0.
 */
unsigned long read_pulse(int pin)
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(pin);      // current pin state
    unsigned long pulse_length = 0;    // default return value

    // On rising edge: record current time.
    if (last_state == LOW && state == HIGH) {
        rising_time = micros();
    }

    // On falling edge: report pulse length.
    if (last_state == HIGH && state == LOW) {
        unsigned long falling_time = micros();
        pulse_length = falling_time - rising_time;
    }

    last_state = state;
    return pulse_length;
}

```

A better approach, but harder to implement for a novice, is to use interrupts. Chris gave you a pointer to Nick Gammon’s tutorial on interrupts. This is definitely a good reading. But you will also have to dig into the data sheet of the ATmega328P microcontroller. It's a little bit daunting, but a must read if you go into low-level programming. If you follow this path, I suggest you look at the “input capture” capability of Timer 1 (chapter 20, section 20.9). This is a feature of the timer that can have it automatically save a timestamp whenever some external pin changes state. You then use the input capture interrupt to alert the program when an edge has been detected, and your interrupt service routine can read the automatically saved timestamp. Using this approach, you can have extremely accurate pulse length measurements, independent on how fast your program goes through its `loop()`.
> 3 votes

---
Tags: arduino-mega, interrupt, millis, pulsein, hc-sr04
---


# Question
Title: Do I need to supply the 12V connection to an HDD
I'm working on trying to control a hard drive with an Arduino Uno, but I'm having trouble with the power supply. From what I know, both the Molex Mate-n-Lok and the new SATA connectors both have 2 grounds, a 5V and a 12V power in. I'm wondering what the purpose of the 12V power supply is. I suspect it's used to drive the motor but I'm not sure.

# Answer
> 5 votes
Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on Google Books \- the 12V supply is for the spindle motor, and it says:

> Spindle motors, particularly on the larger form-factor drivers, can consume a great deal of 12V power.

# Answer
> 4 votes
3.5" hard drives require 12V and 5V for the motor and logic respectively. SATA ones may also require 3.3V for the logic. Most smaller laptop drives (2.5") only require 5V and 3.3V. Some 2.5" drives also require 12V.

You will not be able to interface a SATA hard drive to an Arduino without some kind of SATA hard drive controller, which you could possibly build using a fast FPGA (in which case why would you bother with an Arduino?). For SATA-I (way out of date now) you need to generate a 1.5Gbps LVDS (Low-Voltage Differential Signal) data stream. For SATA-3.2 that is now 16Gbps. Impossible on an Arduino.

PATA (Parallel ATA) is more realistic, although you need a lot of pins since it is a 16-bit parallel interface. Timing is less critical since it is synchronous with the read / write strobes.

---
Tags: power, pins, hardware
---


# Question
Title: How to run stepper motor at its maximum speed
I am running a stepper motor using arduino and IC l293d. What is the maximum possible speed of rotation that I can achieve with the IC and what should be the applied voltage for the same? Earlier, I got the optimum rotation with a step size of 30 at 7V. I want to increase the step size. What should I do?

# Answer
As this link states:

> Stepper motors are normally used for positioning, and are not known for their speed.

However, the link is to an on line stepping motor speed calculator.

As for the size of the step, this is a function of the way the stepping motor is built. Some controllers / stepping motor combinations can do half steps or micro steps. Disable these feature for the fewest number of steps per revolution.

These are some of the basic concepts which deal with practical stepping motor applications. As speed increases, other factors come into play. For example, resonance and inductance.

In this paper resonance is discussed:

> If a rigidly mounted stepping motor is rigidly coupled to a frictionless load and then stepped at a frequency near the resonant frequency, energy will be pumped into the resonant system, and the result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

> An important consideration in designing high-speed stepping motor controllers is the effect of the inductance of the motor windings. ... The inductance of the motor winding determines the rise and fall time of the current through the windings. ...
> 2 votes

# Answer
The speed of the stepper motor (assuming you measure it in RPM) will depend on many factors. I am not sure how the "30 step size at 7V" you mention is relevant.

IMHO, the most important parameters are

1) physical parameters of motor (steps per revolution, rated voltage, motor intetia)

2) Load on the motor

3) software implementation

Normally you shouldn't be able to affect 1( if you are looking like most arduino's developers you should be looking at things like this. i.e. 200 steps per revolution, 5-12VDC and a few tens to hundreds of g\*cm^2 or motor inertia.) or 2 (although with higher loads lower velocities can be achieved, normally you select the motor based on the load and not vice versa).

Therefore you are left with Software implementation. Things here can get messy very quickly depending on how experienced you are and what you want to do. e.g. The arduino Stepper library is simple and you can set parameters but it is blocking (i.e. you can't do anything else until movement is completed, or interrupts are used).

If you want to get your hands dirty (and your head messed up ;-/ ) you can looks at

* Arduino timers
* micros(), and millis() for updating the steps yourself. (Have a look at here and here - shameless plug)
* pin registers (for increasing speed) here.

My experience is that normally you can get up to 150 \[rpm\] easily. Theoretically you should be able to go higher but the uC should be doing pretty much nothing else.
> 1 votes

---
Tags: arduino-uno, motor, stepper
---


# Question
Title: How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters?
I've got an Adafruit Trinket microcontroller set up using this USB keyboard tutorial, and it works great.

I'd like to set up my project to type a shruggie ( `¯\_(ツ)_/¯` ) when I press a hardware button.

My naive solution was:

```
TrinketKeyboard.print("¯\_(ツ)_/¯");

```

But that only printed the underscores, parentheses and slashes, not the "hands" or the "face."

Is there a standard keyboard input method I could use so this device, when plugged into any Mac, will type out a string that includes Unicode (specifically Katakana) characters?

An *ideal* solution does not require configuring the machine before plugging this widget in, and doesn't require changing state on the machine -- although I'll take what I can get! :) (e.g., configuring Japanese keyboard support and toggling input source -- all of which is done blind since the computer can't give feedback to a lowly keyboard -- is un-ideal.)

# Answer
It depends entirely on the operating system you are working with. The Arduino is merely a keyboard. It sends keystrokes. Whatever keystrokes your operating system will accept to generate unicode character are the keystrokes you have to program the Arduino to send. Most likely there is some combination of ALT-GR + keypad numbers that will do the trick.

For OS X it looks like the only possible way is to change the input settings on the computer to allow "Unicode HEX" entry.

There is no other way of doing it. As I say, the Arduino is just a keyboard. It is subject to the same rules as any other keyboard. You can only type things that can be typed. If you need to type other things the OS has to be made aware that you want to type those things through settings.
> 2 votes

# Answer
You could hack it.

1. Make it press CMD+SPACE
2. type `terminal.app`
3. press ENTER
4. type `echo -e
"\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy`
5. press ENTER
6. press CMD+Q
7. press CMD+V

though the user would see a terminal window for a second.
> 2 votes

---
Tags: usb, adafruit, keyboard
---


# Question
Title: Is Adafruit Arduino Feather M0 WiFi compatible with Adafruit Music Maker shield?
I want Arduino to receive MP3 by WiFi (from iPhone), and then send to Music Maker codec and amplifier.

I want to use Arduino IDE and library software from Adafruit for the Music Maker, so I need an Arduino board 100% compatible with the library for Music Maker.

# Answer
No, it is not. Adafruit Feather boards are only compatible with Feather 'wings' and not Arduino shields.
> 0 votes

---
Tags: wifi, shields, hardware, adafruit, audio
---


# Question
Title: How can I determine how many bytes an I2C master read from my Arduino acting as I2C slave?
I have an Atmega328 programmed using the Arduino software and libraries (but is standalone on on a board in the TSOP package) without bootloader and with ISP programming). I am using the Wire library to act as an I2C peripheral, where I implement (and register) the `requestEvent` and `receiveEvent` callbacks.

Is it possible to determine, either during the `requestEvent` callback or after it at some point, how many bytes were read by the master before it sent a NACK?

# Answer
> 1 votes
You can't.

The master will have to inform the slave how many bytes to transfer, or the master will have to query the slave how many bytes there are to receive.

---
Tags: i2c, atmega328, wire-library
---


# Question
Title: I want to pour 500ml of Water in jar with Arduino water flow controller?
I want to pour 500ML of water with Arduino water flow controller with maximum accuracy. How will I get the maximum accuracy with this sensor? Could someone can give suggestion for accuracy or any other sensor that i can use?

# Answer
The flow meter you specified, YF-S201 Hall Effect Water Flow Meter (datasheet) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". **Note that this only measures the rate of flow, it is not a valve and so does not control the flow.**

Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. **Cumulative errors are highly undesirable, because they are difficult to detect and compensate.** You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.

If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.

If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (*load cell*). First, measure the *tare weight* of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's *offset error* is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about *gain error* at 500mL and *repeatability* of the load sensor. **This approach does not have cumulative errors.**

You have not specified what kind of valve you will use to control the flow. If you use a *solenoid value*, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.

Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a *proportional valve* instead of a solenoid valve. Start with a fast flow rate when net weight \<400g and then switch to a slower rate as the jar reaches its target weight.
> 1 votes

# Answer
I suppose that you already found a solution. If you haven't, one inexpensive way for the Arduino to sense when the water reaches the desired level is to drill two thin parallel holes into the container (using a wire gauge drill bit, provided you're not using glass or something difficult to drill) slightly below the "trigger point." Then, you can insert two thin strands of conductor so that they protrude a millimeter or less inside the container(consider something like graphite 0.5 mm pencil leads to prevent corrosion). You'll need to seal the holes using epoxy. If you make a voltage divider and put these two pencil leads in the place of the second resistor, you can measure the resistance change (using an Arduino analog input pin) when the pencil leads are "connected" by the water. Once you find the ADC value for the "water full" state of your connection, you can make the Arduino turn off the flow when this value is detected. You should place the pencil leads below the "trigger point" so that you can experiment with different delay periods between sensing the water and turning the flow off (to compensate for the water that remains in the pipe "downstream" the flow controller. I've used this approach successfully to measure flow rate, but I can't guarantee it would work in your application.
> 1 votes

# Answer
You haven't specified what level of accuracy you are aiming for so I have assumed 0.01ml.

What ever solution you go for you will also need an accurate temperature and pressure sensor, because these will affect the density of the water. Each individual sensor you use has a degree of error associated with them. You would nee to calibrate each sensor to establish what level of error each individual instance of a sensor has.

Weight would seem to be the best solution. Surface tension could affect a flow metre or a contact sensor. I have to be honest I don't see how an ultrasonic sensor could give you any degree of accuracy. With a weight sensor you would need to establish the dry weight of the container then pour the liquid in until the desired volume was achieved. A quick response to close the very end of the inlet pipe would be required to prevent un-necessary drips.

As to marking the container, are you using some computer controlled marking tool, because if you are just drawing on the side with a Sharpie you may as well use a measuring jug. :)

You should be able to get a weighing PCB, a pressure and temperature sensor off any of the usual electronic sites to suit you budget and the libraries will be on Git hub.
> 0 votes

# Answer
Another option is to use a stepper motor and a Peristaltic Pump (or IV pump). You can use this to control the flow rate AND volume. For speed you need to make the motor run faster and for volume just run the stepper motor x times to get x volume. I do not know how precise it is. Good luck with what ever option you pick.
> 0 votes

---
Tags: arduino-uno, sensors
---


title: Power measurement on Pins

text:
# Question
Title: Power measurement on Pins
as a project I have to build a sensor hub based on Arduino. I need a couple of sensors like gyroscope, barometer, etc. This is no problem so far. The problem arises when it comes to power measurement. We have to measure the power consumption of the Arduino AND all the sensors. Sure, I could use a sensor like the Adafruit INA219 sensor. But this only gives the total consumed power of the Arduino and the sensors.

Is it possible to measure the energy, say, for every pin on the Arduino?

# Answer
"Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with."

"it possible to measure the energy, say, for every pin on the Arduino?"

You ask if it possible to measure the energy- yes it is-or at least an approximation. The basic solution is as follows. Suppose you want to find the energy consumed by some component at one pin. Energy is measure in joules. For an electrical circuit we the amount of energy (consumed in 1 second) is given by the formula

joules=current X voltage. Lets consider the case with one sensor first , lets refer to this as sensor A. The amount of energy that electrical component consumes in some time duration is by sensor A is:

joules (use by sensor A)=current X voltage X time duration sensor A is on

Now to make this formula applicable to your answer- we can replace voltage by the average voltage, and current by average current, since this is mathemtically equivalent, that the component is on for, and the time duration would be the time the component is on for. So the equivalent formula that can be used is

joules= average current X average voltage of sensor A during time duration X time duration sensor A is on

So for example if the sensor is only ever used for 50 minutes for all time throughout your project- and the sensor is turned on at the arduino pin for 1 second for every minute of that 50 minutes then the energy used by that sensor on that specific pin is equivalent to leaving the pin on for 50 seconds at the average voltage and average current of that sensor. Say the average voltage is 3v then the energy and average current is 20ma. Then the energy used by that sensor is thus 3v\*0.02amps\*55 seconds=3.3 joules.

Thus to get the total energy (if there were two sensors A and B) you would just need to sum

(joules (use by sensor A)= current of A X voltage of A Xtime duration sensor A is on)+(joules (use by sensor B)=current of B Xvoltage of B Xtime duration sensor B is on.)

Similar formula for more sensors.

To sum up- basically you would need your arduino program to keep track of how long each sensor pin is on (assuming high voltage turn on the sensor and makes it use power, low voltage turns off the sensor or make it use no power) for each of the time duration in the formula for the duration of the project, you would need an estimate of the average voltage and current (e.g. from data sheet) or another way. Then you would need to use the formula in your code to compute the energy used by each sensor and the total energy. If you have a way to measure the voltage and current fast enough then you could use them measurement instead of using average value as explained above-but I guess using averages is the easiest way to do it.

.
> 0 votes

---
Tags: arduino-uno, adafruit
---


# Question
Title: Is Arduino stable enough to use it for a door lock?
I want to replace my door lock with an one made with an Arduino and a servo, but I'm not sure if the platform is stable enough to use it for something like this.

If I do everything right (code, connections, constant power), could I trust in this?

# Answer
> 15 votes
> I'm not sure if the platform is stable enough to use it for something like this.

Absolutely it is. As I describe in my post about an RFID door lock I use a Uno (and some additional parts) to unlock my door.

Since writing that I improved the software as described here so you can reprogram the valid list of cards "on the fly" (without uploading new code) as the valid cards are stored in EEPROM.

My system has been operating for over 5 years without any problems, except once when there was a brownout in the area and I had to power cycle the system (possibly the RFID reader failed and not the Arduino).

My system "fails shut" so it keeps the door locked in the event of a power failure. However I have alternate ways of leaving the building in the event of a power failure combined with a fire.

You are talking about a servo rather than an electric strike. That is likely to be the weak point, and not the Arduino as such. You would need to ensure it was powerful enough to do whatever-it-is you are planning to do, and that it had suitable drivers (eg. MOSFET or driver board).

My system gets used dozens of times each day. We never have a problem with it.

# Answer
> 11 votes
If you want to use an Arduino in this sort of environment, there are a few things to watch out for:

* Heat (usually from sunlight striking the enclosure). This could be relevant for your project, depending on the installation and location of the door. Choice of enclosure material, colour and finish can all affect this.
* Rollover of millis() (see http://playground.arduino.cc/Code/TimingRollover). After 55 days, the millis() function on the Arduino rolls over and resets back to 0. Depending on if/how you use this, it may affect you.
* Power supply stability. If you choose to power your Arduino directly from 5v, ensure that it is a smooth stable supply. I've had noisy power supplies cause some weird resets and glitches.
* Water ingress. Again, this depends on location. Don't forget to account for condensation and frost (if applicable).
* Flyback from relay switching and locking solenoids. Add flyback diodes to relay coils and solenoids to stop any flyback voltages killing your control circuitry. See https://en.wikipedia.org/wiki/Flyback\_diode

I've run in to all of these issues across various Arduino projects. They may not cause the system to fail completely, instead causing strange behaviour.

If you design your system to account for all of these factors, then it is absolutely reliable enough to run something 24x7x365.

# Answer
> 7 votes
If you can *guarantee* that your hardware and software skills are *impeccable* then you can certainly trust the MCU on the board. After all, the ATMega chips aren't toys, even though many people around here seem to treat them as such. They are a professional industrial product.

Of course, this is assuming that the Arduino you have is genuine and not some cheap Chinese knock-off with gawd knows what on the board.

# Answer
> 4 votes
Replying to Majenko's answer with more depth. The limits of the Arduino hardware depend on the ATmega CPU it's built around (I suspect you'll be directly migrating from Arduino to the final PCB).

> but I'm not sure if the platform is stable enough to use it for something \>like this.

Thus it may be worth considering for you to read through the data sheet. I'd read through it and look at the parameters which could affect your project. For example, the ATmega is only designed to work properly within certain temperature ranges (so this may affect your lock if it's outdoors in the cold). If you're relying on the built-in timer for something in your project, then that can get affected by temperatures, for example — as opposed to using a quartz crystal for reliable timing.

So you'd need to think how your project can fail with the parameter limits of the hardware components. For example, if you're activating the door lock with a secret code stored on external memory, then the memory used may get corrupted when it gets near a magnetic field.

# Answer
> 2 votes
To add to the already good advice so far.

Safety and security wise you need to plan and anticpate for failure. An electromechanical lock or your power supply are hardware wise probably more likely to cause issue than the Arduino board, just watch for back emf and use a flyback diode or snubber as mentioned if required. There may be issues though in your code being stuck in a loop or say card reader or contact faults and so on, this may require a simple on-off at best.

Consider using a battery backed power supply for short blackouts or brownouts.

Then consider your lock type and what will happen in an emergency or with a fault.

Locks such as a strike or mortice lock allow you to use standard door hardware so you have the capability to use a free handle egress out so you won't be trapped in an emergency. You can then also fit a key barrel so if the lock has failed you have a backup way of entry.

With either type you can then have a fairly good balance of safety and security, if you set it up as fail secure your house will not be vulnerable in a power outage or PSU fault whilst also not trapping you inside.

In a commercial setting fail safe is commonly used on non secure common areas and rooms but preference for a residential front door is fail secure.

Other lock types such as maglock, drop bolt, V-Lock, hook and loop and automatic doors among others do not have purely mechanical methods of using the door in a fault so are harder to use in a residential setting and may need emergency breakglass or stop buttons to cut power on the inside and keyswitch or pincode unit on the outside in case of fault if no other entry point available.

Maglocks for example are fail safe only and will open once power is off,potentially leaving your home vulnerable, so need fairly significant battery backup. However I have also experienced issues where a door controller has failed and will not release, as it is a maglock the power has to be broken and there was no method of release externally and no other point of entry.

I would suggest a strike or electronic mortice lock for your purpose and suggest an off the shelf unit, it will be far more reliable long term.

---
Tags: servo
---


# Question
Title: Debugging a RadioShack Arduino motor/sensor shield
I bought a cheap "Make" kit at RadioShack, which includes some sort of proprietary Arduino Uno compatible motor/sensor shield. Naturally, the documentation is pretty bad. The documentation and Arduino code for the kit is here:

https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit

It includes a circuit schematic (2770168-CorePCB\_schematic.pdf), but I'm still having trouble mapping the pins to the Arduino's pins. Can anyone help me make sense of this?

What I've made out so far is the shield's screw terminals appear to be connected to quadruple h-bridges. However, there are several other pin headers that I can't quite make out. I think it also directly exposes 4 of the Uno's ADC pins and 4 DIO pins. There are four pins for dual IR line sensors, but there's a lot of circuitry between these and any Arduino pins. Almost everything feeds into a DC6688F2SCN chip, but I can't find a datasheet anywhere, so I have no idea what it does.

The manual says jumpers on J16 need to be removed in order to connect to the Uno over USB, so it looks like I can't use the shield with the board and debug via USB at the same time. Is this board worth investigating or should I trash it?

# Answer
There is a bit of info on the DC6688F2SCN here: Chip Selection Guide, but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.

If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.

That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the Bs can do a full Amp.

The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.
> 1 votes

# Answer
A google search for DC6688F2SC returns spec sheet under Dragonchip (here). It's actually a rather nice chip when you look up the specs on it.
> -1 votes

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: How to control cold to hot (blue to red gradient) RBG LED strip/bulb with a rotary encoder?
I'm doing a project for university and I am struggling to code and set up a rotary encoder that can control hot-cold variations. Much like the idea of communicating temperature selected by turning a dial. I would either like to control a single strip of RGB LEDs or a single bulb (changing and fading between colours at the same time).

I would like to have the dial turn from 0 - 180 degrees and relate to intense blue changing to intense red and all the colours in between as increments.

I have an Arduino Uno.

Thank you!

# Answer
> 0 votes
Well as I understand you want to use a rotary encoder ? Rotary encoder can turn freely. Which you can read via arduino easily with a library. You can count a number(let's say x) from 0 up to 255, and write that number to one of the color. For the other color write 255-x so when blue is fading down the red is increasing. But I suggest you to use a potentiometer which has a limited turn (about 270 degrees). Connect it to arduino's one of the analog read pins. It will give you a 10 bit value which is between 0-1023 . You can scale this down to 0-255 range with map function. \[Example: "x = map(x,0,1023,0,255);" \] after that just follow the same process as before.

# Answer
> 0 votes
http://playground.arduino.cc/Main/RotaryEncoders is where the rotarty encoder libraries are. From there you can use PWM on the outputs as said. There are also some addressable RGB strips/modules that incorporate a driver IC such as adafruit neopixels where you can just write values for colour and brightness to the IC fairly simply, depending on your level of electronics knowledge.

---
Tags: led, rgb-led, rotary-encoder
---


title: Will this SensorHub work?

text:
# Question
Title: Will this SensorHub work?
As a project I have to build a SensorHub with multiple sensors. I am relatively new to the Arduino and circuit world, so I need a little help.

The Goal is to build hub with multiple sensors and to be able to measure power consumption of the entire thing and log the data from all sensors.

So I came up with the following part list:

* Arduino Uno (Rev3)
* Adafruit 10-DOF IMU L3GD20H + LSM303 + BMP180
* Adafruit Ultimate GPS v3
* Adafruit VCNL4010 Proximity and Light sensor
* Adafruit INA219 High Side DC Current Sensor Breakout
* Adafruit MicroSD card breakout board
* of course breadboard, powersupply, calbes, etc.

Everything is connected like this:

My question is now if this thing will work as I expect. With the 10-DOF, GPS and VCNL4010 I'm pretty sure. They work all with I2C on different addresses and all of them need 5V.

The question is now if I can measure the needed power with this setup. Or does the INA219 need power to be able to get the power to the Arduino? Do you see any problems?

# Answer
The INA219 breakout will pass current, even if it doesn't receive any power itself.
> 0 votes

---
Tags: arduino-uno, sensors, power, adafruit
---


title: Turning my GPS logger shield off and on

text:
# Question
Title: Turning my GPS logger shield off and on
I have a Sparkfun GPS Logger Shield and I want to save power by shutting it off when I do not need GPS readings. Now reading the hookup guide it says that the "EN" pin can do this: "Active-high chip-enable – pull low to reset or turn off".

I wanted to ask some advice as to what this actually means and how I safely go about it. Is it as simple as:

```
pinMode(pin, OUTPUT);

//turn off
digitalWrite(pin, LOW);

//turn on
digitalWrite(pin, HIGH);

```

Where the pin is a digital pin on the Arduino and it is connected to the "EN" pin of the GPS shield.

# Answer
Yes, it is as simple as that.

However, since the pin is pulled up already you could also do this:

```
pinMode(pin, INPUT);
digitalWrite(pin, LOW);

// Turn off
pinMode(pin, OUTPUT);

// Turn on
pinMode(PIN, INPUT);

```

That then emulates an Open Drain pin which means you're not actively driving the pin when turned on, only when turned off.

Personally I prefer system that are active low not active high, and are pulled down by default (normally off) so that you don't waste power driving the pin in order to save power (it's kind of silly really) - you drive the pin to turn on and let the pin float to turn off (especially good with deep deep comatose sleep on some MCUs where the IO pins all switch off).

However the designers of this module decided otherwise, so you're stuck with driving the pin LOW to make it sleep.
> 2 votes

---
Tags: power, gps
---


title: Struggling with SD card read on Arduino

text:
# Question
Title: Struggling with SD card read on Arduino
I'm attempting to read data from my SD card, but I have strange behavior and can't figure out why this is happening.

I'm using **CardInfo** from the Arduino example and am trying to read the data from my SD card.

I'm faced with two different problems, but maybe they can be related:

**1:** If I format my SD card from my Mac (FAT32), if my card is still empty, the program can read my card and output the right information. But if I add data from my Mac to the SD Card, card.init never initialise, and my data are never read (because of the hidden files). If I remove those hidden files, but let only the expected files be, the program never find them, like if my card was still empty. I don't know how to handle this.

**2:** From my Arduino, if I feed the card from the 3.3 V output, I get the

> Card type: SD2 Could not find FAT16/FAT32 partition. Make sure you've formatted the card

It only works on 5 V (but the card type becomes SDHC). So I've tried to feed my card with another 3.3 V/5 V supply (my Arduino is grounded to this supply as well), but this is only working on 5 V. On 3.3 V my card isn't detected. My wires to the SD card are about 15 inch. I don't know if it can affect it drastically, but this is the only 'weird' thing about this circuit. By the way I naively think my 3.3 V supply should handle that.

Here are my materials: \- Arduino Duemilanove

* For the SPI wiring I'm using pin 10 for SS.
* Using the Cardinfo from the Arduino library.

# Answer
> 1 votes
I recommend you get a MicroSD card breakout board from that link, or something similar. That's around $US 15.

That includes the logic level converters. That particular board is for the \**micro\* SD card, but similar converters could no doubt be found for an SD card. Or use that one with a micro-SD card and just get an SD converter for when you plug it into the Mac.

I personally have used the SDfat library without any problems. However since he started rewriting it, I did have some issues. I have a backup of an earlier version which might be useful if the live library doesn't work for you.

You might be best off not formatting the card, but leave it as factory formatted. That will probably be compatible with the Mac, and also the SDfat library.

# Answer
> 0 votes
First of all, use 3.3 V. You need a logic-level converter.

Then you have to understand SPI is not the main protocol used by SD cards, and that Arduino should use SDSC to be sure, as some libraries are SDSC only.

Then you may have a hardware problem (from *FAT32/SDHC library for Wave and other shields*):

> SDHC cards have a 3.3 V bus so most Adruino shields, like the Wave Shield, use a resistor voltage divider to shift bus levels from 5 V to 3.3 V. These voltage dividers can not meet the 10 ns rise time for most SDHC cards."

Also using an external power source *may* solve your trouble.

# Answer
> 0 votes
Mac OS X will default to using the GPT partition table to format the card, even in FAT32. This does not work with the standard Arduino library for SD cards I've found. You must use MBR.

---
Tags: sd-card, spi, mac-os, arduino-duemilanove
---


# Question
Title: producing sine wave variable in amplitude and frequency
How to produce a sine wave with variable frequency and variable amplitude? I found a library to produce variable frequency called `sinwave` but not produce variable amplitude (I want -2V to 2V amplitude)

# Answer
> 2 votes
You can use a digital potentiometer as a programmable attenuator or as a feedback element in a programmable gain amplifier circuit.

See references at arduino.cc regarding interfacing an AD5171 or AD5206 to Arduinos.

# Answer
> 2 votes
Here's one solution to do it using your own code implementing the following.The basic solution is as follows. Start with the basic sine wave output (this has amplitude between -1 and 1, and repeats ever 360 degrees) implemented as a function in your Arduino sketch with a variable parameter for the frequency and amplitude.

Now input the frequency you want (which you don't specify) and the amplitude (that is multiply your sine function by 2). The frequency can be implemented by using the delay function to output a value corresponding to the y-axis of the sine wave at the specified time on the x-axis. You would need the y output to depend on the delay and the frequency. This is all in code so far.

The next step is to output the corresponding voltages for each point on the sine wave. To make a varying voltage you can use a digital potentiometer with a voltage divider type circuit (it's not quite an voltage divider because it needs to produce negative voltages too). Thus you just need to make your code activate the digital potentiometer at the required resistance to create the required voltage that represents the y value of that sine value at that point in time (x axis has time). This voltage divider requires some more circuity to make the voltage between 0 and -2 volts (the negative voltage depends on the time the circuit has been on or the x-axis of the sine wave). There are lots of ways to make a corresponding negative voltage (the bottom half of the sine wave). The triggering on or off of the potentiometer is done from the Arduino thus this also controls the frequency of the sine wave.

To sum up code the sine wave in a sketch with your desired frequency and amplitude use these values and implement the discrete point on the sine wave using a (digital) potentiometer which is part of a circuit which is a variation of the simple voltage divider (the voltage divider type circuit will implement the amplitude of the sine wave which you want between 2v and -2v). The frequency is, basically, implemented with the delay function.

---
Tags: library
---


title: Combine DHT22 and SI114X.h

text:
# Question
Title: Combine DHT22 and SI114X.h
It looks like I cannot combine the Grove sunlight sensor and the Grove DHT22 temperature and humidity sensor. I can't figure out why.

I have the following setup:

* Seeeduino Cloud (Arduino Yún clone)
* Grove Shield Grove sunlight sensor connected to an I2C port
* Grove DHT22 temperature and humidity sensor connected to port A0

I'm sending the data to Initialstate.com. This is my code:

```
// Process.h gives us access to the Process class, which lets
// us communicate with the shell
#include "DHT.h" //Temp Hum sensor
#include <Bridge.h>
#include <Process.h>
#include <Wire.h>
#include "SI114X.h" //Sunlight sensor

SI114X SI1145 = SI114X();

////////////////////////////////////////////

//Temperature and Humidity sensor data start
#define DHTPIN A0
// what sensor is connected to, in this case A0
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);
//Temperature and Humidity sensor data end

////////////////////////////
// Initial State Streamer //
////////////////////////////
// URL to IS Bucket API
String ISBucketURL = "https://groker.initialstate.com/api/buckets";
// URL to IS Event API
String ISEventURL = "https://groker.initialstate.com/api/events";
// Access key (the one you find in your account settings):
String accessKey = "KRYLC3tvJUiyTVqTJr5nRqgkKQI2FiDh";
String bucketKey = "Test_Klimaat2";
// Bucket name (name your data will be associated with in Initial State):
String bucketName = "Test klimaat 2";
// Bucket key (hidden reference to your bucket that allows appending):
//String bucketKey = "arduino_stream";
// Bucket name (name your data will be associated with in Initial State):
//String bucketName = "Arduino Stream";
// How many signals are in your stream? You can have as few or as many as you want
const int NUM_SIGNALS = 5;
// What are the names of your signals (i.e. "Temperature", "Humidity", etc.)
String signalName[NUM_SIGNALS] = {"Humidity", "Temperatur", "Visable", "Infrared", "UV"};
// This array is to store our signal data later
String signalData[NUM_SIGNALS];

// This only runs once at the very beginning
void setup() {
  Serial.begin(9600);
  Bridge.begin();
  Wire.begin();
  SI1145.Begin();
  dht.begin(); //Initialize temparature and humidity sensor

  while (!Serial);
    // Post Bucket
    Serial.println("Posting Bucket!");
    // The postBucket() function creates a bucket
    // (unnecessary if the bucket already exists)
    postBucket();
}

// This repeats
void loop() {
  // Gather Data
  // Read from a port for input or output or generate your own values/messages
  // These signals are random numbers for the sake of example

  String VIS;
  String IR;
  String UV;
  String TEMP;
  String HUM;

  //Code reading DHT22
  HUM = String((float)dht.readHumidity());
  TEMP = String((float)dht.readTemperature());

  //code reading Sunlight data
  VIS = String(SI1145.ReadVisible());
  IR = String(SI1145.ReadIR());
  UV = String((float)SI1145.ReadUV()/100);

  signalData[0] = HUM;
  signalData[1] = TEMP;
  signalData[2] = VIS;
  signalData[3] = IR;
  signalData[4] = UV;

  // Post Data
  Serial.println("Posting Data!");
  // The postData() function streams our events
  postData();
  // Wait for 5 seconds before collecting and sending the next batch
  delay(5000);
}

// Here are the data bucket creation and posting functions
// They do not need to be edited - everything you would need to change for
// your situation can be found above

void postBucket() {
  // Initialize the process
  Process isbucket;

  isbucket.begin("curl");
  isbucket.addParameter("-k");
  isbucket.addParameter("-v");
  isbucket.addParameter("-X");
  isbucket.addParameter("POST");
  isbucket.addParameter("-H");
  isbucket.addParameter("Content-Type:application/json");
  isbucket.addParameter("-H");
  isbucket.addParameter("Accept-Version:0.0.1");

  // IS Access Key Header
  isbucket.addParameter("-H");
  isbucket.addParameter("X-IS-AccessKey:" + accessKey);

  // IS Bucket Key Header
  isbucket.addParameter("-d");
  isbucket.addParameter("{\"bucketKey\": \"" + bucketKey + "\", \"bucketName\": \"" + bucketName + "\"}");
  isbucket.addParameter("https://groker.initialstate.com/api/buckets");
  // Run the process
  isbucket.run();
  Serial.flush();
}

void postData() {
  // Initialize the process
  Process isstreamer;
  isstreamer.begin("curl");
  isstreamer.addParameter("-k");
  isstreamer.addParameter("-v");
  isstreamer.addParameter("-X");
  isstreamer.addParameter("POST");
  isstreamer.addParameter("-H");
  isstreamer.addParameter("Content-Type:application/json");
  isstreamer.addParameter("-H");
  isstreamer.addParameter("Accept-Version:0.0.1");

  // IS Access Key Header
  isstreamer.addParameter("-H");
  isstreamer.addParameter("X-IS-AccessKey:" + accessKey);

  // IS Bucket Key Header
  // Note that bucketName is not needed here
  isstreamer.addParameter("-H");
  isstreamer.addParameter("X-IS-BucketKey:" + bucketKey);

  isstreamer.addParameter("-d");

  // Initialize a string to hold our signal data
  String jsonData;
  jsonData = "[";
  for (int i=0; i<NUM_SIGNALS; i++) {
    jsonData += "{\"key\": \"" + signalName[i] + "\", \"value\": \"" + signalData[i] + "\"}";
    if (i != NUM_SIGNALS - 1) {
      jsonData += ",";
    }
  }
  jsonData += "]";
  isstreamer.addParameter(jsonData);
  isstreamer.addParameter("https://groker.initialstate.com/api/events");
  // Print posted data for debug
  Serial.print("Sending data: ");
  Serial.println(jsonData);
  // Run the process
  isstreamer.run();
  Serial.flush();
}

```

When I run this code, the Serial monitor will correctly display the data string I want to send with all values. However the data is NOT sent. Only when I comment out one of these lines in the `loop()` declaration the data is sent to Initialstate successfully. Obviously without the data commented out:

```
  //Code reading DHT22
  HUM = String((float)dht.readHumidity());
  TEMP = String((float)dht.readTemperature());

  //code reading Sunlight data
  VIS = String(SI1145.ReadVisible());
  IR = String(SI1145.ReadIR());
  UV = String((float)SI1145.ReadUV()/100);

```

Any ideas are appreciated.

# Answer
> 1 votes
I found the solution. Based on this post: http://forum.arduino.cc/index.php?topic=198433.0 I concluded that my strings are too long or my board runs out of memory. I removed the posting of the bucket and created abbreviations in my signal names. This solved the problem.

---
Tags: arduino-yun, temperature-sensor
---


title: What power supply should I use?

text:
# Question
Title: What power supply should I use?
I am building a robotic arm using 8 servo motors. I am wondering about what voltage my external power will need to be to control all of them at 6v. I am wanting to use a rechargeable battery.

# Answer
> 6 votes
> I am wondering about what voltage my external power will need to be to control all of them at 6v

Well that would be 6V then wouldn't it?

You're asking the wrong question. The question you should be asking is:

> How much current will I need from my 6V power supply?

And the answer is:

**Add up the total current required by all of the devices and that is the *minimum* current the PSU has to provide**

On top of that you need to consider *how long the supply should last*. The average current need to draw from the batteries, multiplied by the number of hours you need it to run for, is the minimum capacity of battery you need.

For instance, if you need to draw an average of 500mA for 6 hours then you need (0.5\*6 =) 3Ah (or 3000mAh) batteries (or better).

# Answer
> -1 votes
You should use a **Voltage Regulator** for a stable Voltage Output.

First you should know your **maximum Current consumption**. Lets say for example maximum 2A.

You want the Voltage of the Servos stable, so they dont jerk around when there is a voltage drop or change. Because of this reason you should use a Voltage Regulator. For this example, choose one which has a Output of 6V 2A.

For the most of the Voltage Regulators you will be safe if you calculate **an extra of 2V for the Voltage Drop**. The Voltage Drop Value is specific for every Voltage Regulator Model. You can find this Value in its Datasheet.

So you would need a Power Source, for example a rechargeable NiMh battery with 8V(6V+2V), which can supply 2A. Not all batteries in the world will be able to give you 2A, but like all of the NiMh batteries should.

You can find the exact circuit for your Voltage Regulator in its Datasheet, which most likely also will have some (optional) capacitors in it.

---

**In Summary:**

1. Your needed Voltage (6V)
2. Your maximum needed Current (for example 2A)
3. Find one Voltage Regulator with 6V and 2A Output
4. Find out its Voltage Drop Value
5. 6V + Voltage Drop Value = minimum battery voltage
6. Be sure the battery can support the maximum current (2A)
7. Design your circuit with the help of the Voltage Regulators Datasheet
8. Calculate if you need a heat sink for your Voltage Regulator

---
Tags: arduino-uno, power, servo, robotics
---


title: PWM generation for inverter by Arduino

text:
# Question
Title: PWM generation for inverter by Arduino
Can I generate a PWM signal for a Mosfet driver using a saw tooth wave and sine wave through Arduino ?

# Answer
Yes you can very easy generate an PWM Output with an Arduino:

```
void setup()

{

  pinMode(pwmPin, OUTPUT);   // sets the pin as output

}

void loop()

{

  analogWrite(pwmPin, yourWantedValue);  // analogWrite values from 0 to 255

}

```

> On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.
>
> The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

Visit quote origin for more Information.
> 1 votes

# Answer
Currently, none of the boards have a DAC on them, with the exception of the arduino Due. Thus, Unless you have the Due board, it is not possible. If you have a due board, and are interested in generating wave functions, then check out here: https://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator
> 0 votes

---
Tags: arduino-uno, mosfet
---