message:
How to run servo 180 degrees and stop?

I'm creating a PIR motion sensor doggy door.

The problem I'm having with it is, it runs 3 times, I've figured out how to pause when reaches 180° but not how to stop.

I was thinking I could use detach my servo and attach after a delay of 30,000 and then re-attach return to 0 degrees, then wait for next PIR high.

But I don't know how to code it into what I have or even if it would work.

My code:
<!-- language: lang-cpp -->

    /* This code sweeps a servo from 0 degrees to 180 when the PIR sensor detects motion.
       Special thanks goes to the author of the PIR sensor code, whose code helped tremendously
       in the making of this code and Instructable.
       author of PIR sensor code: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at
    **/

    #include <Servo.h>

    Servo myservo; //creates a servo object
    //a maximum of eight servo objects can be created
    int pos = 0; //variable to store servo position
    //amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
    int calibrationTime = 30;
    //the time when the sensor outputs a low impulse
    long unsigned int lowIn;
    //the amount of milliseconds the sensor has to be low
    //before we assume all motion has stopped
    long unsigned int pause = 5000;
    boolean lockLow = true;
    boolean takeLowTime;
    int pirPin = 12; //digital pin connected to the PIR's output
    int pirPos = 13; //connects to the PIR's 5V pin

    void setup() {
      myservo.attach(4); //attaches servo to pin 4
      Serial.begin(9600); //begins serial communication
      pinMode(pirPin, INPUT);
      pinMode(pirPos, OUTPUT);
      digitalWrite(pirPos, HIGH);
      //give the sensor time to calibrate
      Serial.println("calibrating sensor ");
      for (int i = 0; i < calibrationTime; i++) {
        Serial.print(calibrationTime - i);
        Serial.print("-");
        delay(1000);
      }
      Serial.println();
      Serial.println("done");
      //while making this Instructable, I had some issues with the PIR's output
      //going HIGH immediately after calibrating
      //this waits until the PIR's output is low before ending setup
      while (digitalRead(pirPin) == HIGH) {
        delay(500);
        Serial.print(".");
      }
      Serial.print("SENSOR ACTIVE");
    }

    void loop() {
      if (digitalRead(pirPin) == HIGH) {
        //if the PIR output is HIGH, turn servo
        /*turns servo from 0 to 180 degrees and back
          it does this by increasing the variable "pos" by 1 every 5 milliseconds until it hits 180
          and setting the servo's position in degrees to "pos" every 5 milliseconds
          it then does it in reverse to have it go back
          to learn more about this, google "for loops"
          to change the amount of degrees the servo turns, change the number 180 to the number of degrees you want it to turn
        **/
        for (pos = 0; pos < 180; pos += 1) {
          //goes from 0 to 180 degrees
          myservo.write(180);
          delay(8000); ////stops motor for 8 seconds
          for (pos = 180; pos >= 90; pos -= 1) {
            // goes from 180 degrees to 0 degrees
            myservo.write(pos); // tell servo to go to position in variable 'pos'
            delay(15); // waits 15ms for the servo to reach the position
          }
          myservo.write(90);
          delay(4000); //stops motor for 4 seconds
          for (pos = 90; pos <= 180; pos += 1) {
            // goes from 0 degrees to 180 degrees
            // in steps of 1 degree
            myservo.write(pos); // tell servo to go to position in variable 'pos'
            delay(15); // waits 15ms for the servo to reach the position
          }
          //to make it go slower, increase the number.
          if (lockLow) {
            //makes sure we wait for a transition to LOW before further output is made
            lockLow = false;
            Serial.println("---");
            Serial.print("motion detected at ");
            Serial.print(millis() / 1000);
            Serial.println(" sec");
            delay(50);
          }
          takeLowTime = true;
        }

        if (digitalRead(pirPin) == LOW) {
          if (takeLowTime) {
            lowIn = millis(); //save the time of the transition from HIGH to LOW
            takeLowTime = false; //make sure this is only done at the start of a LOW phase
          }
          //if the sensor is low for more than the given pause,
          //we can assume the motion has stopped
          if (!lockLow && millis() - lowIn > pause) {
            //makes sure this block of code is only executed again after
            //a new motion sequence has been detected
            lockLow = true;
            Serial.print("motion ended at "); //output
            Serial.print((millis() - pause) / 1000);
            Serial.println(" sec");
            delay(50);
          }
        }
      }
    }

Could I also just change the jumper pin on the PIR hardware for a retriggering set high to keep the door open when the dog is there so it won't just close on them?

I'm using this PIR:
[![pir][1]][1]

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

body:
I haven't been able to compile or test this but I think it should do what you are asking for, or at the very least steer you in the right direction.

    // This code waits for a signal from the PIR sensor.
    // When the signal is recieved it rotates the servo 180 degrees and waits 30 seconds
    // it then rotates the servo back to 0 (to close the door)

    #include <Servo.h>

    const int ServoIntraStepDelay   =  15;      // Delay between servo steps (ms)
    const int ServoAngleStep        =   1;      // The angle by which the servo position is changed every step (degree)
    const int ServoAngleMinimum     =   0;      // The min angle of the servo (degrees)
    const int ServoAngleMaximum     = 180;      // The max angle of the servo (degree)
    const int DoorOpenPeriod        = 30 * 1000;// The time the door will remain open for (ms)
    const int DoorClearPoll         = 100;      // The interval betwen polls to the sensor when checking to see if the door is clear(ms)
    const int DoorClearPeriod       = 5000;     // The interval that the PIR sensor must report low before closing the door (ms)

    const int PIRCalibrationTime    = 30;       //amount of time we give the sensor to calibrate(10-60 secs according to the datasheet) (s)

    const int PinPIRData            = 12;       //digital pin connected to the PIR's output
    const int PinPIRPower           = 13;       //connects to the PIR's 5V pin
    const int PinServoPower         = 4;        // The pin that controls the servo.

    Servo myservo;                              //creates a servo object

    void setupCalibratePIR()
    {
            //give the sensor time to calibrate
        Serial.println("Calibrating sensor ");
        for(int i = 0; i < PIRCalibrationTime; i++)
        {
            Serial.print(PIRCalibrationTime - i);
            Serial.print("-");
            delay(1000);
        }
        Serial.println();
        Serial.println("done");
        //while making this Instructable, I had some issues with the PIR's output
        //going HIGH immediately after calibrating
        //this waits until the PIR's output is low before ending setup
        Serial.print("Waiting for PIR sensor to report low");
        while (digitalRead(PinPIRData) == HIGH)
        {
            delay(500);
            Serial.print(".");
        }
        Serial.print("SENSOR ACTIVE");
    }

    void turnServo (const int& from, const int& to, const int& step)
    {
        for(int pos = from; pos <= to; pos += step)
        {
            myservo.write(pos);
            delay(ServoIntraStepDelay);
        } //to make it go slower, increase the number.
    }

    // Test the PIR sensor and ensure that it reports low for a specific time
    void waitForDoorClear ()
    {
        bool doorIsNotClear = true;
        while (doorIsNotClear)
        {
            doorIsNotClear = false;
            for (int doorClear = 0; !doorIsNotClear && (doorClear * DoorClearPoll) < DoorClearPeriod; ++doorClear)
            {   // Poll every few ms and check that the sensor in LOW
                // As soon as it is high this loop will exit which restarts the time that the low signal must been seen for.
                delay (DoorClearPoll);
                doorIsNotClear = (digitalRead(PinPIRData) == HIGH);
            }
        }   // This is potentially an infinite loop.
    }

    void setup()
    {
        Serial.begin(9600);                     // Begins serial communication
        myservo.attach(PinServoPower);          // Connect to the servo object
        pinMode(PinPIRData, INPUT);             // Connect the PIR data
        pinMode(PinPIRPower, OUTPUT);           // Connect the PIR power
        digitalWrite(PinPIRPower, HIGH);        // Turn on the PIR power

        setupCalibratePIR();                    // Calibrate the PIR sensor
    }
    // attach
    void loop()
    {

        if(digitalRead(PinPIRData) == HIGH)
        { //if the PIR output is HIGH, turn servo

            turnServo (ServoAngleMinimum, ServoAngleMaximum, ServoAngleStep);
            delay (DoorOpenPeriod - DoorClearPeriod);
            waitForDoorClear ();
            turnServo (ServoAngleMaximum, ServoAngleMinimum, -ServoAngleStep);
        }
    }

You weren't that far off.


sender: user

message:
Why am I always getting 48 with serial communication?

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

The problem is that I always get 48 back.

My matlab code:

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

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

and my arduino code:

In the setup:

    Serial.begin(115200);

In the loop:

    delay(100);
    myFunction();

In myFunction:

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

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

sender: assistant

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

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


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

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

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

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

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

  [1]: http://www.eltima.com/products/serial-port-monitor/


body:
> Why am I always getting 48 with serial communication?

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

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

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

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

  [1]: https://www.arduino.cc/en/Serial/Read
  [2]: http://www.asciitabell.se/


message:
Server checkbox not working properly

I am trying to make an arduino alarm clock to which you can send alarm clock times over the web.
This is the HTML code

     <input type="checkbox" name="alarm1" id="alarm1">1</button>
It's sending the HTTP correctly but the rest of the code insists that the alarms are always on.

          if (_server.arg("alarm1") = "on") {
       alarm1 = true;
       Serial.println("Alarm 1 is set");
      }
      else {
       alarm1 = false;
       Serial.println("Alarm 1 is inactive");
      }

body:
The alarm is always on because you are setting it to be always on.  You code should say:

     if (_server.arg("alarm1") == "on") {


message:
Printing the messages having problem in SIM 900A to Arduino

I have added my Arduino code for reading messages from GSM SIM900A using Arduino. But the output is showing something different. Please help me.

    #define SERIAL_BUFFER_SIZE 256

    char msg;
    void setup() {
      Serial.begin(9600);   // Setting the baud rate of GSM Module
      delay(60000);
      Serial.println("AT");
      delay(1000);
      Serial.println("AT+CREG=1");
      delay(1000);
      Serial.println("AT+CMGF=1"); // set SMS mode to text
      delay(1000);
      Serial.println("AT+CMGR=\"ALL\"");
      delay(1000);
      Serial.println("AT+CMGR=\"ALL\"");
      delay(1000);
      while ( Serial.available() > 0) Serial.read();  // removing serial buffer values
      Serial.println("AT+CMGR=1");
      delay(2000);
    }

    void loop() {
      while (Serial.available() > 0) {
        msg = serial.read()
        Serial.print(msg);
      }
    }

This is the output:

    +CMGR: "REC READ","+91xxxxxxxxxx","","16/07

body: Hello Guys i found the issue. Serial.read() function reads only 62bytes. After i have update the serial buffer size in library file C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.H ... It shows the messages which is stored in serial buffer.


message:
Size of String array

I am trying to find out the size of an array like this:

     String days[3] = { "Mon", "Tue", "Wed" };
 Serial.printf("Size of array: -\n", sizeof(days));
 for (int i = 0; i < sizeof(days); i++) {
  Serial.print(days[i]);
 }

The result of the code above is 36 which is incorrect.

Do I have any other options considering that I don't know the size of the array to begin with?

body:
No, the result is correct, you're just interpreting it incorrectly. If you want the number of elements in a statically-allocated array use:

    sizeof(somearray) / sizeof(somearray[0])


message:
Is possible to concatenate integers?

It's a basic one: I have two values from two different analogRead pins:

    int val1;
    int val2;

For example, val1 = 10 and val2 = 10. How could I put these two values into a variable val3 = val1 + val2 that will give the answer 1010, instead 20 ?

body:
This is not even remotely related to Arduino but mathematics.
As Mikael Patel pointed out this can be done fairly easy.
You might tell us your intent.
If you are seeking for a way to pack values tightly you may consider [Integer Sequence Enconding][1].
But without more detailed information this will be just a guess.

  [1]: https://prtsh.wordpress.com/2014/01/18/integer-sequence-encoding/


body:
If you are reading from the analog pins then the values are 10 bits (not 8 as suggested above).  Are you looking at concatenating 2 10 bit numbers or 2 16 bit numbers or are you using a zero or duo in which case they could be 12 bit numbers.

In any case:

    const int BITMASK = 0x3FF;  // 10 bits = 0x3FF, 12 = 0xFFF, 16 = 0xFFFF
    const int BITWIDTH = 10;
    long result = ((value1 & BITMASK) << BITWIDTH) | (value2 & BITMASK);

I suspect it won't give you the answer you want, but...


body:
You want to send a string of data that represents the data from a number of sensors. For example let's say you have 2 10 bit analog readings and 4 Boolean readings, high or low from the digital pins.  You can compress this into 24 bits of data, or 3 bytes.

If your transmission library supports binary writing and reading then you can send it as 3 unsigned chars.

If your transmission library doesn't support binary then you can either base64 encode it as 4 bytes. (The numbers are converted into printable characters that represent their value).  Or a more light weight solution would be to write each byte as two hexadecimal digits.

You pack the data into three bytes by using bit masking and shifting (as per my other answer).

 int sensor1data = 512;
 int sensor2data = 64;
 bool digital1 = true;
 bool digital2 = false;
 bool digital3 = false;
 bool digital4 = true;

 unsigned char data[3]{ 0, 0, 0 };

 // Take the top 8 bits of the 10 bit data on sensor1data
 // 0x300 takes the 2 lowest bits of the upper byte
 // 0x0FC takes the 6 highest bits of the lower byte.
 // Shift the result 2 places right so the what was bit 2
 // of the upper byte becomes the most significant bit (MSb)
 // in the result byte.
 data[0] = (sensor1data & 0x3FC) >> 2;

 // Take the 2 lowest bits of the lower byte (0x03)
 // Shift the 6  places left to make them the MSb of the
 // result byte.
 data[1] = ((sensor1data & 0x3) << 6);
 // Take the 6 MSbs of the sensor2data and left shift them
 // so that they become the LSbs of the result byte.
 // The result is ORed onto what is already in the result
 // to retain the previous instruction.
 data[1] |= ((sensor2data & 0x3F0) >> 4);

 // Take the 4 LSbs of sensor2data and shift them right
 // for places to ocupy the 4 MSbs of the result.
 data[2] = ((sensor2data & 0xF) << 4);
 // OR each of the flags into the result, shifting by
 // a different amount each time.
 data[2] |= (digital1 ? 1 : 0) << 3; // I explicitly convert the bool to an int
 data[2] |= (digital2 ? 1 : 0) << 2; // because some older compilers don't always
 data[2] |= (digital3 ? 1 : 0) << 1; // use 1 for true.
 data[2] |= (digital4 ? 1 : 0);


body:
If you know in advance how many variables' values you want to transmit:

    char output[100+1];
    ....
    snprintf(output, sizeof(buffer), "%d,%d,$d\n", val, val2, val3);

If not and you need to build the string "as you go":

    char output[100+1] = "";
    char oneVal[12+1];
    ...
    snprintf(oneVal, sizeof(buf), "%d,", value);
    strcat(output, oneVal);

    // more of the above, possibly in a loop.
    ...
    strcat(output, "\n");      // if you need a newline at the end


body:
It sounds to me, from your comments, that what you want to do is turn this:

    myRadio.transmit(val1);
    myRadio.transmit(val2);

into something more like this:

    myVal = join(val1, val2);
    myRadio.transmit(myVal);

That's all pseudocode of course, and those functions are in themselves nonsense, but it serves to illustrate.

So you want to turn two values into one single block of data for sending thus reducing the overall transmission overhead of the packet (one large packet instead of two smaller packets).

What you are actually looking for is called a *struct* and looks something like this:

    struct MyData {
        int val1;
        int val2;
    };

That creates a new variable type which contains two sub-variables in it. You then use it like any other variable:

    struct MyData data;

You can then get at the values inside it with:

    data.val1 = analogRead(A1);
    data.val2 = analogRead(A2);

And the whole thing can be transmitted in one block with whatever functions your RF library provides:

    myRadio.transmit(&data, sizeof(struct MyData));

Receiving at the other end is just the same - as long as the receiving end has the same structure. Receive into a MyData structure variable and you can get at the individual sub-variables:

    struct MyData data;
    myRadio.receive(&data, sizeof(struct MyData));
    Serial.print(data.val1);
    Serial.print(",");
    Serial.println(data.val2);

Of course, you need to read up on whatever library it is you're using to do your transmitting and receiving to find the actual correct functions to call to transmit and receive a block of data like that...


message:
Arduino UNO HTTPS

Is it possible to call a HTTPS web service on arduino UNO? I am trying to connect it through client.connect(ip,port). It said connected but never respond, ended up in TIMEOUT.

body:
No, it is not possible. The Arduino UNO is not powerful enough to encrypt the data for an SSL connection. On top of that the W5100 chip used on the Ethernet shield has its own IP stack built into it, and that stack doesn't support SSL either.

If you require SSL then it is recommended that you use one of the "dual" boards, like the Yun, and have the Linux portion of the board make the SSL connection for you using cURL.


message:
Trying to figure out how to use an extension board with Pi

I am trying to make the following board work with Raspberry Pi.
Board Name: `L293D Motor Drive Shield Expansion Board for Arduino Mega Raspberry Pi`

[![L293D Motor Drive Shield Expansion Board for Arduino Mega Raspberry Pi][1]][1]

All I need to know is which pins do the following:

 1. Enable the motor
 2. Disable the motor
 3. Rotate forward
 4. Rotate backward

More information about the board:

 1. https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors
 2. https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=16118

Can someone please help me find this information?

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

body:
> The following pins are in use only if the DC/Stepper noted is in use:
>
> - Digital pin 11: DC Motor #1 / Stepper #1 (activation/speed control)
> -  Digital pin 3: DC Motor #2 / Stepper #1 (activation/speed control)
> -  Digital pin 5: DC Motor #3 / Stepper #2 (activation/speed control)
> -  Digital pin 6: DC Motor #4 / Stepper #2 (activation/speed control)
>
>The following pins are in use if any DC/steppers are used
>
> -  Digital pin 4, 7, 8 and 12 are used to drive the DC/Stepper motors via the 74HC595 serial-to-parallel latch
>
> The following pins are used only if that particular servo is in use:
>
> - Digitals pin 9: Servo #1 control
> - Digital pin 10: Servo #2 control

([source](https://learn.adafruit.com/adafruit-motor-shield/faq))


message:
Sending a text/notification with Arduino + ESP8266 Wifi shield

Is it possible to send a text message using an Arduino and the Sparkfun ESP8266 Wifi Shield using Temboo? I noticed that the ESP8266 might not be supported by Temboo and I was wondering if there is a workaround.

Thanks.

body:
Yes, apparently you can.

I did a quick search on Google and found a GitHub library for the ESP8266 https://github.com/sabas1080/TembooForESP8266 and a post on the Arduino Forum https://forum.arduino.cc/index.php?topic=337186.0 that says you can download a skeleton program and hack that.


body:
I work at Temboo.

While we don't officially support the ESP8266, we've found a couple of forum posts in which people have been able to get Temboo to work with the ESP8266. Here you go:

http://www.esp8266.com/viewtopic.php?p=24019

https://forum.arduino.cc/index.php?topic=337186.0

If that doesn't help, feel free to contact Temboo Support and we'll do our best to help figure out what's going wrong for you.

The key piece of info you need to be aware of is that you need to modify following Temboo library files:

    \Arduino\libraries\Temboo\src\Temboo.cpp

    \Arduino\libraries\Temboo\src\utility\
    --ChoreoInputFormatter
    --ChoreoOutputFormatter
    --ChoreoPresetFormatter
    --TembooSession
    --tmbhmac
    --tmbmd5

You need to modify all occurrences of `"avr/pgmspace.h"` in these files, changing it to `"pgmspace.h"`.


message:
Is it possible for ThingSpeak to show a simple table of all data collected?

I just recently found the ThingSpeak platform for the IoT. I have been playing around with its features a bit, but I have not found a way for it to show a simple table of all the data collected. For example, the table might have humidity, temperature, and timestamp columns, and then every time data is written to ThingSpeak, a new row would be added with the latest readings. I would be surprised if this is not possible with all of its complex graphing tools. Has anybody found a feature like this?

body:
Since ThingSpeak has an extensive API, you can build a tool to read in data and display it as a table. I have created a GitHub repo called, "[IoT Debugger][1]" that allows you to see data as a table as the it comes into a ThingSpeak Channel.

To use the demo, enter your channel number and the read API key.

If you want to modify the project, fork the project on [GitHub][1].

  [1]: https://github.com/nothans/iot-debugger


message:
Interfacing to scale over RS-232

**Objective:** interface and Arduino MEGA to a Mettler Toledo SB32001 using the RS-232 communication protocol described in [the manual][1].

**Equipment Used:**

* SB32001 Mettler Toledo 32 kg scale
* Arduino MEGA
* [Sparkfun RS232 Shifter - SMD][2]

**Background:**

I am using the `SoftwareSerial` library to try to communicate with the scale through MEGA pins 52 and 53. I have the level shifter connected to the scale using a through cable.

So far, I have tried to send the most basic command to the scale, and the command is both not executing, and not causing a status code to be send back (i.e. failure OR success). My Tx light on the level shifter flashes, but the Rx light never does.

Write string to screen:

`D "String"`

Because I have a through cable, I have tried switching the Tx and Rx pins in code. Neither has worked.

The from the scale has the following options I can set:

* **Baud Rate:** 150, 300, 600, 1200, 2400, 4800, **9600**
* **Parity:** 7b-E, 7b-no, **8b-no**, 7b-odd

Here is a minimal (non)working example of my code:

    #include <SoftwareSerial.h>

    const int pinTX = 53;
    const int pinRX = 52;

    scale = SoftwareSerial(53, 52);

    void setup(){
        Serial.begin(9600);
        scale.begin(9600);
        delay(100);
    }

    void loop(){
        scale.println("D \"Hello!?\"");
        delay(100);

        while (scale.available()){
            Serial.print(scale.read());
        }
        Serial.println()
        delay(100);
    }

**What I need:**

I need help figuring out where I should look next to solve this issue. I have tried switching the transmit and receive pins in software. I have tried using jumpers to switch the Tx and Rx pins in hardware. I have tried 7 and 8-bit settings with no parity. Nothing give me a signal back. Totally perplexed?

Is it my converter chip? Does anyone know of problems with this shifter? I know that it does not contain the industry standard MAX232

  [1]: https://us.mt.com/mt_ext_files/Editorial/Generic/7/MT-SICS_for_Excellence_Balances_BA_Editorial-Generic_1116311007471_files/Excellence-SICS-BA-e-11780711B.pdf"the manual"

  [2]: https://www.sparkfun.com/products/449

body:
The solution turned out to be a couple of things, some of which mentioned by others in the comments.

Problems that needed to be fixed:

 1. My level-shifter was a huge part of the problem. I switched to a MAX232-based chip and then I was a least able to get responses shorted lines 2 and 3 (Tx and Rx).

 2. I needed a cross-over cable. I had tried this while troubleshooting, but because that alone didn't fix the problem, I had not idea whether or not that was the problem, or just one of the problems.

 3. I needed to use the onboard UART (Serial1) rather than SoftwareSerial. The problem was that I needed to be able to set the protocol to 8 bits with no parity. This configuration parameter cannot be changed on SoftwareSerial, but is as simple as `Serial1.begin(9600, SERIAL_8N2)`.

Thank you for the help, and hopefully my mistakes make the process easier for others.


message:
Can multiple xbees send data to one xbee

I am new to xbees. I want to have multiple xbees (up to 400 xbees) send data constantly to one xbee (receiver).This is just simple data like lets say 0 or 1 . Is this possible? Are there any limitations?

body: Yes, you can send data from 400 XBees to a single xbee. I would like to clarify one thing. XBees are connecting to a network, not to a particular xbee. And the devices connected in a network can communicate each other.


message:
Connecting multiple TFT panels to Arduino Uno via SPI?

Is it possible to connect more than one TFT screen (like this one or similar: <https://www.adafruit.com/products/1651>) to an Arduino Uno?

I'm wanting to connect and control two color screens at once; note the touch functionality of the one linked above isn't really necessary, I just like the size and overall build. They have a version that works like a shield and sits on top of the Arduino, which would work I suppose if I bought another unit for the other screen. The breakout board version is more flexible but I don't know of a way to control two screens that require that many pins.

Any suggestions?
Thanks

body:
Yes, you can. All the SPI pins (MISO, MOSI and SCK) are all shared between the panels. You can even share the D/C and RST signals. The only signal that *needs* to be separate is the CS pin since this is the pin that identifies which panel is actively receiving commands and data at any one time. Also you don't need to connect up the MISO pin at all, since that is only connected to the SD card slot, not the TFT screen.

So each screen that you add just requires one more pin to be used. One screen uses 5 pins. Two screens use 6 pins. Three screens use 7 pins, etc.

And yes, for this the breakout version would be easier to work with than the shield version.


message:
Generating an 8V PWM signal

I have a control module that accepts 8V PWM signals.  My goal is to send a 500Hz PWM signal from an Arduino to an 8V PWM input on the control module.  Looks like everything generated from the Arduino is 5V.  Is there a way to generate an 8V PWM output or method of manipulating that signal to reach 8V?

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

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

body:
I'd suggest you use a power-source that delivers you 8V. Your Arduino takes anything from 7-12V to power it and it regulates it down to 5V. But you still can access the 8V from the RAW pins. Use a MOSFET like [D1703L][1] to control the 8V with an 5V Arduino digital pin.

You just connect Drain (D) to GND and Source (S) to your RAW 8V (don't forget to put your device between the Source and RAW 8V). Your Arduino digital pin goes to Gate (G), but to not draw to much current from the pin you might want to use a resistor of roughly 1kΩ.

This is the safest way that also allows for much higher voltage and also current for up to a few amps.

EDIT
----
You should not connect the PWM pin to Ground on your Arduino. But you have to connect both grounds together. I'm not sure where your 8V comes from so I made a sketch where the 8V is an external source and powers your device along with the MOSFET.

[![enter image description here][2]][2]

  [1]: http://www.datasheetlib.com/datasheet/835216/d1703l_stmicroelectronics.html
  [2]: https://i.stack.imgur.com/OJsQo.png


message:
Can anyone help me figure out why this buffer is overflowing? (Updated)

This should be fairly straightforward, but there must be something I'm not understanding about buffers.

I have serial data coming in to my Mega via Zigbee. I'm sending a string just like this: `~-0.6016800`, where `~` is my unique starting delimiter and my end delimiter is a carriage return `\n`. I'm sure it's coming through the zigbee correctly, because I can see my string show up looking good in XCTU when I plug the zigbee into the PC. Here is my code:

<!-- language: lang-cpp -->

    const int numChars = 15;
    char incoming[numChars];

    static boolean Receiving = false;
    static byte ndx = 0;
    char startMarker = '~';
    char endMarker = '\n';
    byte K;
    bool allreceived = false;

    void Get() {
     memset(incoming, NULL, strlen(incoming));
        while (allreceived == false) {
   if (Serial.available() > 0) {
    K = Serial.read();
    if (Receiving == true) {
     if (K != endMarker) {
      incoming[ndx] = K;
      ndx++;
      if (ndx >= numChars) {
       ndx = numChars-1;
      }
     }
     else {
      incoming[ndx] = '\0'; // terminate the string
      Receiving = false;
      ndx = 0;
      allreceived = true;
     }
    }
    else if (K == startMarker) {
     Receiving = true;
     ndx = 0;
    }
   }
  }
    }

So somehow my buffer is overflowing or something, no matter how big I make it. I see the array start off as I expect it for the first few characters, then it turns into unintelligible characters. I think part of the problem might be that the serial data is coming through at a different rate or something, because I can see my starting delimiter `~` on my LCD screen in the middle of my array. The way it's set up, I should never be able to see my start delimiter unless I miss my end delimiter without ending the array. (Note- I've tried different unique end delimiters too, but this seems to work just the same)

Any ideas on what might be causing this??

EDIT: NOW TRYING THIS CODE- I'm still having the buffer overflow, and I'd be really grateful if someone could take a look.

**Sending code:**

    void PayloadSendit(void) {

 Payload[0] = '~';  //1 char unique start

 if (outFormat == 0) {
  Payload[1] = '0';
  Payload[2] = '$';  //spacer
  strcat(Payload, stringval); //5 char for hashmarks
 }
 else {
  Payload[1] = '1';
  strcat(Payload, stringvalin);  //6 char for inch
 }
 if (dotpos <= 99) {
  Payload[8] = '@';  //spacer
  char dotpos2[2];
  sprintf(dotpos2, "%i", dotpos);
  strcat(Payload, dotpos2);    //2 char
 }
 else {
  char dotpos3[3];
  sprintf(dotpos3, "%i", dotpos);
  strcat(Payload, dotpos3);   //3 char ///////////////////////////
 }

 Payload[11] = '0';  //1 char for "no errors" code
 Payload[12] = '*';  //1 char end delimiter
 Serial.println(Payload);
 Serial.flush();
 memset(Payload, '\0', 13);

}

**Receiving code:**

      void Get2() {
     memset(Payload, '\0', bufsize);
     while (allreceived == false) {
      int K = Serial.read();
      switch (K) {
      case -1: // Nothing to read
       break;

      case '~': // Starting a new string
       Receiving = true;
       break;

      default: // Any other characters.
       break;

      }
      if (Receiving) {
       for (int i = 0; i <= 10; i++) {
        Payload[i] = Serial.read();
       }
       if (Serial.read() == '*') {
        Receiving = false;
        allreceived = true;
       }
       else { memset(Payload, '\0', bufsize); }  //destroy array if end delimiter not where it should be
      }

     }
    }

body:
My guess is this line:

    memset(incoming, NULL, strlen(incoming));

When "incoming" hasn't yet been cleared, what is the length of it? It's whatever it counts up until the first '\0' character - and where is that character on the first run through? Who knows.

Instead you should memset the size of the buffer, not the number of non-NULL characters in the buffer:

    memset(incoming, NULL, numChars);

**However**, that is a pointless operation, since you are storing a C string and (should be) properly terminating it, so it really doesn't matter what is in the array to begin with since you are just overwriting it anyway. So you can completely lose that whole function call.

You might like to re-write your receiving routine to use a `switch/case` construct instead of ifs and elses - it'll be much easier to follow:

    #define EVER ;;

    const int numChars = 15;
    char buffer[numChars];

    void Get() {
        int pos = 0;
        bool receiving = false;

        for (EVER) {
            int K = Serial.read();
            switch(K) {
                case -1: // Nothing to read
                    break;

                case '\n': // Got the end of the string.
                    if (receiving) return; // We have a valid string.
                    pos = 0; // Reset pointer to start of buffer
                    break;

                case '~': // Starting a new string
                    pos = 0;
                    receiving = true;
                    break;

                default: // Any other characters.
                    if (receiving) {
                        if (pos < numChars-2) {
                            buffer[pos++] = K;
                            buffer[pos] = 0;
                        }
                    }
                    break;
            }
        }
    }


message:
I want to log GPS coordinates using my Arduino and other sensors

.  The difficulty is that I will be in forested conditions.  Would it be better to hardwire a gps device to the Arduino or to bluetooth an external device (a much more accurate, Trimble device that I know will give me the accuracy I need)?  Can such devices pair to a bluetooth receiver that would hardwire to my Arduino, or do I need an intermediate device like my iPhone?

body:
If the Trimble has a serial output then you could connect via that.

If the Trimble supports the same Bluetooth spec as your receiver, then there is no reason why you shouldn't be able to connect them directly. You will need to find out if the Trimble is a Master, Slave or both and buy the appropriate receiver for you Arduino.


body:
The GPS receiver I've always used is the Adafruit Ultimate GPS:

https://www.adafruit.com/products/746?gclid=CjwKEAjwoPG8BRCSi5uu6d6N5WcSJABHzD8FmldH1vIvTt8h-S-948CJmDR6fR_BcF20UZMS4I-AEBoCt9Tw_wcB

It comes with a spot for you to plug in an external antenna (with an adapter), so you can get more precision and presumably be able to receive data much more accurately in places like forests. However, I'm not sure of this, so an external device may be the way to go. Bluetooth would be possible, but it can be a little difficult to set up with Arduino if you lack the experience, so if you can I'd go with a wired connection (with an RS232 or other).


body:
What's more important, GPS accuracy or GPS yield?

Normally it's a trade off between the two. Under difficult conditions such as lots of trees a high accuracy GPS may simply stop outputting locations because it can't guarantee the accuracy, it depends upon the target market for the GPS.e.g. a survey system will be very conservative, survey people don't like getting bad data. A cheaper lower accuracy GPS won't care and will still output a position no matter how dubious the signals are.
I've seen $100 GPS units output a position when a $20,000 Trimble system refuses to.

The GPS should support NMEA output over bluetooth serial port protocol which would then work fine for a direct connection to your device however you may need to change the receiver settings to enable it, the default is likely to be outputting Trimbles binary TSIP format over the bluetooth.


message:
Problem Atmel Studio 7 with uploading

I have a problem with the interworking between Atmel Studio 7 and Arduino IDE 1.6.10.

I recently upgraded from IDE 1.0 to 1.6.10 and I can no longer upload my code to the Arduino. Everything works including compiling and it does recognise my COM3 port. Atmel Studio is configured for no external programmer.

When I compile with the Arduino IDE it *does* upload the code. My question is what goes wrong here, what do I need to do solve it. Thanks for your help

This the message I have in the end:

    Compiling 'GridMonintor_V1R1' for 'Arduino Nano w/ ATmega328' Binary sketch size: 12,268 bytes (used 40% of a 30,720 byte maximum) (22.20 secs)

    Minimum Memory Usage: 774 bytes (38% of a 2048 byte maximum) Uploading to I/O board using 'COM3'

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

body:
> ...Specify a programmer using the -c option and try again

For Arduino, the programmer switch must be `-c arduino`. The full arguments for `avrdude`, in the Atmel Studio 7 External Tools window, are:

    -c arduino -p m328p -P COM3 -b 57600 -D -V -U flash:w:"$(TargetDir)$(TargetName).hex":a

See [avrdude options][1].

  [1]: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions


body:
you might want to try the following command:
-C “C:\Program Files\Arduino\hardware\tools\avr\etc\avrdude.conf” -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:$(TargetDir)$(TargetName).hex:i

where i is used at the end for intel. the one provided above by @flanker uses a

see this detailed tutorial [How to program Arduino using ATMEL Studio 7][1]

  [1]: http://eestuffs.com/2017/02/13/how-to-program-arduino-using-atmel-studio-7/


body:
Switch on vMicro>Uploader>verbose then try the upload and post the output as a .txt file in a new thread in the visualmicro.com forum.

http://www.visualmicro.com/forums

Because you are using the Visual Micro plugin the forum is the best place to see help.

We will also check that you have configured the new arduino location against the arduino 1.6.x option in Visual Micro and not the Arduino 1.0. option as you had it originally. In fact you can have both IDE versions configured in Visual Micro at the same time and switch between them using the tool bar.

Thanks


message:
Is possible to process analogue inputs with variation frequencies in MHz?

Is it possible for Arduino boards to accurately process analog inputs that vary at MHz frequencies?

If possible, which Arduino board would be most appropriate for such application?

What adjustments would be required for it to handle such rapid analog input variations?

body:
Your typical ATMega-base Arduino cannot sample anywhere near that kind of speed.

It takes 13 clock cycles to sample an analog value on an ATMega chip, and the maximum clock frequency for the ADC is 1MHz. That gives you an absolute maximum sampling speed of 76923 samples per second. That means the highest frequency you can sample is 38461Hz.

There are better chips on the market with higher sampling speeds, but they aren't Arduino. Some can sample at the tens of millions of samples per second allowing you to sample frequencies in the low MHz. Other specialised ADC chips are available that can sample in the Gsps range which are what are used in oscilloscopes and high speed communication (fibre optic) systems etc. Working with these kind of chips needs quite a lot of skill though as the analog signal paths requires special design and consideration.

Also when sampling at those kind of frequencies you need a *lot* of high-speed memory, which no Arduino can ever even consider the possibility of having.


message:
How do I convert a float into char*?

Asked this question on Electrical Engineering Stack Exchange and was directed here:

Pretty self explanatory; how would I go about converting a float into a char*? I have code in which the float 'resistance' is constantly being updated. I would like to be able to update the variable 'result' to take the value of 'resistance'. Here is some of the code, in case it helps:

    const char * result = "";
    float resistance = 2.5;

    result = resistance; //This bit (obviously) doesn't work

Thanks for your help!

body:
There is a function in the standard Arduino library called `dtostrf()`. I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

    char result[8]; // Buffer big enough for 7-character float
    dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!

This will give `result` values like `"  1.23"` and `" -1.23"` and `"123456789"` (without the quotes). Note the last example - it won't truncate the number if it's too large, and that ***10-*** character `result` (don't forget the final `NUL`) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).


message:
Answer power IN from two sources

**Items:**

- Arduino Uno
- Laptop
- 7.4V 2s LiPo Battery
- Neewer 30A ESC

**Scenario:**

The LiPo powers the ESC while the Laptop USB powers the Arduino. If I unplug the USB from Arduino is loses power (obviously) and when I plug in the ESC to the arduino I get power again to the Arduino. I need the USB plugged in to receive `Serial` information from the laptop and I need pow+gnd plugged into the Arduino or else I get a lot of PWM noise rendering my ESC useless.

- ESC is 5V
- USB is 5V

**Question:**

This is my due diligence to not blowing anything up. What is the safest way to plug in power from both USB and the ESC? Same voltage, difference sources. Or can I just connect the grounds and call it good?

body:
Connecting the grounds would work.

You could also connect the 7.2V lipo to the Vin pin on the UNO. The UNO will automatically switch from USB to Vin, if it's present.


message:
Control/switching of headphone audio

I need to do some simple line control of audio out from a phone, 3.5mm TRS. I would have preferred to use transistors, but the voltage drop on an already fairly weak signal makes it unusable. Also not sure about negative voltage from collector to emitter. Essentially I need to switch the line on/off. How can I do this while not introducing noise or signal loss (K.I.S.S.) - I haven't checked if optocouplers are without voltage drop, but in any case they're probably overkill.
Ask for clarification if needed.

body: My first thought was what about relays.  I've done a quick search and found this http://www.geofex.com/article_folders/relays/relays_for_switching_audio_signa.htm and this https://electronics.stackexchange.com/questions/110750/is-it-possible-to-turn-an-audio-signal-on-off-using-a-solid-state-relay so maybe it's not such a stupid idea, but like optocouplers it probably is a bit OTT.


body: Settled on a CMOS bilateral switch (4002). Thanks for the input.


message:
Basic WiFly server returning unexpected output within web client

Currently trying to implement a lightweight webserver using the WiFly shield and an Arduino UNO, this is the code I have so far:

    #include <SPI.h>
    #include <WiFly.h>
    WiFlyServer server(80);

    /* Function defs */
    void cmd(void)  { SpiSerial.print("$$$"); }
    void dhcp(void) { SpiSerial.println("SET IP DHCP 0"); }
    void pass(void) { SpiSerial.println("SET WLAN PHRASE 22222222"); }
    void ssid(void) { SpiSerial.println("JOIN BTHOMEHUB"); }
    void port(void) { SpiSerial.println("SET IP LOCAL 80"); }
    void ip(void)   { SpiSerial.println("SET IP ADDRESS 192.168.1.123"); }
    void tcp(void)  { SpiSerial.println("SET IP PROTOCOL 2"); }
    void boot(void) { SpiSerial.println("REBOOT"); }

    /* Pointer to a handler function */
    typedef void (*Handler)(void);
    Handler table[8] = { cmd, dhcp, pass, ssid, port, ip, tcp, boot };

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

      for(short x = 0; x < 7; x++) {
        table[x]();
        delay(100);
      }
    }

    void loop() {
      WiFlyClient client = server.available();

      if(client){
        while(client.connected()) {
          if(client.available()) {
            client.println("
Hi

This is text.
");
          }
        }
        delay(100);
        client.flush();
        client.stop();
      }
    }

This compiles well, but when hitting `192.168.1.123` in my web browser I get an ever-increasing output like:

    *HELLO*<
    <
    <
    <
    <
    <
    <
    <
    <
    <
    <
    < (cont.)

Definitely not the expected html. I have been playing with this code for hours now and this is the most positive output I can get. If I do a `Serial.write(client.read())` within `if(client.available()) {` I am able to print all the request information to the serial monitor, it just seems I am perhaps sending the data in an incorrect format? Any suggestions? Cheers

**Edit**

I have updated the codebase to include the http headers,

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connnection: close");
    client.println("");
    client.println("<!DOCTYPE html>");
    client.println("
Hi.....

 now I get I different (similar) output, seems like it is printing the first character of each new line

    *HELLO*H
    C
    C

    <
    <
    H
    C
    C

body:
Your browser sent a HTTP GET request. You need to send a HTTP response in kind, in accordance with the protocol, for your browser to correctly interpret the data. Something like this should do:

      #define TIMEOUT 100
      char response[] = "
Hi

This is text.
";
      unsigned long lastRead;
      ...

      while (client.connected()){
        if (client.available()){
          lastRead = millis();
          while (millis() - lastRead < TIMEOUT){
            while (client.available()){
              Serial.write(client.read());
              lastRead = millis();
            }
          }
          client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: closed\r\n\r\n");
          client.print(response);
          break;
        }
      }
      delay(1000);
      client.stop();

EDIT:

It turns out that the Wifly shield sends a response status as well as "HELLO" by default. You have to disable that with a few commands:

    set comm remote 0
    set comm open 0
    set comm close 0

This will ensure that "*HELLO*" isnt sent each time a client connection is made, though I'm not sure if this affects the default `HTTP/0.9 200 OK` response status that is always sent. You can try the sketch above with and without the response header to see what you get.


message:
Cannot open file with underscores using the SD library

So I'm trying to create a new file that has underscores in its name. However, when I try this, no file is created.

**This works**

    String fileName = "NMEA.txt";
    mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

**This does not work**

    String fileName = "NMEA__23_33_3__16_7_29.txt";
    mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

Does anyone know why?

body:
> [The SD library] uses short 8.3 names for files.

source


message:
Connect USB cable to GPIO pins on an Arduino Uno

**Electronics Newbie!!**

I want to connect a USB cable to my Uno's GPIO pins (and then connect it to a USB port on my computer). I have chopped off a USB cable from a keyboard, I read [this][1] and I'm hoping that the wires will be in the correct order (the keyboard was made by Dell). I'm a little confused about which wires go where.

  [1]: https://electronics.stackexchange.com/a/37066

body:
The reason you are confused about which wires go where is simply because the Uno has no connection on it for a USB cable's wires.

You cannot directly interface an Uno to a USB port without extra hardware.  What hardware you require depends on exactly what it is you think you are trying to achieve.

(There have been some attempts to create a USB device interface purely in software, but personally I wouldn't touch it with a barge pole - the GPIO of the Arduino is not electrically compatible with USB.)


message:
can teensy 3.0 or above run fingerprint scanner fps gt-511c1r?

I have an fps gt-511c1r fingerprint sensor module. I want to know whether i can run it using teensy 3.0 or above?
I have tried it successfully using arduino uno.

EDIT: I have uploaded the fps blink sketch on the teensy 3.2 successfully, but the fingerprint scanner is not responding. Here is the code:-
         #include "FPS_GT511C3.h"
         #include "SoftwareSerial.h"

         // Hardware setup - FPS connected to:
         //   digital pin 0(arduino rx, fps tx)
         //   digital pin 1(arduino tx, fps rx)

         FPS_GT511C3 fps(0, 1);

         void setup()
         {
          Serial.begin(9600);
          fps.UseSerialDebug = true;
          fps.Open();
         }

         void loop()
         {
            // FPS Blink LED Test
           fps.SetLED(true);
          delay(1000);
          fps.SetLED(false);
          delay(1000);
         }

connected fps tx to teensy rx(pin 0),
          fps rx to teensy tx(pin 1),
          fps vcc to 3.3v teensy,
          fps gnd to teensy gnd.

body:
The GT-511C1R is a 5V device. The Teensy 3.0 is a 3.3V device. You will require some level shifting as you would with any 3.3V Arduino connecting to a 5V device.

Besides that, yes, the Teensy 3.0 is more than capable of working with the fingerprint scanner. Will the software work? Most likely, but only trying it will confirm that.


message:
Sending data using Bluetooth SPP-C Module without a Breakout-Board

tl;dr
-----
I can't send data using the raw [SPP-C][1] Bluetooth module without a breakout board.
The communication via UART works fine as I am able to issue AT commands and get proper responses.
But when connected over Bluetooth the data passed over UART does not show up on my computer while the other direction works fine.
Has anyone tried that module yet without using a breakout board?

The long story:
---------------
I started my project by using a regular [HC-05][2] module on a breakout board. The prototype worked just fine as there are also plenty tutorials available. The drawback using that breakout module is that it works with two voltages, 5V for power and 3V3 for communication. I have also more components in my project that run best at 3V3. That is why it came to my mind to use 3V3 as the only voltage. The raw [HC-05][3] module without breakout board is also powered with 3V3. So everything looked just perfect.

Looking at the specs to the HC-05 I noticed that there is also more on that module like SPI and USB ([page 12 bottom][4]). So I got curious and off track.

Anyway. Instead of ordering raw HC-05 modules without breakout board I ordered cheaper SPP-C modules that don't have all this fancy stuff but just UART communication.

Following the description from [Martyn Currey][5] I was quicky able to issue AT commands and receive data over bluetooth. But I am not able to send data over Bluetooth.

I am using the same setup as it is shown on page 4 in the [Chinese datasheet][6]. (no I can't read that crazy symbols but I can read and understand the images)

  [1]: http://www.aliexpress.com/item/10pcs-SPP-C-Bluetooth-serial-module-wireless-serial-communication-Module-Wireless-SPPC-Bluetooth-Module-free-shiping/32375150414.html
  [2]: http://www.aliexpress.com/item/Free-Shipping-910K-1-0603-100pcs-LOT-SMD-Resistor-sample-in-stock-most-value-don/615810800.html?spm=2114.01010208.3.8.Bz3tbN&ws_ab_test=searchweb201556_0,searchweb201602_5_10057_10056_10055_10037_10049_10033_10059_10058_10032_10017_405_404_10060_10061_10062_412,searchweb201603_1&btsid=8f32b1e9-afa4-451e-87c0-13841a62c223
  [3]: http://www.aliexpress.com/item/Free-Shipping-lot-wholesale-HC-05-HC-05-RF-Wireless-Bluetooth-Transceiver-Module-RS232-TTL-to/32532940254.html?spm=2114.01010208.3.17.az8Edc&ws_ab_test=searchweb201556_0,searchweb201602_5_10057_10056_10055_10037_10049_10033_10059_10058_10032_10017_405_404_10060_10061_10062_412,searchweb201603_1&btsid=5b7f99a0-2a87-42b0-9cf6-30852c96567f
  [4]: http://www.tec.reutlingen-university.de/uploads/media/DatenblattHC-05_BT-Modul.pdf
  [5]: http://www.martyncurrey.com/bluetooth-modules/
  [6]: http://www.elektroda.pl/rtvforum/download.php?id=745759

body:
I found a solution myself.
The modules are working as they are supposed to and are not faulty.
Also I did nothing wrong.

The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using `minicom`. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.

After that I turned over to my Windows and used [Hype! Terminal][1]. Everything worked!

Then I went to my Raspberry Pi and Linux. After pairing using `bluetoothctl ` and issuing a few commands from [Bluetooth as ttyUSB][2]. Everything worked as well.

Then I tried [BlueSPP][3] on an Andriod phone. And again, it worked as it was supposed to.

So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.

  [1]: https://sourceforge.net/projects/hypeterminal/
  [2]: https://raspberrypi.stackexchange.com/questions/9119/bluetooth-as-ttyusb/9127#9127
  [3]: https://play.google.com/store/apps/details?id=com.shenyaocn.android.BlueSPP


message:
WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer

I'm having issues implementing a web socket on the Arduino/Genuino to procress a string received and do something respectively.

I'm using SimpleWebSocket example, edited for my purpose, from the ArduinoHttpClient...

don't seam to get the hangs of it. don't know what i'm doing wrong, cannot store the received string object on a string variable or use the readString() method on and if statement to compare with a string to decide what flow path to get in to

This is the code im trying:

    /*
      Simple WebSocket client for ArduinoHttpClient library
      Connects to the WebSocket server, and sends a hello
      message every 5 seconds

      note: WiFi SSID and password are stored in config.h file.
      If it is not present, add a new tab, call it "config.h"
      and add the following variables:
      char ssid[] = "ssid";     //  your network SSID (name)
      char pass[] = "password"; // your network password

      created 28 Jun 2016
      by Sandeep Mistry

      this example is in the public domain
    */
    #include <ArduinoHttpClient.h>
    #include <WiFi101.h>
    #include "config.h"

    char serverAddress[] = "192.168.1.140";  // server address
    int port = 8000;

    WiFiClient wifi;
    WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
    int status = WL_IDLE_STATUS;
    int count = 0;

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

      Serial.begin(9600);
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to Network named: ");
        Serial.println(ssid);                   // print the network name (SSID);

        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);
      }

      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
    }

    void loop() {
      Serial.println("starting WebSocket client");
      client.begin();

      while (client.connected()) {
        int messageSize = client.parseMessage();

        if (messageSize > 0) {
          String test = client.readString();
          Serial.println(client.readString());
          Serial.println(test);
          if (client.readString() == "off") {
            Serial.println("low");
            digitalWrite(6, LOW);
          }
          else {
            Serial.println("high");
            digitalWrite(6, HIGH);
          }
        }
      }

      Serial.println("disconnected");
    }

On the example above, you can see in the void loop, after I check there's incoming data with messsageSize I store the incoming data using readString on a variable test, which I then println, this shows and empty line, although when I directly via println readString it shows some data, so the data is coming in... subsequently when I try to use the data from the incoming buffer on and if statement to compare with a string is wont work.

I've tried everything I can think off, puting the string to compare in to a variable and compare them, using Compare method from the object and I cannot even remember what else.

does anyone have any advice on how to do this, maybe the library is buggie, maybe I'm doing it wrong, any other libraries that anyone can recommend, I've looked around and this is the only one that looked simple enough to get started with and had the most examples.

body:
this workes:

    if (messageSize > 0) {
          //Serial.println(client.readString());
          String input = client.readString();
          Serial.println(input);

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.

It worked.


message:
do i need an I/O shield for quadcopter motors

I would like to know if I need an I/O shield for the 4 ESC's on a Quadcopter I am building using Arduino Mega2560.  The current to the ESC's should come from the battery itself and the data from the board so my first thought is that it is not needed however I wanted to be sure.

body:
If the ESC accepts a signal that the Arduino can generate (i.e., 5V PWM) then no interfacing is required.

If the ESC is running from 3.7V (or similar) then some level shifting may be required to reduce the 5V signal to 3.7V, depending on the ESC. That may be built on a shield of some form or just with discrete resistors wired in manually to the leads.


message:
Arduino Driver can I use only PNP?

is it possible to use a normal PNP transistor to drive a motor?
I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.

I have made a motor driver? https://circuits.io/circuits/2493784-test-1
But I'm not sure if i have done right and I wont break any components.

So does this work without any problems and have I done it right?

I'm not trying to make a H-bridge because I need both PNP and NPN?

EDIT:Picture
[![enter image description here][1]][1]

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

body:
You need an NPN transistor to run a motor like that off of an arduino. Take a look at this article: https://learn.sparkfun.com/tutorials/transistors

>Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
>
>This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because Vb would always be less than Ve.

Using an NPN transistor is the way to go here. Keep in mind that you can't control the direction of a motor with just one transistor, however.


body:
I don't know what you are trying to do, because the link fails to display in my browser.

In general there is no reason why you can not use a PNP transistor, providing you use appropriate polarities, and assuming common-emitter mode, reference to the +5V rail rather than Gnd.

Having said that, you would need some specific reason. In general NPN devices are cheaper and/or outperform PNP, all other things being equal.


body:
Despite the fact that the circuit you have is completely wrong, there is one fundamental thing that is stopping you using a PNP transistor.

With an NPN transistor you have to raise the voltage on the base *above* the ground voltage (this voltage is called *V_BE*, the *V*oltage between *B*ase and *E*mitter). Typically that voltage is around 0.7V.

With an PNP, because the emitter is wired to your 9V rail, *V_BE* must therefore be relative to 9V, not ground, so the voltage on the base must be less than 0.7V *below* 9V to turn on. Which in itself is fine - a LOW will be around 0V, which is about 9V less than 9V. So it will turn on. The problem comes when you want to turn it off. You need to get the base voltage *above* 8.3V (9V - 0.7V), and that is impossible for an Arduino to do.

So normally a PNP transistor is switched by using an NPN transistor to switch the base of the PNP between 9V (pulled up through a resistor) and 0V (switched through the NPN).

And that then becomes pretty much pointless, since you are then adding a second, NPN, transistor, and you could just as well use the NPN alone to switch the motor, making the PNP completely redundant.


body:
When connecting together several circuits that have different supply
voltages, common practice is to make them all have a common negative
supply rail. This is called “_common ground_”. As explained in Majenko’s
answer, you would need an NPN transistor for that.

If you want to use a PNP instead, then you could forget the common
practice and do everything “backwads”: if you connect together the positive
ends of the power supplies, you will have a “common VCC”
instead of a common ground. Relative to the Arduino ground, your
9 V battery will have one pole at +5 V and the other at
−4 V.

The wiring is the following:

* connect the emitter to +5 V (Arduino +5 and battery +)
* connect the base to an Arduino output through a resistor
* connect the collector to the motor
* connect the other end of the motor to the battery −
* put a free wheeling diode in parallel with the motor.

**Edit**: Below is an ASCII art rendering of the circuit. Beware that
the motor is ON when the Arduino output is LOW.

    +-----------+
    |         5V|-----------------+-------------------+
    |           |                 |                   |
    |  Arduino  |                 |                   |
    |           |    ,-----.  B |< E                 ___ +
    |        D13|----|     |----|    PNP              _
    +-----------+    `-----'    |\                   ___
                                  |C                  _
                                  |                  ___
                                  +---------+         _
                                  |         |        ___ 9 V batt.
                                  |         |         _
                                 ---        |        ___
                                  ^       motor       _
                                 / \        |        ___
                                 ---        |         _  −
                                  |         |         |
                                  |         |         |
                                  +---------+---------+


message:
Why does my servo execute an action in the beginning when the odds are almost 0?

I made a servo motor turn if the result of random(0, 10000) is less than or equal to 1. If that is the case, the motor turns to 130 degrees, to 50 degrees, and then to default position(90 degrees). It works well except whenever I turn on the Arduino, it automatically executes the turning maneuver. It usually takes dozens of seconds for the randomNum to be 1 or 0. However, the servo always turns right away at the beginning. Here is my code. I will make comments to help you understand what I was thinking. I used no delays.

    #include <Servo.h>
    Servo servo;
    unsigned long timer=millis();//counter
    unsigned long servoTimer;
    boolean turned130 = false;
    int randomNum;//will hold value 0-9999
    bool backCheck = false;//variables to keep track which code block to call
    bool checkingAllowed = false;
    bool turned50 = false;
    bool startChecking = false;

    void setup() {
    servo.attach(12);
    servo.write(90);//set default position
    servoTimer=millis();
    }

    void loop() {
    timer=millis();//update counter each time
    if(checkingAllowed==false){
    randomNum = random(0, 10000);//random number generator
    if(randomNum<=1){//small odds
      checkingAllowed = true;//makes this codeblock unable to run
      servoTimer=millis();
      servo.write(130);
      turned130=true;/sets variables to allow other if statements to run
      turned50=false;
    }
    }
    if(timer-servoTimer>=1000 && turned130==true && checkingAllowed==true && turned50==false){//next codeblock that runs if random <= 1 after 1 second
    turn50();
    }
    if(timer-servoTimer>=1000 && turned130==false && checkingAllowed==true && turned50==true){
    turnBack(); one second later this runs
    }
    if(timer-servoTimer>=1000 && checkingAllowed==true && backCheck==true){
      backCheck=false;//servo turns back to 90
      checkingAllowed = false;//allows the main code block to be called
    }

    delay(2);//small delay
    }

    void turnBack(){
    random50 = random(0, 160);
    servoTimer=millis();
    servo.write(90);
    backCheck = true;
    turned50=false;
    }
    void turn50(){
    turned130 = false;
    random130  = random(0, 160);
    servoTimer = millis();
    servo.write(50);
    turned50=true;
    }

It takes a while for the random number to be 1 or 0. I do not understand how 100% of the time, the servo executes the maneuver in the beginning. I will give any more information if you need it to aid me. The random() will soon be replaced by ping() of ultrasonic sensor. Then, the problem will probably disappear. I just want to be clear on what is happening here.

body:
Recognise that, despite the name, `random()` does not produce a _truly_ random number. Because a computer is basically determinate, every time `random()` is called it produces results in a fixed sequence - it is possible that this sequence includes `0` or `1` straight away.

If you want it to start at a different point, you need to "seed" the random number generator by calling `randomSeed()` and passing in an integer. Note that it can't be the _same_ integer every time - that would just move the sequence to the same point every time. The [Arduino reference for `random()`][1] suggests reading an unconnected analog input with `analogRead()` (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.

    randomSeed(analogRead(A0)); // Seed random() with random starting point

  [1]: https://www.arduino.cc/en/Reference/Random


message:
Using interrupts for two MCP23017

I am creating a simple shield with two i2c `MCP23017` chips. Each `MCP23017` has two interrupt pins, but the Arduino Uno only has two interrupt pins (`pin 2` and `pin 3`).

The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the `MCP23017` for the latest pin reads.

How can I connect the 4 interrupt pins to my Arduinos 2 pins?

body:
The MCP23017 (and it's sister the SPI-based MCP23S17) can have their interrupt pins set to "mirror" mode. In this mode both pins are internally joined so when an interrupt occurs on any port both pins activate.  This is done using the `MIRROR` bit of the `IOCON` register.  Using this will turn your 4 interrupt pins into just 2, one for each Arduino INT pin.

Should you want to add more in the future, or if you find you want to use one of the interrupt pins on the Arduino for something else, there is also the `ODR` bit in the `IOCON` register. This sets the interrupt pins to be *open drain*, which means that all of them can be wired together into just one INT pin on the Arduino. Add a pullup (or enable the internal pullup) and you have have many IO expanders on one INT pin. Of course, that then means that you have to poll all the expanders to find which of them triggered the interrupt, so could slow things down somewhat depending on how you are using it.


message:
LED Strobe based on switch press through Arduino

I have a problem I can't see to solve. I'm trying to program my Arduino, which I just got. I have read a lot of programming scenarios, but can't seem to find one that fits my problem.

I can get the LED to turn off and on like I want.

Assume a switch is pressed or even two wires to the LED are put together. Once the switch is pressed I'd like the LED to flash briefly, even though the LED has power to it. Is there a way to do this with Arduino code?

(1) Press switch
(2) Flash LED briefly
(3) Switch is still being pressed
(4) LED remains off until switch is pressed again
(5) loop through routine again.

body:
This is a modified Example program that i have tested and seems to do what you expect. I have used a 2 position switch instead of a button. using a pointer "ledState" to indicate that the LED has flashed and have then combined 2 conditions with the "&&" in the IF statement.

    /*
      Button

     Turns on and off a light emitting diode(LED) connected to digital
     pin 13, when pressing a pushbutton attached to pin 2.

     The circuit:
     * LED attached from pin 13 to ground
     * pushbutton attached to pin 2 from +5V
     * 10K resistor attached to pin 2 from ground

     * Note: on most Arduinos there is already an LED on the board
     attached to pin 13.

     created 2005
     by DojoDave <http://www.0j0.org>
     modified 30 Aug 2011
     by Tom Igoe

     This example code is in the public domain.

     http://www.arduino.cc/en/Tutorial/Button
     */

    // constants won't change. They're used here to
    // set pin numbers:
    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status
    int ledState = 0;
    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if ((buttonState == HIGH)&&(ledState == 0)) {
        // Flash LED:
        ledState = 1;
        digitalWrite(ledPin, HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        delay(500);
      } else if ((buttonState == LOW) && (ledState == 1)){
        ledState = 0;
        delay(50);
        }
    }


message:
How to handle low temperatures using Arduino Uno?

I want to create a simple electronic temperature sensor using the Arduino Uno.

The environments I want it to handle is inside a fridge and near a heater.

Although I am sure the Arduino can easily handle a heater; my issue is that the Arduino may not be able to handle a fridge.

A fridge also has the added problem of causing water vapor (and we all know water + electronics is never a good idea).

So my question is:

 - How would I create a temperature sensor using my Arduino Uno, that I can put in my fridge?
 - Are there any other problems I have not considered and how do I solve them?
 - Will I need a special type of casing? If so, which type?
 - Is an Arduino Uno even the best tool for this task?

body:
Your Arduino does not have to be in the fridge, just the sensor. You can always choose waterproof sensor [like this one][1] to use with the arduino. Then you can always store your arduino outside the fridge. Same goes for the heater. Try to keep the arduino at room temperatures to avoid decreasing its life unnecessarily.

As for an actual answer to the temperature ranges, [here is a good answer][2]

  [1]: https://www.sparkfun.com/products/11050
  [2]: https://arduino.stackexchange.com/questions/633/how-cold-or-hot-can-my-arduino-uno-get


body:
Humidity would be your biggest enemy. The fridge is a very moist environment for two reasons:

 - The colder the air temperature, the less moisture it can hold overall, thus saturating more quickly and reaching a higher relative humidity.
 - Lots of moist foodstuffs in an enclosed space.

You should be OK as long as the enclosure you choose has plenty of ventilation to avoid a temperature differential or trapping moisture.  Either of those two conditions could cause and even larger increase in humidity or, worse, condensate to form.


message:
Using Arduino Yún to send data through Ethernet

I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.

I've seen other tutorials but they use Uno with an Ethernet shield.  Is it the same with the Yún too?

How can I send data through Ethernet using Yún?

body:
There are three bits of information you need to know:

1. The Ethernet port is connected to a tiny Linux computer
2. On Linux you can do HTTP POST and HTTP GET using a program called cURL
3. The AVR chip can tell the Linux computer what to do using the `Process` library.

Putting all those together: You need to use the `Process` library to tell Linux to run `curl` with the right parameters.

Just like the tutorials show you:

* https://www.arduino.cc/en/Tutorial/Process


message:
How can I convert PID correction values to an PWM brushless command?

Please I'm working on a quadcopter, and I have to made my own flight controller based on arduino uno.
First of all please how can I get a filtred angular velocity and linear acceleration from the MPU6050, is the following code give us the angular velocity in deg/sec and the linear velocity in m/s² ?

`accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);`

and is this pid value in this following code is right ?

      accel_reading = ax;
      accel_corrected = accel_reading - accel_offset;
      accel_corrected = map(accel_corrected, -16800, 16800, -90, 90);
      accel_corrected = constrain(accel_corrected, -90, 90);
      accel_angle = (float)(accel_corrected * accel_scale);

      err = angle_setpoint - accel_angle  ;

      P = Kp * err ;
      I += (Ki * err) ;
      D = Kd * (err - errp);

      pid = P + I + D;

Thank you.

body:
You convert PID outputs to process outputs by selecting appropriate Kp, Ki, and Kd constants -- they translate the error components into a process output.   For example, if you want 10 degrees of error to give you a full-scale analogWrite() adjustment, set Kp=255.0/10.   Ki and Kd will depend on the (unspecified) sampling interval.  If the measurements are noisy, you can use the Ki term to do some filtering work, but if you filter it prior to the PID, it will reduce the performance of the PID.

Code-wise, you are missing some sort of`errp=err;` code, you need more than acceleration in the x direction to calculate an angle, (atan2(az,ax) or some such, depending on orientation), and your PID scheme doesn't protect against common problems like out-of-range, integral windup, or inconsistent sampling interval.   You should investigate the http://playground.arduino.cc/Code/PIDLibrary for a more robust implementation than you've half-coded above.


body:
> How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?

after that, you will need to map the pid value to a range for your pwm dc.

basically, it is application / task specific, and you are in complete charge.


message:
do i need to also connect GND and 3.3v

I am trying to run this code:
https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino

Using an ESP8266 based D1 board and an RFID-RC522.

I am not able to get it to detect the rfid tags ...
the serial monitor just shows:

     ets Jan  8 2013,rst cause:4, boot mode:(3,4)

    wdt reset
    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v00000000
    ~ld

The "Typical pin layout used" section of the above document does not mention any connections on the 3.3V & GND pins of the RFID-RC522 card.

Does this mean that I do not need to connect them?
Or is is just so obvious that I should connect them that they did not bother to write it in that section?

body:
It is just so obvious that you should connect them that they did not bother to write it down.

The reader needs power. That is taken as read. Without power it can do nothing. Why would they bother to waste time telling you to connect the things that you have to connect regardless? The only things that they tell you to connect are things that are specific to the sketch - i.e., which IO pins to connect to which function on the reader. Power doesn't change - it's the same from sketch to sketch and from person to person. The IO pins do, though, and need to be detailed. Power and ground don't.


message:
Confusion about PNP transistors

I was reading through SparkFun's article on transistors when I came across something that confused me. The article showed this circuit:[![enter image description here][1]][1]

With this description:
>Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
>
>This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. **For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor.** In that case it’d be impossible to turn the switch off because VB would always be less than VE.

I am confused because the part about the Arduino not being able to turn off a PNP transistor makes sense, but doesn't the circuit shown feature exactly the situation described that the transistor wouldn't work in? Is this an oversight by me and is there something else going on here that I don't understand, or is this a mistake in the article?

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

body:
The article is saying that the **circuit wouldn't work**, thus it illustrates (correctly) something that won't work. What is the confusion?

To turn the PNP transistor off, the base voltage needs to be low *with reference to the emitter voltage*. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.


message:
Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters

When I am using RF 433 MHz module with ARDUINO MEGA then it is transmitting any text or anything in ASCII values. Now how to decode those ASCII values to alphabets? If I use ASCII conversion programme then what if I send a number and that conversion program converts that number also to text or related ASCII character? please suggest any way.

body:
Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0.  When 8 ones or zeros arrive you have a byte.  A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.

In your case your sending program is sending a letter, lets say A.  Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII [code] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65.  Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.

To show that A you might need to cast the data you receive to a character i.e.

    unsigned char rxData = 0;
    Radio.ReceiveData (&rxData, 1);
    Serial.println((char)rxData);


message:
Steppermotor+Arduino Mega+ Adafruit

I have 2 Stepper Motors (QMot stepper motor1 Amp, 5.3Ohms, 5.3 volts and 200 steps/rev.)
, which are connected to the Adafruit shield2.4, they are mounted to Arduino Mega, the motors pull generally 2 A from external current from Adafruit. My problem is, they don´t rotate smoothly, clearly and fast at the same time.
When I use DOUBLE to define my Stepps, speed is ok but rotation is lout and shaking. When I use MICROSTEP is more smoothly but too much slow. The program is running two stepper motors to roll up optical cables. The cables have to be really precisely come together and accurately be installed on pulley.
Also I need a solution to run my Steppers Motors smoothly, clearly and fast.
Incidentally, I want to know, do I need BigEasyDriver for that?
 If you need more info oder fotos feel free to ask

Regards,

Paria

body: I'd look for a proper stepper driver, e.g. something based on A4988 or similar. I wasted a fair amount of time on the Adafruit motor-shield 2.3 until I finally abandoned it after failing to achieve higher speeds (I also had lots of issues with the motor getting hot). The A4988 takes care of step sequencing including micro-stepping and interfacing and programming is very simple. It only comes in surface-mount packaging but there are bread-board friendly carriers costing a few dollars available from multiple manufacturers.


message:
Declaring literal strings

When I want to write a literal string in Python, I use `r` before the string (or `@` in C#):

    in [1]: print r'\no esca\pe ch\ara\cters'
    out [1]: \no esca\pe ch\ara\cters

In straight c++ I can use `R`, but in the Arduino IDE, this throws the following error:

    Serial.begin(9600);
    Serial.println(R"\no esca\pe ch\ara\cters");

    <output> invalid character '\'in raw string delimiter

So how do I do the same in Arduino c++?

body:
Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.

    Serial.println(R"(\no esca\pe ch\ara\cters)");


message:
Arduino Due - using built in ADC as a DSO causes issues at high frequencies (kHz)

I am trying to use the inbuilt ADC of the Arduino Due to measure voltage signals. The frequency range I'm interested in measuring is  up to about 30 kHz.But I'm observing a strong capacitor behaviour as I increase the frequency ( from 10kHz onwards this is quite visible).

This is most visible when measuring a square wave. When I get close to 30 kHz the signal looks exactly like the text book capacitor charge/discharge wave and nothing like a square wave. Even at around 15 kHz, the square wave looks more like a sine wave/ ramp signal than a square wave.

Based on the behaviour my guess is that a capacitor in the Arduino Due ADC is causing this (as  the frequency increases, the capacitor cannot charge/discharge fast enough). But I'm not sure whether I'm correct about this.
Even if I'm correct, how can I fix this?

Any help would be much appreciated.

Thanks.

I don't have screenshots for the behaviour for a range of frequencies, but I will attach a hand drawing of what it looks like.
[![enter image description here][1]][1]

Also NOTE that As the frequency increases, the amplitude of the observed wave decreases ( I couldn't show this in my drawing). Think this again links back to the capacitor charge/discharge speed behaviour.

My Vin circuit : I tested by adding a voltage follower at the right most end(not shown on the schematic), but that made no difference.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/kRmY2.jpg
  [2]: https://i.stack.imgur.com/v4474.png

body:
Well, if you have source output impedance about 1k and Sample-And-Hold capacitance is 14pF, then RC time constant is about 14us.

You need something with low output impedance. Non-inverting Voltage Follower would be perfect for this (see [source][1]):<br/>
[![enter image description here][2]][2]

  [1]: http://www.electronics-tutorials.ws/opamp/opamp_3.html
  [2]: https://i.stack.imgur.com/uOr8k.gif


body: Fixed : The issue was with the LM324 op-amp. It has a small slew rate (0.5 v/uS) which was causing the signal to flatten out at high frequencies. So had to change to an op-amp with a better slew rate.


message:
How do I read numbers from a serial sequence

I have read through a number of posts including https://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string/1237 However I cannot work out how to extract numbers from a serial string.

My challenge is this;

I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.

The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.

Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.

If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.

Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.

Thanks

Callum

body:
> I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a
decimal point just after it. You can use `strchr()` to find them. Then,
you will have to prepend a zero if needed, and terminate the string one
character before the decimal point.

The following code does this by overwriting the original string. If you
need to keep that string, you will instead have to copy the relevant
characters to another buffer:

<!-- language: lang-c++ -->

    char * get_freq(char *message)
    {
        char *space = strchr(message, ' ');
        char *dot   = strchr(message, '.');

        if (!space || !dot || dot - space < 5)
            return NULL;    // invalid message

        if (dot - space == 5)
            *space = '0';   // prepend a zero

        *(dot - 1) = '\0';  // terminate the string

        return dot - 5;
    }


message:
Bluetooth radio control of a motor

I need to purchase the correct bluetooth module for interfacing some simple functionality between an arduino and a motor. The tricky bit is getting the bluetooth radio to play nice with android and apple ios. There are things like MIT App Inventor, but I'd love to hear from someone with experience how to reliably control arduino from tablets/phones. Preferrably in a way that lets me define the control on the arduino. I can build android apps (slowly), not ios apps, but I would then have to either ask users to install untrusted apks or get it out through the google app store, which would take too long. Any help on this would be great.

body:
You may want to have a look at the Adafruit BLE modules:
https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/bleuart?view=all

They have provided great examples of how to connect from Android and iOS devices, as well as providing apps or code to integrate into your own apps and you get to implement the motor controller code yourself on the Arduino so should have full control over that side.

They even have an example where they are controlling a motor using an Arduino and Bluetooth, it may not be exactly what you need but hopefully gets you closer to an answer:
https://learn.adafruit.com/bluetooth-motorized-camera-slider/overview?view=all


message:
Arduino Micro: how to switch off its blue power LED?

everybody!

I have a genuine Arduino Micro ("designed with adafruit", made in Italy) which is working perfectly well.

One thing I'd like to do but cannot figure out how (or at all), is to turn off the blue power LED. I hate blue LEDs, they hurt my eyes, and this one is particularly bright too.

I could just paint it over with black paint but maybe there are programmatic ways to switch it off?

Regards

body:
Unfortunately the blue LED is a direct connection between 5V and GND. You can see below in the schematic exactly how it is connected

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

The only way to 'turn off' the LED would be to remove either the 1K resistor or LED with a soldering iron.

Another possibility is to take a sharp knife and make a cut in the track directly before or after the LED. I've marked the locations where to cut on the eagle screenshot.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/wDAiW.png
  [2]: https://i.stack.imgur.com/68fO6.png


body:
There is not way to turn it off in software.

The only thing you can do is desolder the led, or it's resistor. Just add some solder to the joints on both sides. Then angle the iron, so it touches both side. The led/resistor will tend to get loose and stick to the iron. Cleanup the board, by removing the excess solder.

I tend to just destroy the led using a utility knife. Just try to lift the "glass" on top of the led with a bit of force. Scrape over the white remains to make sure there isn't any connection left.


body:
The Blue LED is permanently connected to +5 volts through R5.

You would have to either remove R5 or the LED from the circuit board.

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

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


message:
Arduino as a custom I2C slave device

I'm trying to interface with a master I2C device that doesn't exactly follow the normal I2C protocol.

The only difference really is in the read request. A "normal" I2C read operation looks like this ([M]aster, [S]lave):

    S | SLA+R | ACK | Data | Ack | Data ...some number of bytes... Nack | P
    ^M  ^M      ^S    ^S     ^M    ^S                              ^M     ^M

But this device expects to do a read like this:

    S | SLA+R | ACK | Data | Ack | Data | Ack | Data | Ack | P
    ^M  ^M      ^S    ^M     ^S    ^S     ^M    ^S     ^M    ^M

Essentially a read request goes to the slave device, and then the master sends an 8-bit register address, and then the master expects 2 data bytes back from the slave with the Master responding with an ACK on both.

I've been able to set up a master device to do this style of protocol pretty easily by just manipulating the I2C registers directly. But I can't seem to find a way to get the slave device to accept that it is going to receive a data byte after it has been selected by a SLA+R, which leads to a bus contention problem and the slave not giving the master an ACK.

Is this possible to do with the built in I2C hardware on the Atmel chips? Is there any alternative if it can't (bit-banging)?

body:
I'm missing something on the bus operation. Pretty much whenever I get NAK'd I know I need to redo the operation. On the i2c bus it should be an ACK'd or NAK'd on every byte.

Usually you send the address of the device then the command. So the master initially sends the address, which is ACK'd and then the master sends the command that it wants executed. Your diagram has the slave answering when it's the master that's required to give it an operation?

Here's a good document on it... :)

[Philips I2C Document][1]

  [1]: http://www.nxp.com/documents/user_manual/UM10204.pdf


message:
Nano onboard "test" LED blinks when powered via 5V pin

I have a Nano (clone) that I am powering from a regulated supply via the 5V pin; I have checked this at the board and my multimeter reads 4.92V, which seems close enough (?). The main reason I don't use the microUSB jack is a space constraint. In any case, thus far it does work fine.

*Except* the leftmost (considered with the microUSB jack as "top") of the four onboard LEDs, on the opposite side from the rx/tx lights, blinks at a steady one second interval.  Searching around, the only association I've found for that LED is that it is connected to D13, which I'm not using for anything.

What does this indicate?  I have not tried disabling it (by setting 13 low) but I am hoping to do so if it is a benign issue.

body:
So, as per the comments on the question here's what I think happened:

That "test" LED lights briefly when the board is first powered on, indicating I suppose that it's booted and `setup()` is either complete or about to run.

It also lights briefly when the reset button is released.

In the sketch I'm using one of the digital pins is connected to RST -- the arduino is being controlled via UART.  I have swapped some of the pin numbers and wiring around, so I tried leaving the one driving RST low instead of high and indeed, this seems to be the issue: It's resetting at ~1s intervals.

(I honestly believe I checked this before by removing all connections, but since I did not note that in the question, perhaps I never did...)


message:
ESP8266 stuck in flash mode?

I have the setup described here: https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/wiring

I currently have the reset pin set to float and the GPIO0 pin grounded, which should make it execute the uploaded program, but instead I get the flash mode output:

     writing flash
    ...................................................................................................................................................................................................................................................

How do I put it into execution mode?

body: I was stuck in a similar scenario. I managed to exit programming mode by floating GIPO0, then grounding RST for ~3 seconds, then floating it. If you power off the esp, and now turn it on, it should have exited programming mode. Powering it off is actually optional.


message:
analogRead values all over the place, while measuring light

I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.

Minimal sketch:

    while( true )
    {
        int photoValue = 0;
        analogReference(INTERNAL);
        photoValue = analogRead(A5);

        Serial.println(photoValue);

        delay(300);

    }

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:

    0
    0
    4
    4
    0
    16
    15
    22
    21
    25
    20
    36
    40
    34
    36
    24
    5
    0
    3
    6
    0
    0
    0
    0

That would translate to values between 0 and 43mV.

When I disconnect the multimeter only get `1023` printed.

I don't get how the values from the ADC and the multimeter, totally don't match.

body:
The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.

Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.

The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.

By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.