text:
What is better: one sprintf() or multiple strcat() and itoa()?
I was creating Arduino function which sends two int and additional chars between them and at the beginning and end of char array - then print that array to the serial port in almost real time. (For example "X50Y100T".)
I don't want to use String object in Arduino and I found two possible solutions:

Using sprintf():
char sendBuffer[16];
void dataSend(int first, int second) {
  sprintf(sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
};

Or something like this:
char sendBuffer[16];
void dataSend(int first, int second){
  char convert[6];
  sendBuffer[0] = 'X';

  itoa(first, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'Y';

  itoa(second, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'T';

  Serial.println(sendBuffer);
  memset(sendBuffer,0,sizeof(sendBuffer));
};

My question is - which one is better from technical point of view?
The sprintf() looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of sprintf()? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of char array?

Why do you feel you need to use either method? Neither are needed. Just print the individual parts:
Serial.print('X');
Serial.print(first);
Serial.print('Y');
Serial.print(second);
Serial.println('T');

No intermediate buffers, just sending the data direct out to the UART.

It really does the same thing? Great. If it has the same or better performance I will use this :)

When you send to the serial it all gets put into a circular buffer for sending using interrupts. It makes no sense putting it into your own buffer first to then transfer that buffer to the serial buffer. It's more efficient to just fill the serial buffer directly.

Thanks. It makes sense :) I will use this solution from now. Probably my solutions are better for in-sketch operations.

Here's a method that for some reason uses slightly fewer bytes of flash memory than Majenko's does, while producing the same output:
Add #include <Streaming.h> at the beginning of the program, and replace the five statements shown in Majenko's answer with the following line:
Serial << 'X' << first << 'Y' << second << 'T' << endl;

That is, use the Streaming.h contributed library, which adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it via Streaming5.zip from arduiniana.org.
When the #if-delimited sections in the program shown below are selected individually (by changing two of the three 01's at a time to 0's), I got the following compiled-code and RAM figures, running the program on a Nano, where all three ways appear to give the same output:
      Bytes  Bytes
Alt.  Flash   Ram    Note
 1    2,204   182    Five Serial.print stmts
 2    3,384   190    Using snprintf()
 3    2,176   182    One Streaming stmt

I don't know whether this slight decrease (from 2204 to 2176 bytes of flash) is replicable, but the method probably is worth trying in your situation.
The program:
#include <Streaming.h>
void setup() {
  Serial.begin(115200);
}
void loop() {
  int first=50, second=100;
  //enum { first=50, second=100};
#if 01
  Serial.print('X');
  Serial.print(first);
  Serial.print('Y');
  Serial.print(second);
  Serial.println('T');
#endif
#if 01
  char sendBuffer[16];
  snprintf(sendBuffer, sizeof sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
#endif
#if 01
  Serial << 'X' << first << 'Y' << second << 'T' << endl;
#endif
}

Note, I used snprintf() rather than sprintf() because it's easier to avoid buffer overruns with snprintf() than with sprintf().

Hmm... I've never seen the streaming library. It looks great from both memory and readability point of view. Thanks for your answer :)

Excellent! I wished I have known this long ago.

I'm working on an attiny, and removing all calls to .print and .write, replacing them with << streaming syntax, saved me about 400 bytes. Very useful.

The sprintf() function has a memory cost because of the library import at compile time.  But it only costs that once, no matter how many more times you use it.  Unless you're running out of space, memory used is not a big deal.  There's no point keeping some memory unused on an Arduino.
I think it's better to use sprintf() because:

sprintf() produces code that is more readable, since the final output string can be easily visualised - obviously with only place holders for the variable parts.
Making minor changes to the output is quicker, since there's not lines of output generator functions to re-organise.
You end up with less code.  Less code is is easier to debug and maintain.

I would however, encourage you to use snprintf().  This function differs from sprintf() by taking the maximum buffer size as an argument.  This will help prevent problems with buffer-overruns (i.e.: accidentally putting more data into a string than in can hold)
Sprintf on Arduino does not include support for floating point numbers though.  This is quite a drawback.  One needs to use additionally use dtostrf().
The real takeaway point is this:  Only optimise your program when you need to.  Donald Knuth said: "Premature Optimisation is the root of all evil".

As a general principle code that is easy to read and modify is "better" – the problem here is that there are many "betters" to consider:

Readability
Maintainability
Space efficiency
Time efficiency

There is no universal answer to which of those is the most important. My personal bias is to start with code that is easy to read and obvious in its function. Then if time or space are an issue to start looking for ways to improve.
In your code, you could also do something like this:
  itoa(first, sendBuffer[1], 10);

Which would save you a function call and perhaps some space.
Also keep in mind that the cost of sprintf() in terms of space may get amortized over many uses, so it might not be as bad as it initially seems.

The sprintf() may appear two times in sketch, In this case I'm focusing on memory and performance rather than amount of lines of code. Thanks for your answer.


text:
Transistor slows motor instead of turning it off
I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.
I'm using an Arduino Uno's digitalWrite() feature to activate a transistor, allowing the external 9V battery to turn on the motor.
Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.
Here's the schematic of my circuit:

simulate this circuit – Schematic created using CircuitLab
Code:
void setup(){
  pinMode(9, OUTPUT);
}

void loop(){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

Why isn't the motor completely turning off?

At first glance: your base resistor is way too high allowing only a small amount of current to flow through the collector.

And you forgot your flyback diode...

Another arbitrary migration- this has no particular relevance to Arduino- it could be any micro. 8-(

This is an electronics question - although the word "Arduino" does happen to appear in it.

I can't make much sense of your diagram-  but this is the correct way to do it:

simulate this circuit – Schematic created using CircuitLab
R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.
You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.

My precious reputation :(

Have an upvote, my friend.

There are multiple things wrong with your drawn schematic:

The ground symbol is not wrong but really misleading.
You forgot to add a flyback diode.
You wired the load the wrong way: the load is placed between the collector and VCC, not between emitter and GND.
The base resistor is way too high.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
It seems my Arduino doesn't work
I've got an Arduino Uno.
I was building a simple circuit with only one switch and it doesn't seem to work (I followed the Arduino project book from the Arduino starter kit).
This is my circuit :

Then I try again to move the switch and then it works (but I don't understand why).

So I tried to understand where the error is and I try to read digital input from the simple circuit with only one LED :

And this is my code :
int SWITCH = 13;

void setup() {
    Serial.begin(9600);
    pinMode(SWITCH, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
    int val;
    val = digitalRead(SWITCH);
    if(val == HIGH) {
        Serial.println("OKAY");
    }
}

I expect to see on the Serial Monitor "OKAY OKAY" and so on... but nothing appears on the Serial monitor.
Then I try to change the condition :
if(val == LOW)

And now I see "OKAY OKAY" and so on...
I think that there is something wrong with this Arduino... Can someone tell me something about what is happening? Am I stupid or there is really something wrong with this?

Could you try to turn the led around. And maybe even take out the switch.
If that doesn't work, try another LED and turn it around when it won't work.
LED's have polarity, which means they only work one way around.

I tryied with a lot of different leds and switches. In the lastest image (link) the led is on so this works right but if a read digital input from that I see that there is no voltage. Why?

It looks to me like your arduino is working just fine.
In the first two images you use the arduino only to provide 5v power to the circuit on the breadboard. In the first image you haven't connected your button to properly function as a button. I don't know the exact pin layout of the button (which should be explained in a datasheet of that button), but it is also good to know exactly how to holes in a breadboard are connected. This picture shows why your button works on your second image but not your first:

This picture also shows how the breadboard holes are connected:

In your third image you have practically connected input pin 13 to GND, so it makes sense that digitalRead(13) in your code always returns LOW. Thus, the variable var is always LOW (or 0). Thus, the comparison (var == HIGH) is FALSE, which won't send "OKAY" to the serial monitor. And, the comparison (var == LOW) is TRUE, which will* send "OKAY" to the serial monitor.
I hope you can follow the logical steps and it is clear to you what is happening.

Thanks so much for your answer. I've build now the same circuit and it works right. If i push my switch the led turn on. Here is the picture of my circuit : http://imgur.com/6DWyWr6 . If I use the same code than above using val == LOW than print "OKAY" what I have to expect in output if my switch is open, and what if my switch is closed? (i tryied to print Serial.println(digitalRead(SWITCH)) and also if my switch is open or close i always have 0) Why? Thanks.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Problem connecting Arduino Uno with Wifi and NFC
I'm new here and also new to Arduino.
I've got a rather specific problem and I've posted to the official Forum
on arduino.cc two days ago (original Post)
Sadly, I've yet to recieve any help and since it's a project for work, theres a (loose) schedule. So I've decided to post it here as well.
If you have some ideas, it'd be really great!
Also, if I've posted this question without acknowleding some forum rules please tell me so that I can write better posts in the future ;-)
Regards,
Patrick
Edit:
The original Posts as Text :-)
Post # 1
Hello Guys,
this is my first time posting in the forum since I'm new to Arduino, so please be kind  smiley-wink.
Me and a colleague of mine have been given a Project to create with arduino hardware.
The Project is, that you should be able to read NFC tags with the arduino
and send them to a server to be checked and eventually being written into a db.
The hardware:
Arduino Uno R3 (funduino.de/index.php/shop/product/view/2/4)
Adafruit CC3000 (www.adafruit.com/products/1469)
Adafruit PN532 (www.adafruit.com/products/789)
Stepper Motor (not yet included and not relevant for the problem)
Sorry about not using hyperlinks, but the forum says I'm not allowed to post more than 2 links at once...
Now on to the Problem:
When we're using the shields separately (meaning connecting the arduino to either of the shields by itself), the shields work fine. The cc3000 gets a connection and the PN532 reads cards.
Now we've tried to stack them together for live use. That's where the trouble starts...
If I connect the PN532 5V to the arduino 3.3V
and CC3000 VIN to 5V arduino,
the shields both do what they should with separate example sketches ('readMifare' and 'buildTest').
If I put my sketch in (which combines both of those sketches and some other stuff)
and comment out the initialization of either the PN532 or the CC3000, the other shield works.
Now if I try to use both, the CC3000 and the PN532,
the CC3000 tries to initialize, but falls into a loop of restarts.
I've read that that (possibly) is because of the lack of power supply.
(I've connected a 12V wall-wart by the way and it didn't work with that either)
The manual says, that the CC3000 needs 5V, but can work on 3.3V too (though I didn't find a source to explain how)
and the PN532 needs 3.3V to run.
Am I doing something wrong, or is it a problem with the arduino?
If I'm doing it wrong, how am I connecting these parts correctly?
I really am not that good with electronics and didn't find a sollution to my problem nearly a days worth of searching the net.
For your understanding I'll post the script I'm using and some pictures of the board setup.
Thanks in advance for ANY help you guys can give me (even if it's just  good guide for problems like mine) ^^
Regards,
Patrick
The part of the sketch that initializes the components (and also where the CC3000 gets stuck...)
Code:
//WLAN-Libraries
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"

//NFC-Libraries
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

//Motor-Libraries
#include <Stepper.h>

//NFC-shield PINs
#define IRQ   (2)
#define RESET (4)  // Not connected by default on the NFC Shield

Adafruit_NFCShield_I2C nfc(IRQ, RESET);

//Motor-settings
const int stepsPerRevolution = 180;  // change this to fit the number of steps per revolution
                                     // for your motor

Stepper Motor(stepsPerRevolution, 6,7,8,9);  // initialize the stepper library on pins 8 through 11:

//Wifi-settings
// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIV2); // you can change this clock speed

#define WLAN_SSID       "mySSID"           // changed for your convenience
#define WLAN_PASS       "myPassphrase"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client www;  //defines how we will refer to the cc3000 connection object

// What page to grab!
#define WEBSITE      "10.2.10.170"  //NOTE: CC3000 doesn't seem to like the default localhost address of 127.0.0.1 - need to enter actual IP
#define WEBPAGE     "/index.php"

//this is the counter that will be used for uploading data
long pollCounter = 1;

//used for storing data for upload
//set it to the data type that suits your data
int
  NFC_ID, Session_ID, UID_final;

//used for commands received from base station
int
  command_open, command_close;

  boolean pollFlag = false;         //tells the sketch whether to poll or not

//declare a variable to hold a numeric IP address
//can be overridden below if you use lookup
  uint32_t ip = (192L << 24) | (168L<<16) | (1<<8) | 13;

/**************************************************************************/
/*!
    @brief  Initialization of the modules (Motor, Wifi, NFC-Reader)
*/
/**************************************************************************/

void setup(void)
{

//Set up the Motor for the lock
  // set the Motor speed at 60 rpm:
  Motor.setSpeed(60);

//Set up the Wifi module
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialize the Wifi module */
  Serial.println(F("\nInitializing..."));                 //<======== Here the CC3000 gets stuck in a loop
  if (!cc3000.begin())                                          //                          when both shields are connected
    {
      Serial.println(F("Couldn't begin()! Check your wiring?"));
      while(1);
    }

  cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
    {
      delay(100); // ToDo: Insert a DHCP timeout!
    }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails())
    {
      delay(1000);
    }

  cc3000.printIPdotsRev(ip);

//Set up the NFC module
      if (pollFlag == true)
      {
            nfc.begin();
        uint32_t versiondata = nfc.getFirmwareVersion();
        if (! versiondata) {
          Serial.print("Didn't find PN53x board");
          while (1); // halt
        }
        // Got ok data, print it out!
        Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
        Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
        Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

        // configure board to read RFID tags
        nfc.SAMConfig();

        Serial.println("Waiting for an ISO14443A Card ...");
  }
  else {
     Serial.println("Failed to initialize NFC-Reader... Sorry...");
  }

  }

Hope I'm not messing up the image-uploads...
(I kept the wiring-colors where I coul for you to see the connections easily)
The boards connected via cables (both separately working)
www.directupload.net/file/d/3740/j3y3tx38_jpg.htm
The boards put together
www.directupload.net/file/d/3740/yb9q6qla_jpg.htm
The boards connected together with the Wifi in the picture.
(You can't see the LED on the CC3000 light up, but I swear it does  smiley-wink)
www.directupload.net/file/d/3740/uorksjrj_jpg.htm
Post # 2
Ok, I got myself a multimeter today to measure if it is really a problem with the power supply.
With the NFC-Reader running I measured 4.85V on the 5V-Pin and 3.32V on the 3.3V-Pin.
This means, that the CC3000 should have enough Power to run.
So I'm now looking for a possible address collision in the libraries (specifically I2C- and SPI-collisions). As I'm still new to this, help is really appreciated.
Edit #2:
Morning everyone!
What I've found out since yesterday is, that the PN532 uses I2C while the CC3000 uses SPI to communicate. When I looked through the libraries I found out that the PN532 includes Wire.h which gets its address at "nfc.begin();"
In the begin-function in Wire.cpp there is an address transmitted to the function, but I can't find it's source. Is it possible that that address collides with the one the CC3000 uses?
When I uploaded an I2C-Scanner to the UNO, it said that the only device fount is the PN532 on address '0x24'.
I don't really know what to do with that info though, since there are more libraries being included (like  which in term calls others) and I cant even find these on the Mac I'm working on at the moment...
Edit #3:
The problem has been solved in the arduino.cc forum. The SRAM was overflowing, but applying the F()-macro to the strings being printed solved the issue!
(Just in case someone has similar issues ^^)

The problem has been solved in the arduino.cc forum. The SRAM was overflowing, but applying the F()-macro to the strings being printed solved the issue! (Just in case someone has similar issues ^^)


text:
Using Arduino as USB Device?
I'm trying to get audio data from an ADC connected to an Arduino into a host PC.  I've done some digging and found LUFA, which I think Arduino uses under the hood. Is it possible to use the Arduino as a USB device, and if so, are there any examples?  Thanks!

For those Arduinos which use general purpose microcontrollers for their USB interface, yes, you can reprogram them.  But what data rate do you need to move?  An ATmega based Arduino tends to imply a moderate one, and if you don't need to put it directly into the PC's unmodified audio stack, you can probably just crank the serial channel to maximum baud rate and push your data that way, with a lot less work.  One where the USB comes direct from the sketch processor - either a Leonardo or one of the ARM-based boards - would probably be most capable.

Do you want to have it be a HID device or is serial to audio fine? It might be cheaper to buy something designed for this and prebuilt... anyway no, Arduino doesn't use LUFA. It uses a similar firmware for the serial connection.

I need it to appear as a USB Class Audio device so that it can interact with pre-existing OS drivers.

I'd assume this would require me to do some low-level stuff

Someone has done 10-bit 16 Ksps stereo with a Leonardo: http://forum.arduino.cc/index.php?topic=208140.0

I'm glad if it helps you, but as just a link it's sort of an answer of last resort in quality, and unfortunately there's not much more that can be said about it without downloading and studying that code to see what can be learned from it.

Thanks so much!  I've seen you comment on some of my other questions and you were a huge help!

LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.
But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.
The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:

On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.

I am confused on what your end purpose is.  do you want something that works or you want to make a project for self-learning purpose.
For ready-made products that you can buy, if you want the PC to be able to input and output sound, there are hundreds models of a) sound card plug into PC  b) external sound card link to PC via USB cable    They ranges from a few USD to 50 to 200 with huge range of performance in terms of sampling rate and number of bits (low noise).
Ardu build-in ADC is 10 to 12 bits. These card are 16 to 24 bits.
See
http://www.bestbuy.com/site/computer-cards-components/sound-cards/abcat0507003.c?id=abcat0507003
24 bits 116 dB SNR very low noise
http://us.creative.com/p/sound-blaster/sound-blaster-z
I used them as test instrument for commercial/university projects with success.
I saw on TV news that same setup (high bit card, at -110dB or lower noise level) used in the underwater signal search for MH370 down plane months ago.


text:
Arduino Serial Monitor only returning Null Characters
I'm trying to simply access my HC_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, it only seems to be returning Null characters, though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

So you can clearly see that the command AT and AT+NAMEdevice return different data, but they are both all NUL blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.
Code for this simple program is below:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Wire Diagram is as here
NOTE I have used both a direct connection to the 5V and also used a Voltage Divider. Neither changes the NUL return.

Are you sure the module is running at 38400 baud?

Shouldn't it be while (BTSerial.available()) and while (Serial.available()) instead of if...?

Have you tried to force the Key pin of HC-05 directly to +V, instead of using Arduino pin 9, just to remove one potential issue?

First, change all Serial.write to Serial.print I think that might be half your problem.
Next,
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:
Change BTSerial.begin(38400); to BTSerial.begin(9600);
Or, as jfpoilpret suggested, tie the Key pin directly to VCC.  The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up.  By the time the digital write in your code happens, it's too late.
If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's AT+UART= off the top of my head.
Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX
char myChar;

void setup()
{
  ...
}

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

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

This sounds like baud-rate mismatch. These dongles don't have a reset ability; they remember their most recent settings. See my answer to another user having trouble communicating with one these.


text:
Rewrite part of the example code from Adafruit FONA
Recently, I bought the FONA 800 shield from Adafruit. I have got it running with the examples and it plays very nicely.
I want to use the part of the example code which handles a call in my own sketch. The example code waits for a number to call which should be entered in the serial. I want to do the exact same thing, just with the phone number supplied from a variable in Arduino.
I have two possibilities: To supply the whole number when the call should be performed and to build up let's say an array every time a number is entered.
The code for performing a call:
// call a phone!
    char number[30];
    flushSerial();
    Serial.print(F("Call #"));
    readline(number, 30);
    Serial.println();
    Serial.print(F("Calling ")); Serial.println(number);
    if (!fona.callPhone(number)) {
      Serial.println(F("Failed"));
    } else {
      Serial.println(F("Sent!"));
    }

The flushSerial function:
void flushSerial() {
  while (Serial.available())
  Serial.read();
}

And the readline function:
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;

while (true) {
  if (buffidx > maxbuff) {
    //Serial.println(F("SPACE"));
    break;
  }

while (Serial.available()) {
  char c =  Serial.read();

  //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

  if (c == '\r') continue;
  if (c == 0xA) {
    if (buffidx == 0)   // the first 0x0A is ignored
      continue;

    timeout = 0;         // the second 0x0A is the end of the line
    timeoutvalid = true;
    break;
  }
  buff[buffidx] = c;
  buffidx++;
}

if (timeoutvalid && timeout == 0) {
  //Serial.println(F("TIMEOUT"));
  break;
}
  delay(1);
}
  buff[buffidx] = 0;  // null term
  return buffidx;
}

It is the readline function which should be edited. Right now it retrieves the number entered from serial.
I am kind of a newbie myself so I am not that familiar with data types and so on.
Thank you very much for any answers.
EDIT:
The function without readline:
if (!fona.callPhone("12345678")) {
        Serial.println(F("Failed calling"));
      } else {
        Serial.println(F("Calling ..."));
      }

I can't quite follow this. The much obvious way to make this use a constant phone number this would be to load your number string into the char number[30]; variable and skip the entire readline process. You could also simple substitute char* number = "01234567..";. Is that what you want?

@MaximilianGerhardt
That's the problem. I can't just put in a number, it fails calling. As I wrote, I am not that familiar with Arduino but I think it wants the numbers as an array or something (that's why I gave you the readline function). I have tried a various ways to put in the number directly to the call function but none of the times did it go well.

All readline does is fill the number buffer with the data coming over serial while ignoring newlines. If you input some number "1234" over serial then it is equivalent to just putting char* number = "1234";. Are you absolutely sure that if you input the number over serial using readline it works, but putting the same number directly in the number variable doesn't? Can you show the code with which you tried that?

@MaximilianGerhardt
This is what I have tried. If it is a number it doesn't even recognize the number. When it is a string like here it inputs the number correctly but somehow it fails calling (I have done exactly as I did when it worked regarding the way I call the call function)

When calling through the shield, it prints in the serial (the library does). I can see the number it is trying to call which is only correct when I put in the numbers as a string. But the next serial print is the one I have defined to tell if there is an error: "Failed calling".

I see no logical reason why this should not work. Please post the entire code which is trying to call a hard-coded number and also the serial monitor output. If ARDUINO_FONA_DEBUG is defined in your library (here), you should see at least some more debug messages on what it's trying to do. What is the serial debug output compared to when you input it over Serial with the first version?

@MaximilianGerhardt, thank you so much for the help. I was confused about the string, numbers, buffers and so on which were the course for it to fail. It works now. Please leave an answer for closing this question

i think it's best if you write the answer yourself because I'm not sure what exactly you changed in the code so that it suddenly runs.

I had to enter the numbers as a string. Also I found out that I had set the variables in a wrong way.
The library for the FONA Shield needs the number to call as a string. They are creating it by assigning the input from serial to a char.
The problem was that I tried to input numbers. Also, I found out that when I tried to work with variables instead of hard coded numbers I messed around in data types.
Final conclusion:
When calling the fona.callPhone function, you have to put in a string containing the numbers instead of actual numbers.

Of course. I can't mark my own as correct before 22 hours have passed ..

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino Pro Mini Serial Monitor garbage
This is my first post. I hope that I am posting in the right section of the forum. Otherwise, could an admin move this topic to the appropriate section please?
Board : Arduino Pro Mini 3.3V 8MHz
Arduino IDE : 1.6.12
Arduino is powered by a FTDI Board and USB Mini-B cable from the computer USB port in the following order :
Arduino        FTDI
BLK              GND
GND             CTS
VCC             VCC
RXi              TX
TXo             RX
DTR             DTR
Also, I have connected a HC-06 bluetooth module in the following order :
Arduino    HC-06
GND         GND
VCC         VCC
D10         TXD
D11         RXD
The Serial Monitor is open on COM4, Newline, 9600 baud.
The code that I'm trying to run is :
#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11);
void setup()
{
  pinMode(13, OUTPUT);
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from BTSerial");

  Serial.begin(9600);
  Serial.println("Hello from Serial");
}

char a; // stores incoming character from other device
void loop()
{

  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    Serial.println(a);
  }
}

I am trying to communicate with the HC-06 from an Android phone.
I am posting in this section of the forum because when I send a message from the phone to Arduino the following is printed in the Serial Monitor :
à„…€ƒ¦¤„„‡…§¤¦„‡Å„EóAãbBãbHãb

When I am trying to send a message from Arduino to the phone, nothing is received on the phone.
Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window?
Is there a problem with the Arduino IDE?
Edit 12.11.2016
This is what I get when I open the Serial Monitor in the Arduino IDE with this code :
Newline, Baud rate 9600
‚Æ‡¥Ç$¤†Fó

If I change the Serial Monitor properties to Newline, Baud rate 19200 this is what I receive :
Hello from Serial

On the Android phone application I do not get anything printed.
Also, please note that this question is also addressed on the Arduino forum at the following link :
http://forum.arduino.cc/index.php?topic=434623.0
I will try and answer in both places as I am not sure that everybody has an account on the forum

Is there any possibility that your HC-06 have not configured to run at 9600  baud?

Was about to say the same thing as @dpw, there's a huge chance the HC-06 runs at a different baud rate. A simple Google search shows that 38400 is a common (or even default) baud rate of the HC-05 and HC-06. This definitely would explain the gibberish you're receiving.

Changed this through TeraTerm. I got the confirmation message that the Baud rate was changed. Still, no change.

I had the same issue. The problem was solved in an other forum:
https://forum.arduino.cc/index.php?topic=434623.0
I copy the solution here:
It appears that in fact your board is not running at 8MHz, but instead 16MHz.
Please select the correct setting for your board:
Tools > Processor > ATmega328(5V, 16MHz)
Or if it has the ATmega168:
Tools > Processor > ATmega168(5V, 16MHz)

that helped me a lot.

BLK GND
GND CTS

That looks backwards to me. Connect GND to GND and CTS to BLK.
The bluetooth module operates at a predefined baud rate. You need to ensure that your Arduino communicates at that baud rate - you don't get to pick any old baud rate.
The baud rate can be changed with the AT+UART=x command (where x is a single digit representing the baud rate: 1=1200, 2=2400, 3=4800, 4=9600 (default), 5=19200, 6=38400, 7=57600, 8=115200, 9=230400, A=460800, B=921600, C=1382400).  If the HC-06 isn't on the default baud rate of 9600 (which is highly possible) then you will have to guess what the right baud rate is. Work through the possible ones listed there in yopur BT.begin(...) function to see if one of them starts working.

He's actually right. It isn't backwards.

Flip the RX and TX wires of the HC06. This is because this statement : SoftwareSerial BT(10, 11); actually means SoftwareSerial BT(RXpin, TXpin);. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.

I think I typed wrong in the main question because this is how I have them connected. Sorry for misleading you.

Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window? Is there a problem with the Arduino IDE?

Even if the baud of serial monitor and the code is same, there is a possibility that you have not configured your HC-06 to works on the same baud.
There are many ways to check and configure it by using AT-Command. You will easily found them since many tutorial has been written, here is some of the example :
link 1
link 2

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Why is my Arduino still working?
I read an article that said that shorting an IO pin to ground would destroy the pin.  I've done this before when I connected a buzzer to an IO pin and to ground without resistors, the buzzer is only 14 ohms so the current would be quite high through the pins.  Why is my Arduino still working,  and how should I know when to use resistors or what rating to use?

The Arduino is tougher than it looks. ;-) Or maybe you were just lucky.
The exact point of failure of an IC is hard to predict, because of part
to part variations, and because it can depend on many uncontrolled
factors (duration of fault, temperature, voltages and currents on other
pins, part history...). Then, the absolute maximum ratings are not the
predicted point of failure. They are rather a lower bound:

The part should not fail if you do not exceed the ratings
it may fail anywhere beyond those limits.

Time is, however, also a factor. The manufacturer says that operating
the part close to the limits for an extended period may shorten its
lifespan.

You don't necessarily destroy the pin, but it won't do it any good. To work out the resistors use Ohm's Law. The continuous output of a pin should not exceed 20 mA, thus:
V = I * R
R = V / I
R = 5 / 0.020
R = 250

Thus 250 ohms, from the pin to ground, would allow a safe amount of current to flow.
As for the rating, that resistor would dissipate:
W = V * I
W = 5 * 0.020
W = 0.1

Thus a resistor that could handle 100 mW would be required. More reasonably, a quarter watt resistor should be fine.


text:
Reprogramming a specific slave from the master ATTiny 85 (connected to IDE)?
Given that every ATTiny connected already has a bootloader (micronucleus) installed, here's my theoretical chain:
Computer > Master ATTiny (Connected via USB) > ATTiny Slave A > ATTiny Slave B
Is it possible to flash an individual slave (say, slave B) with new software without replicating it to all of the other slaves, or altering the master?
Can this be done with the normal MISO/MOSI/SCK/RESET method?
I've done some research (Programming multiple ATMegas/Arduinos at once) but I'm not looking for a batch flashing method; I want to upload custom programming to a single slave.
Note: I'm not trying to pass data between the master and the slaves. What I want is to reprogram the slaves from a single USB connection. It's also important that each slave has a fixed identity so I know exactly which one I'm flashing every time I boot the "system".
Disclosure: I'm an arduino novice and programming intermediate. This is my first project utilizing serial communication.

I recognize that I could simply connect each ATTiny as a unique USB device but (a). I don't want to have that many USB devices connected to my PC and (b). I would like to be able to pass some data between the master and slaves if it turns out reprogramming over the serial bus is feasible.

What sort of wiring are you envisaging? How close is the slave to the master? Using the bootloader you normally reprogram using a serial connection (not MISO/MOSI/SCK).

Wiring is flexible, I haven't actually put together the hardware yet. Closest slave would be a few inches, furthest out 3-4 feet. Does that mean I would want these connected via I2C?

Well, the current bootloader expects serial input, as I said. Not SPI and not I2C. You can write your own bootloader, but that would take more work than somehow adapting your hardware to use the existing one.

Is there a wiring diagram for that? I would like to have the ability of flashing the slaves in addition to master/slave serial communication (like with I2C). Can I use serial input to flash and I2C to communicate in-software?

If I can't control individual slave flashing, then pushing a software update through to master and every attached slave would suffice. Just unsure of the wiring I'm going to need and where to research.

Given that the ATtiny85 has 8 pins, 3 of which are Vcc, Gnd, and Reset, you don't have all that many to play with. This is starting to sound like an X-Y problem - rather than asking about flashing multiple chips either at once or individually, perhaps explain more about the project?

Here is an app note that can inspire: http://www.atmel.com/images/doc8079.pdf


text:
SendSMS example sketch hangs at PINMUNBER if statement
I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - sendsms in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

and never goes beyond it.
I didn't keep any pincode for my SIM card. please help

Post your code properly. Does the shield show any sign that it is on, like a blinking LED? Do you have a SIM attached?

...and please summarize your problem in the title. Success.

You can't just straight away to send SMS, you need to send commands to establish the Serial communication with the module, register to the network, and if the module acknowledged that it has register to the network, you can then start sending msg. Whatever library you are using, it should come with the examples, try those and try to understand the example code.

Try this sketch:
#include <SoftwareSerial.h>

SoftwareSerial gsm(2,3);
void setup() {
  Serial.begin(9600);
  gsm.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (gsm.available() > 0)
    Serial.write(gsm.read());
  while (Serial.available() > 0)
    gsm.write(Serial.read());
}

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.
Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to BOTH NL & CR and the baud rate to 9600. Enter AT from the serial monitor. If you recieve OK, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.
Then send the command AT+CREG? to check the SIM's registration status. If you get something like +CREG: *, 1 or +CREG: *, 5 (* means 'dont care'), then your SIM has been registered on the network. Report your results here.


text:
Error: invalid types 'int[int]' for array subscript
I am trying to get an Arduino to work with some Adafruit Motor shields.
Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.
Would anyone have a guess at what's wrong?
    //////// Imports
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    ////////My globals. Times are in milliseconds
    unsigned long currentTime = 0;
    unsigned long elapsedTime = 0;
    unsigned long startTime = 0;
    byte currentMotor = 1;
    byte currentShield = 1;
    byte motorRunning = 0;

    //// Settings

    // How many seconds between motors
    unsigned long endTime = 4000;

    // How many shields and motors per shield
    const int nShields = 1;
    const int nMotorsPerShield = 3;

    /////////MicroManager globals
    unsigned int version_ = 2;
    const unsigned long timeOut_ = 1000;
    byte currentPattern_ = 0;
    unsigned long time;

    /////////Adafruit globals
    Adafruit_MotorShield afms[nShields];
    Adafruit_DCMotor *motor[nShields][nMotorsPerShield];

    ////////////Setup
    void setup() {
      Serial.begin(57600);

      unsigned char address = 96;

      for (int i = 0; i < nShields; i++) {
        afms[i] = Adafruit_MotorShield(address);
        address = ++address;
        afms[i].begin();
      }

      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          motor[i][j] = afms[i].getMotor(j + 1);
          motor[i][j]->setSpeed(255);
        }
      }

      pinMode(13, OUTPUT);
    }

    ////////////////////Main
    void loop() {
      currentTime = millis();
      elapsedTime = currentTime - startTime;

      if (elapsedTime > endTime) {
        startTime = currentTime;
        currentMotor = currentMotor + 1;
        if (currentMotor > nMotorsPerShield) {
          currentMotor = 1;
        }
      }

      if (Serial.available() > 0) {
        int inByte = Serial.read();

        switch (inByte) {
          case 1:
            if (waitForSerial(timeOut_)) {
              currentPattern_ = Serial.read();
              if (currentPattern_ == 0) {
                for (int i = 0; i < nShields; i++) {
                  for (int j = 0; j < nMotorsPerShield; j++) {
                    motor[1][j]->run(RELEASE);
                  }
                }
              }
              else {
                switchMotor();
              }
              Serial.write( byte(1));
              digitalWrite(13, HIGH);
            }
            break;

          case 30:
            Serial.println("MM-Ard");
            break;

          case 31:
            Serial.println(version_);
            break;
        }
      }

      digitalWrite(13, LOW);
    }

    ////////////////Function definitions

    bool waitForSerial(unsigned long timeOut)
    {
      unsigned long starTime = millis();
      while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
      if (Serial.available() > 0)
        return true;
      return false;
    }

    void switchMotor()
    {
      int shield = currentShield - 1;
      int motor = currentMotor - 1;
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == motor)
            motor[i][j]->run(FORWARD);
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

Please post the full error message from the compiler. And the code where it occurs.

Take a close look at this line:
motor[1][j]->run(RELEASE);

Looks like it should be:
motor[i][j]->run(RELEASE);

Otherwise it is an illegal index (as there is only one shield).
The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.
void switchMotor()
{
  int shield = currentShield - 1;
  int motor = currentMotor - 1;
      ^
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == motor)
        motor[i][j]->run(FORWARD);
        ^
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

My guess is that this is where the compiler give you the error message!
Cheers!

To be able to help you must add the compiler error output with line, file, and the code. It is too much guessing otherwise.

Changing the int motor = and the j == motor to xmotor instead of motor allows it to compile perfectly fine for me. Just get rid of that variable naming conflict and it should be fine.

Thanks Mikael, the motor naming conflict was the problem!

I get a warning flag in UECIDE for the line:
address = ++address;

‣ operation on 'address' may be undefined [-Wsequence-point]

Increment address, and then assign the new value from address into address.  That seems a bit odd to me.  I think you just meant to increment:
address++;

Or
address = address + 1;

Also it flags up the 1 instead of i that Mikael found:

‣ array subscript is above array bounds [-Warray-bounds]

And of course there is the (somewhat hard to spot - Kudos to Mikael for finding it - it took me a bit to see it myself) naming conflict:

‣ invalid types 'int[int]' for array subscript

It was only when I used the advanced editing facilities of UECIDE to highlight all occurrences of motor that I found there was extra ones that shouldn't have been there causing the problem.

So just changing the integer variable name from motor to something else fixes it:
void switchMotor()
{
  int shield = currentShield - 1;
  int thismotor = currentMotor - 1;       // RENAMED MOTOR
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == thismotor)  // RENAMED MOTOR
        motor[i][j]->run(FORWARD);
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

Cheers, that was the issue!


text:
Creating a wireless remote
I am trying to create a wireless remote control to control a servo motor via Bluetooth. What all do I need to establish this? I did some research and found the following:
Tinyduino
Bluetooth low energy shield
Would these be enough (in addition to the servo motor) to establish my needs? Any advice on how I would go about coding this? I can research on the specifics but hints on functions to use would be greatly appreciated. Thanks!
I need to be able to control the system wirelessly (may it be Bluetooth or whatever) through a remote control. This remote control could be a push button system or an app on the phone. I do not have this designed yet. I do not know how to make iPhone apps so the best solution for me would be a simple push button on/off switch that can wirelessly tell the servo motor to either turn 90º clockwise or counterclockwise.
The RFDuino suggestion is very helpful, thank you for that. Can anyone recommend a push-button switch (small) that can wirelessly transmit the signal to the servo motor on the device? I hope this clears things up. Thanks!

You're a little vague here. You want to create the "remote control", or make your project "remote controllable" (I'm assuming thru your phone?)? Do you have the app/program for your phone already or are you yet to develop it? Or are you controlling via Bluetooth on another arduino?

As Madivad points out it's unclear what you're trying to do. Add some more details about the project and we can help you better.

@Madivad - thanks for the comment. I added more detail to my post. I need to make the project remote controllable and need to make a remote control for it. I cannot use an app since I do not know how to program iOS (though it would easiest to do this way if I could). Thanks!

I would also check out RFDuino.
Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.
The RFduino runs Arduino code and can do everything an Arduino can.


text:
Measuring resistance conceptually and in code?
How would I measure resistance over a certain length? In this case the resistance is variable.
What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.
I'm not sure if this would work, or how to implement it in code.
I've seen this forum post, but it's not making much sense to me.
How can I measure resistance?

Read up on voltage dividers. It's 2 resistors in series. Usually the resistor values are known and chosen depending on what output voltage you want given a set input voltage. But, if you have a known/unknown resistor and can measure the output voltage you can determine the value of the unknown resistor.

@sachleen That is a valid answer.

2 points: first, input current = output current (Kirchhoff's current law). Second: you mentioned a "certain length", do you really mean length or duration? If it is length, then an important question is about how long? Are we talking about centimeters, meters, kilometers?

Do you know what Resistance Value (in Ohms) your resistance is and how accurately you need to know the value? This would help answer the question. For example, measuring 0.01 Ohms would require a different approach than  measuring 1000 Ohms; and measuring to 50% accuracy would be very different to 0.1% accuracy.

you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).
Then what you need is a know resistence resitor, so you can set up a voltage divider and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)

So I saw the Wikipedia article you linked to on voltage dividers -- I'm still confused. Is a voltage divider something I need to buy (like a part), or can I make one myself? I saw a schematic on the wikipedia article using a resistor and a capacitor, but it didn't specify values for the parts...

I saw @sachleen's comment too, but I'm still confused!

no, you can build it yousel using only ONE resistor, see figure 2: Vin is 5V, Vout is what you read from analog pin, R1 and R2 are your know resistor and the resistence you want to know. lets say you want measure R1, then you know Vin, Vout, R2, and you use the formula at "To solve for R1:"
For the R2 value there is no a "right" value: it have to be choosen based on what you need. You know that ADC has only 10bit, so 1024 step, this mean it can measure 5V/1024step = 0.004V/step. Starting from this, and expected min/max R1 value, you can use the forula for R2 to fing a goo value!

Also, I thought resistors reduce current, not voltage!  Are we measuring current or voltage?

Read the wikipedia article, resistor work for current and voltage, it depends if they are on series or parallel. those are basic notion of electronics, you should look for a basic book in your nearest library


text:
Pro Mini not communicating with computer
when I try to upload blink program to my Pro Mini, I get this error:
avrdude stk500_getsync() not in sync resp=0x00

I've tried everything, changing the COM port, different USB cable and even another computer. Here is what I'm dealing with:
Arduino Pro Mini 328 5v 16M (Fake)
FT232RL USB to serial adapter
Nothing is connected to any pins on the Arduino, just trying to get LED to blink. I'm pretty sure the bootloader is installed, because when I hit the reset button, the LED blinks. I've tested the FTDI chip by connecting the TX and RX pins together, and it does echo in the serial monitor.
Help appreciated!

Did you install the driver? What OS are you on?

Yes, the driver has been installed. I'm currently running Windows 7, although I have an IMac if needed.

Just curious, what happens when you use your iMac? I'm trying to figure out if it's your computer or Arduino.

I will try tomorrow and get back to you soon.

I've tried with my iMac and I get this error
avrdude: stk500_recv(): programmer is not responding

You'll get a similar message if there is no bootloader on the atmega328. Maybe the fake pro-mini is just blank. You can flash the bootloader using a working arduino as ISP.

I don't have another Arduino. I an also pretty sure there is a bootloader because when I press the reset button, The LED comes on for about a second, and then turns off. It will also occasionally blink.

You did set the Serial Port and then tell the Arduino IDE that it's talking to a Pro Mini right?
This gets me every time I switch between my Nano & Uno.
On the main menu
[Tools]->[Board]=>"Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega 328"
I've also had this problem trying to use a longer USB cable, it just wouldn't work.  The stock cable (shorter) worked fine.


text:
HC-0# Bluetooth module questions
I've been playing with the HC-06 BT module lately, but now I want to do more with it and I'm not sure how to. I was wondering if it's possible to get signal strength from the module, or would I have to purchase another HC-0# module to do so? Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths.  You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered.  There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.


text:
Accessing Arduino Yun from Internet
I am trying to access my Arduino Yun from the internet, and it's not quite working. I have correctly port forwarded the port 5555 from the router to the Yun (verified I am able to access my many other NAT'd resources).
I can access the Yun from my internal network.
In the Arduino sketch I have this (among many other things). Mainly taken from example sketches.
#include <Bridge.h>
#include <HttpClient.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer server;

void setup {
   // Listen for incoming connections on port 5555
   server.noListenOnLocalhost();
   server.begin();
}

Is server.noListenOnLocalhost(); the right one to use to access from the outside world?

Well, I'm not familiar with the Yun, but the first thing that stands out is the missing
Bridge.begin();

line apparently needed to initialize the Bridge library that you use.
And you do have something like
YunClient client = server.accept();

and "more" in the main loop (or a function where applicable) of your code, right ?
And yes, noListenOnLocalhost() is the correct function for serving external clients.

Yes, I have Bridge.begin(); and YunClient client = server.accept(); is there within the loop. I'm able to access everything internally, just not externally.

So your answer helped me validate that what I am doing is correct. I'll mark it as solved. What ended up happening is that my router didn't save the NAT for port 5555. So I re-did that, and it's good. Thanks again for verifying that noListenOnLocalhost() is correct for external hits!

@Pat Glad to have... ahem... "helped" :-)

You did! I wasn't sure if noListenOnLocalhost() was correct, and the documentation on noListenOnLocalhost vs listenOnLocalhost wasn't overly clear (I think they both say the exact same thing).

The doc is "correct", but indeed not very explicit regarding internal VS external. And I must admit that when I first saw the function name I found it rather suspect.


text:
How do string pointers work in Arduino?
To the best of my understanding, when I declare
String s = "This is a string.";

what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write
int a = 1;
int* x = &a;
int* y = x;

what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write
String s1 = "This is a string.";
String s2 = "Hello World!";
s1 = s2;

does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write
String s1 = "This is a string.";
s1 = "Hello World!";

does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?
Thank you in advance for your help!

I suggest you study https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.cpp#L214. The expression s1 = s2 will invoke the overloaded assignment operator, which will, depending on the used C++ version, execute a move() or a copy. Expressions of the form s1  = "Some String value"; will result in a copy (see operator = (const char *cstr)). Also see https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

String is not a simple type like an int or a char. It is a class with many member functions and, more importantly, operators.  When you create the object it allocates room for that object either on the stack (for a local variable) or in the global data area if it's a global variable. However that object doesn't contain the memory used to store the actual string data - it only has a pointer. The memory for the string data is allocated on the heap using malloc() and realloc().
Assigning string data to the String object is done through the = operator defined in the class, of which there are a number of overloaded varieties:
String & String::operator = (const String &rhs)
{
    if (this == &rhs) return *this;

    if (rhs.buffer) copy(rhs.buffer, rhs.len);
    else invalidate();

    return *this;
}

#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & String::operator = (String &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}

String & String::operator = (StringSumHelper &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}
#endif

String & String::operator = (const char *cstr)
{
    if (cstr) copy(cstr, strlen(cstr));
    else invalidate();

    return *this;
}

String & String::operator = (const __FlashStringHelper *pstr)
{
    if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
    else invalidate();

    return *this;
}

They all, ultimately, call the copy() or move() functions which copy the data from the source into the memory allocated on the heap (increasing the allocation if needed).
Using:
String s1 = "Foo";
String s2 = s1;

s1 has memory allocated on the heap, then Foo\0 copied into it.  s2 then also has memory allocated on the heap, and the data from s1 is copied into it. So you have two separate objects with separate memory allocated for their content.  So then doing:
s2 += "bar";

you end up with:
s1: "Foo\0"
s2: "Foobar\0"

Since it's an object that's allocated on the stack (or in global space) and not a pointer to the object you can get a pointer to it like with an int:
String s1 = "Foo";
String *s2 = &s1;
(*s2) += "bar";

Which gives you just one object and one memory space, but two names for it, and the result is:
s1: "Foobar\0"
s2: "Foobar\0"

This is why it's important to use either pointers or references when passing String objects as parameters to functions, and the constant allocation and reallocation on the heap why String objects are frowned upon in microcontrollers with very limited RAM.

important to use either pointers or references when passing String objects as parameters to functions.
Updating this great explanation with couple examples of how to/not pass strings to func would be very helpful!


text:
Response from ESP8266 is returning unknown characters
I'm working on a project with Arduino UNO that needs connection with a cloud server, that is why I'm using ESP8266 module.
I'm already connecting to wi-fi and making GET and POST request but my problem is get the response from these requests.
Here is my code:
/* Doing all these steps to make the request
AT+RST
AT+CWMODE=1
AT+CWJAP="MyNetwork","MyPassword"
AT+CIPMUX=1
AT+CIPSTART=0,"TCP","myserver.com.br",80
AT+CIPSEND=0,270
*/

String data = "data=example";

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
comando += "User-Agent: Arduino/1.0\r\n";
comando += "Connection: Close\r\n";
comando += "Content-Type: application/x-www-form-urlencoded;\r\n";
comando += "Content-Length: " + String(data.length()) + "\r\n\r\n";
comando += data;

esp8266.println(command);

delay(2000);

String response;

while(esp8266.available()) {
  response += esp8266.readStringUntil('\r');
}

Serial.print("Request response: ");
Serial.println(response);

When I run this code the only response I can get is something like:
Recv 270 bxt⸮⸮C⸮
SEND OK

+IPD,0.569:HTTP/1.0 200 OK

But I was expecting a JSON.
Can someone tell me what I am doing wrong and how can I resolve it?

Edit.
Ok, after Code Gorilla helps me (Thank you so much) and a lot of research what I did was program Arduino UNO to send some commands that I invented to serial and program ESP8266 to read the serial and, depending of the command that it reads, do requests and stuff.
ESP8266 is a lot easyer to make requests and have a lot of others possibilities, like HTTPS requests, that you can't do using AT Commands.
When I create this ask I didn't know that I could program directly in ESP8266, but when Code Gorilla told me about it and helps me with some articles I could finally continue with my project.

try using the GET method instead of POST

This variable named "data" is the content of the POST

Try posting all your code, not a meaningless snippet.

you expect that after reading a line, the first character of the next line is immediately available

Why are you using an Uno?  Why not just program the ESP8266 directly (using the Arduino IDE and language), much quicker and you don't need to send everything via serial.

@CodeGorilla How can I exactly can do it? You have any article to indicate to me?

See my answer below

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
...
esp8266.println(command);

I suspect this is just a typo because it shouldn't compile.  But you are adding all the HTTP headers to commando not command.
Usually the ? means that the character is unprintable.  So to help diagnose the issue display the integer value for each character that is returned.  Something LIKE this (I've never used a String before so length() might not be right)
Serial.print("Request response: ");
Serial.println(response);
for (int index = 0; index < response.length(); ++index)
{
   Serial.print (response[index]);
   Serial.print (" ");
}

If you want to program the ESP directly then have a look at these guides, they should give you the general idea.  Its usually as easy as programming an UNO once you are setup.
http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
https://www.hackster.io/harshmangukiya/how-to-program-esp8266-with-arduino-uno-efb05f

I'm sorry, I think that I need to make a new question because I am not expressing my question very well. But your answer seems to be correct, the example shouldn't compile. Thank you!

Don't make a new question, edit the one above.  Use diagrams because then the language doesn't matter so much.

Thank you so much! I could not continue without your help. I edited the question with what I did to resolve it.


text:
Error to make a request using Arduino Uno and ESP8266
I'm using Arduino Uno and ESP8266 in a project.
I'm using AT Commands to connect to wi-fi and make a request. I'm using the monitor serial to test the code before compile it in arduino.
It is connecting to wi-fi and I can make a request to a server in my network but when i try to make a request to my web-service in cloud it doesn't work well.
The return is an HTML with an 404 page instead of what I am expecting:

Hello Versa

Here is my code:
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=18
GET /webservice/

Can someone help me telling me what I am doing wrong?

After see the answer of Maximilian Gerhardt, I solved it writing the following sequence in the monitor serialize:
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=70
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close
[Just press enter and send a new line]

what does the response code 404 mean?

An html page with saying "page not found"

A HTTP requests is comprised of more than just GET /webservice/. Take a look at what curl (console-line HTTP client) does.
C:\>curl -v "http://ternary.com.br/webservice/"
*   Trying 187.84.237.200...
* Connected to ternary.com.br (187.84.237.200) port 80 (#0)
> GET /webservice/ HTTP/1.1
> Host: ternary.com.br
> User-Agent: curl/7.46.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 11 May 2018 15:04:16 GMT
< Server: Apache
< X-Powered-By: PHP/5.6.30
< Vary: Accept-Encoding
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Expires: Wed, 11 Jan 1984 05:00:00 GMT
< X-UA-Compatible: IE=Edge,chrome=1
< Pragma: no-cache
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<

Hello Versa
* Connection #0 to host ternary.com.br left intact

You will have to at least transfer the minimal correct HTTP Headers of the form
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close

To get an answer. Also mind the ending \r\n\r\n. Refer to this website for more headers.
When I only send GET /webservice/ I also get 404 page.
C:\>cat test
GET /webservice/

C:\>cat test | ncat ternary.com.br 80
[...]
        <title data-i18n="[html]404_page.title">404 ÔÇô P├ígina n├úo encontrada</title>

Thank you so much! I solved it using these headers with HTTP/1.1


text:
ESP8266 serial monitor spitting out garbage
I am trying to set up a weather station, and I should just have the anemometer left. This code works fine (as far as I know).
// Pin definitions
const int reedSwitchPin = 2;

// Variables
volatile unsigned long lastRotationTime = 0;
volatile float windSpeed = 0.0;
const float windSpeedFactor = 2.4; // Factor to convert rotation time to wind speed

void setup() {
  pinMode(reedSwitchPin, INPUT_PULLUP);
  // attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
  Serial.begin(9600);
  Serial.println("hello world!");
}

void loop() {
  // Test reed switch functionality
  int reedState = digitalRead(reedSwitchPin);
  if (reedState == HIGH) {
    Serial.println("Reed switch triggered!");
  }

  // Calculate wind speed based on the time between rotations
  unsigned long elapsedTime = micros() - lastRotationTime;
  if (elapsedTime > 0) {
   windSpeed = windSpeedFactor / (float)elapsedTime;
  }

  Serial.print("Wind Speed: ");
  Serial.print(windSpeed);
  Serial.println(" m/s");

  delay(1000); // Delay for 1 second before measuring again
}

void handleRotation() {
  // Record the time of the last rotation
  lastRotationTime = micros();

}

But when I uncomment the following line:  attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
it prints garbage characters on the serial monitor. Here is the full code:
    // Pin definitions
const int reedSwitchPin = 2;

// Variables
volatile unsigned long lastRotationTime = 0;
volatile float windSpeed = 0.0;
const float windSpeedFactor = 2.4; // Factor to convert rotation time to wind speed

void setup() {
  pinMode(reedSwitchPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
  Serial.begin(9600);
  Serial.println("hello world!");
}

void loop() {
  // Test reed switch functionality
  int reedState = digitalRead(reedSwitchPin);
  if (reedState == HIGH) {
    Serial.println("Reed switch triggered!");
  }

  // Calculate wind speed based on the time between rotations
  unsigned long elapsedTime = micros() - lastRotationTime;
  if (elapsedTime > 0) {
   windSpeed = windSpeedFactor / (float)elapsedTime;
  }

  Serial.print("Wind Speed: ");
  Serial.print(windSpeed);
  Serial.println(" m/s");

  delay(1000); // Delay for 1 second before measuring again
}

void handleRotation() {
  // Record the time of the last rotation
  lastRotationTime = micros();
}

By garbage, do you mean that even if the anemometer is stopped, you get initially a high speed reading in the serial monitor which, continually reduces each second ?

by garbage, I mean random characters that make no sense

A picture is worth a thousand words. Add one to your question. If the esp8266 is continually crashing then it may write to the console at a baud rate other than the one you selected. Try changing this to 115200 or  74880 in Serial.begin() and the console to see readable output.

What happens if you remove anything else but the anemometer (hardware and source code)? What does the serial window say when you change the baudrate as suggested? Please [edit] your question and add this important information.

previously, I tried every  baud rate which got me a few things, but not what I wanted, also, I don't know what you mean to remove the anemometer, and also is this issue between the serial moniter or hardware, because if it is serial moniter, I can skip this part and try to put it directly onto the website. last thing, I don't really know what you want the picture to be of

The picture I referred to would ideally be a picture/screen dump showing the serial monitor while it is displaying these "garbage characters" or, if you have found a baud rate which shows more understandable text, that instead.

Pin 2 that is  gpio2 (D4) is not suitable for this esp8266 application because this pin must be high at boot time and your anemometer could be in either state. Try say pin 4 that is gpio4 (D2) instead or search for "best pins to use - esp8266"
A crash during boot time can result in characters being written to the serial monitor at a baud rate of 115200 or 74880.

Whoever voted down, please add a comment, why.

I wasn't the one that voted down but just saying that I thing I was using D2 not D4, at least hardware wise. should I try using D4 because D2 was the one I was using before?

@Iliketurtles   You appear to have difficulty with the two different pin numbering system in use on the nodeMcu. Search for a nodeMcu pinout diagram to see the translation between the GPIO and "D" pins. In the case here const int reedSwitchPin = 2; the 2 is a GPIO pin. On the nodeMcu board this is labeled D4. Try the suggestion I gave in my answer .

oh, so i should say in the code to use  const int reedSwitchPin = 4;

@Iliketurtles    Yes. const int reedSwitchPin = 4; is correct. So you then connect the anemometer to the pin marked D2 on your nodeMcu board. If you have anything else connected to other pins on your nodeMcu, say a led, then temporarily disconnect these. If you still have problems then select the baud rate which gives the most understandable output on the serial console and add this output to your original question.

I have a slight problem: I have kind of soldered the pins in place and that includes an analogue pin(A0(again from the pin marking on the board)), as well as its gnd and +5v pins. I am also getting this problem where the port dropdown is greyed out

@Iliketurtles It is clearly getting worse. What you are now describing is either a problem with the IDE installation or the USB functionality of your NodeMCU. It must have worked better before for you to have seen the "garbage" characters which you reported originally. Maybe open a new topic exclusively for this latest problem.


text:
How to read Ultrasonic sensor value to use and drive servo motors
I would like to know how i can use my ultrasonic value in an if else statement, so i can use the value that the servo motors stop running and go in another direction when the ultrasonic sensor gets close to an object.
/*
  Digital pin 2 is connected to a switch
  Digital pin 3 is connected to a switch
  Digital pin 7 is connected to the echo port of the ultrasonic sensor
  Digital pin 8 is connected to the trig port of the ultrasonic sensor
  Digital pin 9 is connected to a servo
  Digital pin 10 is connected to a servo
  Digital pin 13 is connected to a LED

 */

#include <Servo.h> // include a special file that is needed for servo motors, do this only once

Servo motor1; // create a servo object for each motor
Servo motor2;

int echo = 7; //declare echo from ultrasonic sensor
unsigned long duration;
void setup() {
  // initialize the LED pin as an output:
  pinMode(13, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(2, INPUT);
    // switch 2 initialize
    pinMode(3, INPUT);
  // initialize the servo on pin 9
  motor1.attach(9);
  // motor 2 initialize
  motor2.attach(10);
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    //echo pin of ultrasonic sensor
    pinMode(echo, INPUT);
    //trig pin of ultrasonic sensor
    pinMode(8, OUTPUT);

}

void loop() {
      // the trigger pin sends a pulse
       digitalWrite(8, LOW);
       delayMicroseconds(2);
       digitalWrite(8, HIGH);
       delayMicroseconds(10);
       digitalWrite(8, LOW);
       duration=pulseIn(echo, HIGH);
      // the echo pin measures how long it took for that pulse to come back
       Serial.println(duration);
      // delay in between reads for stability
       delay(50);
       duration=pulseIn(echo, HIGH);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if(duration <=400) {
    // turn LED on:
    digitalWrite(13, HIGH);
    // turn the motors off for 2 seconds
    motor1.write(90);
    motor2.write(90);
    delay(2000);
    //turn motor 1 on for 2 seconds to make a turn
    motor1.write(180);
    delay(2000);
  } else {
    digitalWrite(13, LOW);
    //motors run when vehicle is not near objects
    motor1.write(0);
    motor2.write(180);
  }
}

So what is the problem so far? Does the code not work? Please be more specific.

The sensor shows me all the values in the console but i dont know how i can use those values in an if else statement so that my servo motors would stop and turn around when the sensor gets close to an object. The code works when i use a switch in the if else, but now i want to use the ultrasonic sensor to be the switch in stopping the servo motors.

First, I would make sure I have continuous servo motors that can rotate 360 degrees. Your servos will just rotate to the degree you entered if they are not continuous. Additionally, it would be more helpful if you named your pins. For example:
int echo = 7;
void setup(){
    pinMode(echo, INPUT);
}

This will help us read the code better.
I also see that you have "pulseIn" in your if statement. You must save the value to a variable with the data type of unsigned long.
//before the setup
unsigned long duration;

//keep your setup as it is

void loop(){
   digitalWrite(8, LOW);
   delayMicroseconds(2);
   digitalWrite(8, HIGH);
   delayMicroseconds(10);
   digitalWrite(8, LOW);

   duration=pulseIn(echo, HIGH);

   if(duration<=400){//check for the value
       // turn LED on:
        digitalWrite(13, HIGH);
        // turn the motors off for 2 seconds
        motor1.write(90);
        motor2.write(90);
        delay(2000);
        //turn motor 1 on for 2 seconds to make a turn
        motor1.write(180);
        delay(2000);
   }else{
        digitalWrite(13, LOW);
        //motors run when vehicle is not near objects
         motor1.write(0);
         motor2.write(180);
       }
   }

Overall: check your servos and save the value of pulseIn to a variable. You might also want to convert to centimeters by dividing duration by 58.2.

the led goes on now when i put my hand in front of the sensor and off when i get my hand away, but the motors do not continue running. When before they would just go on forever

@S.Mateijsen What power source are you using? So the LED goes off, motor 1 stops and motor 2 is already stopped? And they just stay at rest?

im using 4 AA batteries and my laptop as power, the led stays on untill i remove my hand(thats also whats supposed to happen so the led works) the motors just rotate a bit around and then stop at there angles

turned out my batteries where almost empty :< But now the motors both go on at the start. after a couple seconds the led goes on and he makes a turn. but he keeps making turns now and doesnt go right ahead anymore so he keeps looping the if duration <=100 statement and doesnt come to the else part.

First check your batteries. Maybe they are dead. It happened to me yesterday. A servo was working and then in the middle it always shut off. Can you confirm that they are continuous servos? Post a picture of them or a link where you got them. The phrase "at their angles" confuses me. Do the servos stop at 0 and 180 degrees? If yes, then they are not continuous.

If you are using your computer for power, the chances are that your computer is in the way of the sensor. It might always read low values and trigger the if statement. Try using a 9V battery to power the arduino and out the robot on the floor in an open space without obstructing the sensor.

It would also be helpful for you to post the updated draft of the code you are using now.

The servos are continuous servos they keep running now(problem was the batteries) I also tried to put it in on open area where nothing would be in front of the sensor but it keeps looping the "stopping and making a circle part" instead of going straight ahead. and i updated the main post with my current code.

Try reading the Serial Monitor and seeing if the duration values actually change. You might have a defective sensor. Also, does the LED turn off in a wide area or no?

The sensor puts the values out like every 2 seconds in the console with a value of 7000 so it shouldnt be doing the <=100 statement at all. The LED also stays on in an open area.

What if you put your hand in front of the sensor? Still 7000? Also do Serial.println(duration) not Serial.println(pulseIn(7)). The second option will cause the duration to become 0 after printing because the signal will have already been collecting and pulseIn will return 0 the second time.

i updated the main post again, the sensor gives me the values now and when i put my hand infront of it it becomes like 200 and when i dont the values is around 17000.

That is not what I meant with Serial. First save pulseIn to duration. Only then print it out and then do the if statement. If you called pulseIn twice, the second time will give you a 0 and the first time will give you the right value.

Cheers man! that was the problem it works perfectly now :D


text:
Setting 10 RGB Strips Independently from Single Arduino
I want to control 10 different 12V RGB LED strips independently from a single Arduino.
As a clarification - I've setup a bunch of NeoPixels and understand how to wire and control them independently. So now I'm looking to do something similar but rather than set color of individual LED's, I'm looking to set color of LED strips.
I've already done all the research to understand how to use a MOSFET to control a single strip - but that requires 3 PWM outputs on the Arduino board and I don't see any boards that have 3 * 10 = 30 PWM outputs.
Are there existing controllers that can abstract the power conversion and voltage control, so I can just send a color and brightness setting from the Arduino to each strip?

How many leds per strip (i.e. how much current per strip)?

How about using an extra chip as driver. Something like this. Or, if you haven't bought the strips yet, you can by the individually addressable strips. They don't need PWM, but only one pin for shifting out the data

@chrisl - thanks for the reply. The chip as a driver looks interesting. To then control the color on an RGB strip would I need to connect a Mosfet to each R/G/B output of the chip?
I want to avoid the neopixel strips as it's overkill for this project. I.E. I don't need to address individual LED's, but do want to control several separate strips.

@Gerben - I'm hoping to connect many strips together to form larger strips. So probably 10 strips with each strip being 60-300 LED's

Yes, surely you need a MOSFET for each PWM line, since LED strips with this many LEDs can easily draw multiple amps. I mentioned the Neopixels, because despite the individual addressing might be an overkill you don't need further components (besides a capacitor and a resistor). So this might be the cheaper solution, depending on the strips.

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLED library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".
Wiring:

Example code:
#include <FastLED.h>

#define NUM_LEDS 10
#define DATA_PIN 3
#define CLOCK_PIN 2

CRGB leds[NUM_LEDS];

void setup() {
    FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

int hue = 0;
void loop(){
    for(int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
    }
    FastLED.show();
    delay(20);
    hue += 2;
}

You'll need external circuitry to control the actual LEDs.
There is the WS2811 chip which can control 3 channels of 12V LED strips controlled though a single wire and you can daisy chain them controlling each strip individually. The protocol is the exact same as you'll find in individually addressable RGB LEDS. In fact it's the same IC that is embedded in those LEDs.


text:
Connect one HC-05 "master" to two slaves at the same time
Does any one know what AT+CMODE=2 "slave loop" used for. As I try to connect one HC-05 master to two slaves using it, but it didn't work.
i donot know if AT+cmode=2 is used for connecting to multiple slaves or not as i want to know what is used for , i tried to understand what it do from the HC-05 datasheet but i didnot find anything useful about it excpet for what is this image

why do you think that AT+cmode=2 is used for connecting to multiple slaves? .... please provide a link to the source of your information

HC-05 CANNOT connect to more than one slave at a time. This wouldn't even make sense, since this is a bluetooth to serial/UART module. UART can only work between two devices, not more

AT+CMODEis mainly used for setting the address pairing purpose. What chrisl stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as 2 you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.

Based on the documentation :
Slave (slave role)----Passive connection;
Slave-Loop----Passive connection, receive the remote Bluetooth master device data and send it back to the master device;
Master (master role)----Inquire the near SPP Bluetooth slave device, build connection with it positively, and build up the transparent data transmission between master and slave device.
More info here : http://www.linotux.ch/arduino/HC-0305_serial_module_AT_commamd_set_201104_revised.pdf
So if you want your HC-05 master send : AT+ROLE=1
If you want it to connect to a device safely send : AT+CMODE=0 but you have then to specify what address ( AT+BIND= )
If you want it to connect to all devices available send : AT+CMODE=1


text:
Why I always see while(serial.available() > 0) as the standard way of reading serial data?
Examples online always show this code to read bytes from the serial interface:
while(serial.available() > 0)
{
      char receivedByte = serial.read();
}

But I don't understand why it works.
The read() operation "removes" a single byte from the queue, so the while loop should consume all the bytes from the queue.
However, what guarantees that the incoming bytes are being pushed into the queue faster than the consuming process? I would imagine that any Arduino board is order of magnitude faster than a standard serial transmission, so it would starve the queue and effectively exit the while loop even though there are more incoming bytes to process.
What am I missing here?

You're right. It depends on what else is done in the while block.
BTW: byte is a data type in the Arduino environment, better don't use it as a variable name.

@DataFiddler fixed

an if block would make more sense than a while block

what guarantees that the incoming bytes are being pushed into the queue faster than the consuming process?

Nothing. In the code handling the transmitted data you need to account for that. The fact, that serial transmission is not as fast as the code runs, doesn't matter, when you regularly check execute that while loop again (on each iteration of a non-blocking loop() for example). The code shouldn't rely on a full message being received inside that while loop. The data is normally saved into its own buffer and only processed, when a full valid message is in there (which can be checked by using a delimiter byte at the end of each message). So this makes more sense in the context of the rest of the corresponding serial code.
Though you should always keep in mind, that there are many many codes for Arduino online and that many of them are not that good.

That's the answer I was hoping for. Some sloppy implementations use a small delay(x); inside the loop to guarantee that at least 1 new byte is present when re-checking the while condition. The x depends on the baud rate. Reading piece by piece over the main loop() makes sense, but then one has to guarantee that the overall loop() execution time does not exceed the time required to fill up the serial queue, otherwise bytes would be lost. Isn't it ?

Yes, in that case loop() should be non-blocking. Though this is recommended either way, because it enables you to do multiple things simultaneously, basically multitasking, and keeping everything responsive.

Examples online always show this code ...

 while(serial.available() > 0)
 {
       char receivedByte = serial.read();
 }

You wouldn't have seen this "always" because it is Serial and not serial.
Also the code you posted would be useless because it would repeatedly read into the same byte and do nothing with it.
Assuming you are taking a bit of a licence with what you actually saw, it would be better for the code to gradually fill a buffer (and check for overflow) and then when a newline or other delimiter arrives, do something with it.
You are right that you would, generally speaking, read faster than data arrives. You are also right that putting delays in is a silly way of trying to allow for that.
I have an answer on this site plus a page with suggested code which goes into more detail.
Those posts might help.


text:
HC-05 3.3 voltage regulation
HC-05 Bluetooth RX requires 3.3 v (TX has a regulator built in)
I understand my uno and nano are 5v
Ive connected a 3.3v Zennor in series with a led and resistor and with multimeter established the black stripe goes ground to achieve 3v
But which is considered ground between hc-05 RX or the arduino TX that it connects to..
Is this an acceptable way to drop the voltage?
If not I've ordered some small voltage regulators.
But I still have the same question, which way round.
The regulator has connections v1...gnd...vo
Thanks Paul
(Edit to this post)
Ive read a bit more and if correct I now think the Hc-05 rx connects direct with the arduino tx and the Zennor connect anode to the link and stripe side to ground...
Still unsure..

All you need are two resistors. As shown in every single tutorial for using the HC-05 with an Arduino.

Thanks... Where are thease tutorials? . I've watched 12 now on YouTube and they are all connecting them direct. One guy at the start mentioned he was going to use two resistors then proceeded not to use any in his video..

YouTube is worse than instructables for being full of crap. Type "hc-05 Arduino" into Google and look at the pictures.


text:
Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs?
It's clearly documented that when global data is shared with an ISR and the main program, the data needs to be declared volatile in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). Here we have good rules:

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

But is volatile needed when the variable is accessed from > 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a static variable:
void func() {
    static volatile long counter; // volatile or not?
    // Do stuff with counter etc.
}

That function is called in two ways: from pin interrupt, and from TimerOne library:

attachInterrupt(0, func, CHANGE);
Timer1.attachInterrupt(func);

There are no atomicity problems, since when an ISR is entered, interrupts are automatically disabled, but this volatile is more of a compiler question: what is cached and what is not.
Better safe than sorry, of course...

volatile only informs the compiler's code generator that the variable may be modified by something other than the code being generated, so not to assume any copy of it remains accurate.
ISR code must be written/generated under the assumption that it has no context at entry, and preserve the CPU's context around its (ISR's) own operation. So, as with the indivisbility of non-atomic operations, volatility depends, in this case*, on whether or not interrupts are allowed to nest. If non-nesting is guaranteed, the shared variable can not change by other than this ISR during its own execution. If your ISR might someday be used in an environment where interrupts are allowed to nest, then that constraint will no longer hold.
* in this case:
I'm assuming a software-maintained variable here. If we're talking about a variable that can be updated by a hardware event, a timer register for example, all bets are off: the variable is volatile no matter what.

So, as long as I don't change Arduino's default "interrupts don't nest" behavior, then the variable doesn't need to be volatile, since it's not modified by anything other than the code being generated; compiler can "assume" that the ISR executes linearly, and it does, as long as interrupts don't nest. That makes sense. Thanks!