text:
How to connect two IMU in one arduino board?
The code below works fine when  one IMU (MPU9250). What I want to know is how can I edit this code to work perfectly with two IMU (MPU9250) in one arduino board ?
Hope someone can help me. THANKS :)
////////////////////////////////////////////////////////////////////////////
      //
      //  This file is part of RTIMULib-Arduino
      //
      //  Copyright (c) 2014-2015, richards-tech
     //
     //  Permission is hereby granted, free of charge, to any person           obtaining a copy of
    //  this software and associated documentation files (the "Software"), to deal in
    //  the Software without restriction, including without limitation the rights to use,
   //  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
   //  Software, and to permit persons to whom the Software is furnished to do so,
   //  subject to the following conditions:
   //
   //  The above copyright notice and this permission notice shall be included in all
  //  copies or substantial portions of the Software.
  //
  //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  //  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  //  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  //  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  //  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  //  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  #include <Wire.h>
  #include "I2Cdev.h"
  #include "RTIMUSettings.h"
  #include "RTIMU.h"
  #include "RTFusionRTQF.h"
  #include "RTPressure.h"
  #include "CalLib.h"
  #include <EEPROM.h>

  RTIMU *imu;                                           // the IMU object
  RTPressure *pressure;                                 // the pressure object
  RTFusionRTQF fusion;                                  // the fusion object
  RTIMUSettings settings;                               // the settings object

  //  DISPLAY_INTERVAL sets the rate at which results are displayed

  #define DISPLAY_INTERVAL  300                         // interval between   pose displays

 //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

 #define  SERIAL_PORT_SPEED  115200

  unsigned long lastDisplay;
  unsigned long lastRate;
  int sampleCount;

  void setup()
  {
  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
  imu = RTIMU::createIMU(&settings);                        // create the    imu object
  pressure = RTPressure::createPressure(&settings);         // create the  pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu-   >IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());
   if ((errcode = imu->IMUInit()) < 0) {
   Serial.print("Failed to init IMU: "); Serial.println(errcode);
   }

   if ((errcode = pressure->pressureInit()) < 0) {
   Serial.print("Failed to init pressure sensor: ");
   Serial.println(errcode);
   }

   if (imu->getCalibrationValid())
   Serial.println("Using compass calibration");
   else
   Serial.println("No valid compass calibration data");

    lastDisplay = lastRate = millis();
    sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
   // In-between gives the fusion mix.

   fusion.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

    fusion.setGyroEnable(true);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);
    }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
         continue;

      fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
      sampleCount++;
      if ((delta = now - lastRate) >= 1000) {
      Serial.print("Sample rate: "); Serial.print(sampleCount);
      if (imu->IMUGyroBiasValid())
      Serial.println(", gyro bias valid");
      else
      Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
       }
       if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
       //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());
                  // gyro data
        //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());
                     // accel data
       //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
          // compass data
        RTMath::displayRollPitchYaw("Pose:",   (RTVector3&)fusion.getFusionPose()); // fused output

        if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
        Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }
        }

EDITED CODE:
       #include <Wire.h>
       #include "I2Cdev.h"
       #include "RTIMUSettings.h"
       #include "RTIMU.h"
       #include "RTFusionRTQF.h"
       #include "RTPressure.h"
       #include "CalLib.h"
       #include <EEPROM.h>

       RTIMU *imu;                                           // the IMU object
      RTPressure *pressure;                                 // the pressure object
      RTFusionRTQF fusion;                                  // the fusion object
      RTIMUSettings settings;                               // the settings object

      //  DISPLAY_INTERVAL sets the rate at which results are displayed

      #define DISPLAY_INTERVAL  300                         // interval between   pose displays

     //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

     #define  SERIAL_PORT_SPEED  115200

    unsigned long lastDisplay;
    unsigned long lastRate;
    int sampleCount;

    // ================= MPU: 1 =================

   RTIMU *imu1;                                           // the IMU object
   RTPressure *pressure1;                                 // the pressure object
   RTFusionRTQF fusion1;                                  // the fusion object
   RTIMUSettings settings1;                               // the settings object

   unsigned long lastDisplay1;
   unsigned long lastRate1;
   int sampleCount1;

   const int CS_MAX = 2;
   const int CS[CS_MAX] = { 7, 8 };

   void setup()
   {
  for (int i = 0; i < CS_MAX; i++) {
  pinMode(CS[i], OUTPUT);
  digitalWrite(CS[i], HIGH);
  }

  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
   imu = RTIMU::createIMU(&settings);                        // create the imu object
  pressure = RTPressure::createPressure(&settings);         // create the pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
  while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu->IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());

  for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);
  if ((errcode = imu->IMUInit()) < 0) {
  Serial.print("Failed to init IMU: "); Serial.println(errcode);
  }

  if ((errcode = pressure->pressureInit()) < 0) {
  Serial.print("Failed to init pressure sensor: "); Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  lastDisplay = lastRate = millis();
  sampleCount = 0;

   // Slerp power controls the fusion and can be between 0 and 1
   // 0 means that only gyros are used, 1 means that only accels/compass are   used
  // In-between gives the fusion mix.

  fusion.setSlerpPower(0.02);

  // use of sensors in the fusion algorithm can be controlled here
  // change any of these to false to disable that sensor

   fusion.setGyroEnable(true);
   fusion.setAccelEnable(true);
   fusion.setCompassEnable(true);
   digitalWrite(CS[i], HIGH);
   }

   int errcode1;
   Serial.begin(SERIAL_PORT_SPEED);
   Wire.begin();
   imu1= RTIMU::createIMU(&settings1);                        // create the imu object
   pressure1 = RTPressure::createPressure(&settings1);         // create the pressure sensor

    if (pressure1 == 0) {
    Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
    }

    Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu1->IMUName());
    Serial.print(", pressure sensor "); Serial.println(pressure1->pressureName());

    for (int i = 0; i < CS_MAX; i++) {
    digitalWrite(CS[i], LOW);

    if ((errcode1 = imu1->IMUInit()) < 0) {
    Serial.print("Failed to init IMU1: "); Serial.println(errcode1);
    }

    if ((errcode1 = pressure1->pressureInit()) < 0) {
     Serial.print("Failed to init pressure sensor1: ");
     Serial.println(errcode1);
     }

     if (imu1->getCalibrationValid())
    Serial.println("Using compass calibration");
    else
    Serial.println("No valid compass calibration data1");

    lastDisplay1 = lastRate1 = millis();
    sampleCount1 = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion1.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

     fusion1.setGyroEnable(true);
     fusion1.setAccelEnable(true);
     fusion1.setCompassEnable(true);

     digitalWrite(CS[i], HIGH);
     }
     }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the   latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
        continue;

       fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount);
        if (imu->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
        }
        if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
        //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());

         // gyro data
         //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());

         // accel data
        //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
        // compass data
          RTMath::displayRollPitchYaw("Pose:",
          (RTVector3&)fusion.getFusionPose()); // fused output

         if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
            Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }

       unsigned long now1 = millis();
      unsigned long delta1;
      float latestPressure1;
      float latestTemperature1;
      int loopCount1 = 1;

      while (imu1->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount1 >= 10)
        continue;

      fusion1.newIMUData(imu1->getGyro(), imu1->getAccel(), imu1-  >getCompass(), imu1->getTimestamp());
      sampleCount1++;
      if ((delta1 = now1 - lastRate1) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount1);
        if (imu1->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount1 = 0;
        lastRate1 = now1;
    }
    if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
        lastDisplay1 = now1;
      //          RTMath::display("Gyro1:", (RTVector3&)imu1->getGyro());
      // gyro data
      //          RTMath::display("Accel1:", (RTVector3&)imu1->getAccel());
      // accel data
      //          RTMath::display("Mag1:", (RTVector3&)imu1->getCompass());
        // compass data
        RTMath::displayRollPitchYaw("Pose1:", (RTVector3&)fusion1.getFusionPose()); // fused output

        if (pressure1->pressureRead(latestPressure1, latestTemperature1)) {
            Serial.print(", pressure: "); Serial.print(latestPressure1);
            Serial.print(", temperature: "); Serial.print(latestTemperature1);
        }
        Serial.println();
    }
}

}

Before editing the code to support an additional MPU9X50 you will need to figure out a way to address them on the I2C bus. Hopefully the MPU9X50 module you are using has a pin named AD0.
There are two basic solutions to multiple MPU9X50.
The first solution is to use the two different addresses. AD0 pin LOW on one and AD0 pin HIGH on the other. The sketch above would require two instances (imu), one for each module/address.
The second solution, which works for several modules, is to hold the AD0 pin LOW for the module that is addresses and all other HIGH. The setting must be handled by a digital pin. One for each module. They will be used as chip/module select. Below the example code assumes that the MPU I2C address is with the lowest bit LOW.
In the setup() initiate these pins to output mode and high. The example code uses pin 7 and 8.
const int CS_MAX = 2;
const int CS[CS_MAX] = { 7, 8 };

void setup()
{
   ...
   for (int i = 0; i < CS_MAX; i++) {
     pinMode(CS[i], OUTPUT);
     digitalWrite(CS[i], HIGH);
   }
   ...
}

Set the digital pin LOW for the module you want to address before calling an MPU library function and back to HIGH afterwards.
digitalWrite(CS[0], LOW);
imu->someMemberFunction();
digitalWrite(CS[0], HIGH);

If several functions are called in a block it can be convenient to run all of them per module. An example section from the setup:
for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);

  if ((errcode = imu->IMUInit()) < 0) {
    Serial.print("Failed to init IMU: ");
    Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  digitalWrite(CS[i], HIGH);
}

Cheers!

Thank you so much ! :) I really appreciate you . Yes , my MPU has ADO. Please see the above edited code if that is what you mean . When I upload the code the value of MPU1 n MPU2 are almost same even if I just move one of the MPU . Please guide me . Thanks :)  By the way where should I place this code   "    digitalWrite(CS[0], LOW); imu->someMemberFunction(); digitalWrite(CS[0], HIGH);             "

How can I declare tha address in the exmaple code above? thank you

Check RTIMUSettings. It contains the I2C address.

I already edit that but still no luck . :( i put MPU9250 0x69  but still the same result , is that what you mean ?

It should be 0x68 if you are going to do chip select with a LOW assert. Also the AD0 pin should be tied low. The alternative solution is to tie AD0 low on one and high on the other. They are then addressed 0x68 and 0x69 and will need two instances of the settings (imu).

I know it's too much for you to do this can you please show me how to do it ? If it's okay to you . Because i don't really get your point, THANKS :))

I got what you mean , It's now working ! Thank you so much! :)


text:
How to generate Analog Signal (Voice) to the microphone
I have question about microphone and generating sound signal. I have microphone in my intercom at home. It is simple analog microphone, not digital.
What I want is to connect arduino analog output to the microphone and generate some signal that will be heard like a voice at least few words.
Is it possible to do this ? Or it would be quite hard ?
Please suggest the easiest way to implement this.

This might help https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

It will be impossible to "generate some signal that will be heard like a voice" using an Uno - or perhaps any Arduino. Playing a pre-recorded track is possible, as linked in a previous comment, but you will need a board with a digital to analogue convertor built in, like a Due.

source: Stack Exchange

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

sort: votes


text:
Led issue with arduino controled by raspberry pi/python
I'm having an issue with my project. My project is 8 leds and a potentiometer on an arduino being read and controlled by a raspberry pi running python.
when I'm using a potentiometer the signal is received by my raspberry pi with python which then tells a set of leds to either turn on or off. However my leds flash on my low threshold when they shouldn't, the leds on my higher threshold work as expected and stay on till my pot is out of that range. How can I fix this?
Here is my script!
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
#this is the section that is blinking when it should stay solid
   if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.5)
# end of section
   if pot < 650 > 450:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.1)
    if pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.5)
    print pot

Implement hysteresis.

Your second condition is written wrongly. It should be this way:
elif pot >= 450 and pot <= 650:
    # do stuff

Your code should be such that only an option is chosen at any time. There should be only one 'if' condition at the top and the rest should be 'elif'.

Yes, except it's python, so - if (pot < 650 and port > 450):

@Kingsley Python! Can't believe I totally missed that

The problem is you're using multiple if statements, whereas the if-blocks should be mutually exclusive, so elif would be better.  It's not really clear what you intend in the 2nd clause either, since it's a typo(?) - not valid python syntax anyway.
if (pot <= 450):
    Arduino.digitalWrite(LED1, Arduino.HIGH)
    ...
    time.sleep(0.5)
elif (pot > 450 and pot <= 650):
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.1)
else # pot > 650
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.5)

I think your LEDs were flashing because both the first and second if clauses were evaluating to True, thus both code segments were being executed (were only the first four LEDs flashing?)  Using if/elif/else instead, ensures only ever one clause is run.
If I might make a suggestion, assuming you want an LED bar graph based on the POT reading...
The analogRead() will give you a result 0-1023. Graphed over 8 LEDs, this means one more LED should be illuminated roughly per 128 units.  Since you want a full bar when rounding makes the value near 1023, maybe something like 120 is a better divisor (I just guessed this, it's probably calculable).
A simple loop over your LEDs, summing units over each iteration gives an easy way of turning the LEDs on or off.
Arduino.analogRead(POT)
led_bar_per_units = 120   # needs a better name

### illuminate the LED-bar
bar_length = 0
for led in (LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8):
    bar_length += led_per_bar_units
    if (bar_length <= pot):
        Arduino.digitalWrite(led, Arduino.HIGH)
    else:
        Arduino.digitalWrite(led, Arduino.LOW)
time.sleep(0.5)

EDIT: I know you don't need brackets around python if statements.  I've been doing C/C++ code for so long I find bracketed-clauses easier to read, and thus code my python this way too.

I figured it out.
Here is my new script.
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
    if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    elif pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.01)
    else:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    print pot

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


text:
LCDs measuring volts arduino
How do we measure 100 Volts Arduino LCD Proje
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int analogInput = 0;
float vout = 0.0;
float vin = 0.0;
float R1 = 100000.0; // 100K ohm direnç
float R2 = 10000.0; // 10K ohm direnç
int value = 0;
void setup(){
   pinMode(analogInput, INPUT);
   lcd.begin(16, 2);
   lcd.print("DC VOLTMETRE-PROJEHOCAM");
}
void loop(){
   // read the value at analog input
   value = analogRead(analogInput);
   vout = (value * 5.0) / 1024.0;
   vin = vout / (R2/(R1+R2));
   if (vin<0.09) {
   vin=0.0;
}
lcd.setCursor(0, 1);
lcd.print("VOLTAJ V= ");
lcd.print(vin);
delay(500);
}

Attenuate it...

The project that you show as your reference : link in your question,  shows this picture :

Change R1 to 200 K ohms.   The Arduino will receive 4.76 volts when the input is 100 volts.
You will also need to change your program line for float R1 = 100000.0;
CAUTION :  Beware of high voltage.  Also, the Arduino is not isolated from the 100 volts.

It's probably a good idea not to deal with HV if a voltage divider needs to be asked about.


text:
Sim800 sim card requirements
What kind of a sim card is required for sim800 module? I know it must be activated and must be valid. But about 2g, 3g or LTE...What kind of a sim card in overall should I use with this module?

the question is: whether it will work with 4G or not?

What kind of a sim card is required for sim800 module?

The SIM interface complies with the GSM Phase 1 specification and the new GSM Phase 2+ specification for FAST 64 kbps SIM card. Both 1.8V and 3.0V SIM card
are supported. The SIM interface is powered from an internal regulator in the module.
For more details see here and here. And remember "Google is your friend".
Cheers!

so if I were to go to a store to look for a sim card for a project related to sim800, I would ask for a 1.8V or 3.0V sim that complies with GSM phase 1 or 2+ specification right?

oh only 2g sim...and micro sim won't work

Actually I think it works like this; the SIM card gives a set of numbers to identify the unit when connecting to the network. The SIM800 can only connect with GSM (2G) so the SIM card must be for a vendor (service provider) that supports that.

So what kind of a sim should I ask the seller for?

You are still missing some info to be able to answer that. What size is the SIM card holder? You will have to ask for a 2G (GSM) SIM with the right size. Check other restrictions such as security (PIN) etc in the SIM800 documentation. It is all a question of reading.

a doubt: will 3g sim work?

The SIM800 can only connect to a 2G (GSM) radio network. The SIM card is not specifically GSM, 3G etc. It is the radio network service provider that must support GSM. They may call the SIM card 3G but the radio network may be a combination of technologies for provide coverage. You will have to stress that you need 2G (GSM) coverage.

I wanted to know that a regular sim or a micro/nano sim is required for this module:http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW

The SIM card holder is under the shield; http://i.ebayimg.com/00/s/MTYwMFgxMzQ4/z/4KYAAOSw5VFWMidx/$_58.JPG Looks like a mini? https://en.wikipedia.org/wiki/Subscriber_identity_module


text:
ATtiny85 communication with computer through USB
I am trying to receive and send some data from a computer to an ATtiny through USB. Can an ATtiny85 IC communicate with a computer through USB? If yes, how should it be connected?

The answers don't seem to address the core question. I believe he is asking how to communicate with a computer over the USB port AFTER burning the code. The answers talk about connecting seemingly for the purpose of programming and developing and loading any program. The question is, how do you communicate with a host PC over USB FROM the attiny with your own code? I have the same question. Paul

Digispark made a lot of these as part of a "cheap Arduino USB interface" project a while back.
This is my Digispark, it's pretty cute:

They have a web page here.

I got them for about $2 each. The board has the ATtiny85, a voltage regulator, and a handful of other parts.
Schematic (courtesy of Digistump Wiki):

More information about the Virtual USB idea at USB-Keyboard with Arduino and V-USB library, an example.

If someone is wondering if you can use SPI devices with it due to the low amount of pins, the answer is yes, you can.

Can an ATtiny85 ic communicate with a computer through USB?if yes,how should be the connection?

Have you checked the web? There are many such projects. Here is a link to one:
http://www.instructables.com/id/Digispark-DIY-The-smallest-USB-Arduino/
Please remember "Google is your friend".
Cheers!

Nooo... not Google... Marjory!!!

Whatever make you happy - "Google == Web search tool of your liking" :)

The Digispark (of which I bought a few) works quite well. It is based on the "Virtual USB" (V-USB) concept which you can find with a *ahem* search-engine-of-your-choice search.

@MikaelPatel Could you please highlight the most important parts of the content you linked? It's currently very much link-only answer.

@Avamander Please see the schematics provided below by Nick. That should answer all your questions about how to connect the ATtiny85 to USB.


text:
Arduino signed int can't fire timer > 15 seconds
I have tried to use different libraries like TimeAlarms , SimpleTimer, Timer and others. My goal is to call function periodically every minute or so. Each library works fine when repeat time is less than 15 seconds ( maybe greater) but 30seconds,45seconds, 60seconds doesn't work at all.
It seems something with internal timer.
I also use NRF24l01 Mesh library.
Please help to solve the problem
SOLVED
The issue was that I used int type instead of long. but I don't understand why 60 000 cannot be stored in int type which is 4 bytes (2^32)

Please post code, links to libraries, and any projects that you might have copied code from. Even better is to isolate the issue to a test sketch that others can run and understand the issue. If this is an issue with any of the libraries it will have to be solved there.

Thank you for the help. but the issue was that I used int type instead of long. but I don't understand why 60 000 cannot be stored in int type which is 4 bytes (2^32)

A code snippet had shown that. The take-away is that you should provide more info. BW: int is only 2 bytes on Arduino/AVR. Remember this is an 8-bit MCU.

And here is a link for more info on the AVR ABI https://gcc.gnu.org/wiki/avr-gcc.

An int on Arduino is only 16-bits (2 byte). It's also signed. So the maximum value is 2^15-1.

Please post an answer explaining this, I will accept it

Since you found out the solution yourself, you should add the answer yourself.

You could summarize what people told you, and then post your complete solution. You are allowed to answer your own questions. The maximum in an int on the Arduino is 32767 so I am a bit surprised 30 seconds didn't work.


text:
Can an AT89S52 be programmed using an Arduino as ISP?
Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?
I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.
According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?

Have you placed a capacitor between ground and reset?

Yup, I've tried putting a 10uF cap between the reset an ground of the arduino.

You should be able to use the Arduino as an ISP since an ISP is basically just a serial to SPI interface. If you are trying to use the arduino software to upload your program, you will need to edit your boards.txt file to be able to talk to the chip. If you are just using avrdude you will need to update your avrdude.conf.  AVR Freaks has a post on someone trying something similar and may be of some help. Without knowing your environment it's difficult to give more specific advice

I've used keil to get the hex file of  a simple blink program written in C. The problem I'm facing is burning this hex file onto the AT89S52. I've tried using progisp, 8051 loader and ISP Prog v1.4 but none of them detect the Uno as a programmer. Also I've uploaded the ArduinoISP sketch onto the Arduino.

You provided information for a) Arduino IDE and b) Avrdude. While accurate and correct, I am looking for a way to use programs like AVRISP, or PROGISP to work with Arduino as ISP. Because they provide easy and graphical interface to a) read HEX and b) program using ISP. Is there any way to use an Arduino Uno programmed with ISP sketch with these software? Sorry for the long comment.

You might be able to use the programmer sketch I wrote a while back (it runs on a Uno). You need an SD card interface so it can read the .hex file for programming. See: http://www.gammon.com.au/uploader
You connect things up roughly like this (Atmega328P shown, your wiring would be different at the target chip side):

You would need to modify the sketch to add the details for the AT89S52. As far as I can make out from the datasheet:

Signature: 0x1E 0x52 0x06
PROGMEM: 8k bytes
RAM: 256 bytes
Pinouts: Depending on the chip package. You need to identify MOSI/MISO/SCK/RESET along with Vcc and Gnd.
Fuses: None that I can see
Flash page size: 256 bytes

Thus you could modify the table of chips to add that one, along these lines:
// see Atmega datasheets
const signatureType signatures [] PROGMEM =
  {
//     signature        description   flash size   bootloader  flash  fuse
//                                                     size    page    to
//                                                             size   change

  // AT89S52
  { { 0x1E, 0x52, 0x06 }, "AT89S52",   8 * kb,           0,   256,   NO_FUSE },

// ... other ones here ...

I haven't got an AT89S52 to test it on, so I can't say for sure I got those parameters right. I am assuming that the programming instructions for ICSP programming are the same as for the other chips in their range.

Sketch source: https://github.com/nickgammon/arduino_sketches

Thank you so much for this brilliant guide! I shall test this today and get back to you with the results!

If you haven't been successful yet, Try this.(assuming it's still not solved.)
I'm using Arduino to successfully program the AT89S52.
Need 2 tools:
Arduino program and
an AT89S52 programmer software.
Here's a complete tutorial on how to do it.
Works on Windows, not so sure about linux.
http://www.instructables.com/id/ARDUINO-AS-A-8051-PROGRAMMER/?ALLSTEPS

authors: Александр Кирьянов


text:
driver is not showing up in Port assignments mac
arduino nano, the driver is not showing up in Port assignments. It has worked with this operating system before. I’ve messed something up.  “OS X EI Capitan ver. 10.11.3 I have check the posts but the serial port is a no show

Genuine Arduino nano, or cheap Chinese copy?

If the port showed in earlier versions of OS X, but never showed after upgrading to El Capitan, then you probably used an unsigned driver, which is no longer allowed by Apple's new System Integrity Protection (a.k.a. "Rootless"; more details in a WWDC session).
Any unsigned drivers will have been disabled during the upgrade process. Even more, SIP does not allow any non-Apple files in /System, /bin, /sbin and /usr (except for /usr/local), so anything you had put in there will have been moved away as well. To see what has been disabled:

ls -l "/Incompatible Software"
ls -lR /Library/SystemMigration/History/Migration-*/QuarantineRoot/*

To get it working again: find a signed driver, or Switch off SIP.


text:
How to wire an LMD18200 and an arduino?
Ive been working with a motor project for a while and i bought this H-bridge(LMD18200). I dont understand how im supposed to connect it to the arduino.
Here is the datasheet for the lmd18200:

Most basic way would be to use only DIR, PWM and Break.
Use Break as enable (put high at begining of the program, put low when you want to start rotation).
Use Dir to change rotation of the motor (usually high is CV, low is CCV, but you need to check the datasheet)
And hook up PWM to PWM pin on arduino. This will control the speed.

Do i just put the break and dir in any digital port?

yes, any output.
If you want to monitor thermal and current later on connect those to the input

To the analog inputs (A0 to A5 on the uno)

@jms they are in use. What do i do with tf and sen?

@Marc Sorry, I was confusing. The TF is just a binary output and can be connected to any IO pin configured as a digital input, but if you want to measure current you do need to connect CSEN to an analog input. You can still drive the motor without connecting TF or CSEN at all, they are optional.


text:
RC drag strip finish line with mph calculation (using 1" spaced lasers)
My question is: how do I read multiple inputs at the same time without using interrupts on an UNO.  I'm building an RC drag strip with tree and finish line that will calculate run time as well as calculate each run in mph.  I'm using lasers and non modulated laser detectors for the beams and I'm using a 1" beam gap(between 1st beam and 2nd beam) at the finish line(for mph calculation). My concern comes in when two cars come close enough at the finish line for one to break the first beam at set the win flag but the car in the other lane is close enough to cross the 1st beam before the 1st car actually crosses the 2nd beam then the detection loop is going to miss one of them. (just a note: a few of these cars can top 100 mph when crossing the line)

100mph 5280ft/mi12in/ft/(3600s/h)=1760in/s, so your system needs to measure on the order of 1in/1760in/s = 568 microseconds, broken down tighter for ties.  How many multiples?  Just two? Why not use interrupts?  From http://arduino.stackexchange.com/a/12958/6628 you could approach 0.01" resolution.

then the detection loop is going to miss one of them - how long are the cars? Isn't the bigger issue that the first beam will still be broken, and that the second car won't register at all, regardless of how you program it?

With the beams crossing both/all lanes, overlapping cars will always be an issue.  Whether for determining how fast the first car is or who is second with more than two lanes.  You will need to use separate detectors per lane if you want to avoid this.

@nick, your code in http://arduino.stackexchange.com/a/12958/6628 detected and switched in 1.52us. One could maybe save (PIND_last ^PIND)  and a timer/counter in a table of events with each pin change, and then leave the arming and interpretation to the loop().  You could store timing information at the resolution of the counter, and differentiate ties at the resolution of the interrupt servicing routine.  Maybe I'll copy your code and try that as an answer.

Yes, I was going to try a timing test once we cleared up the issue of the overlapping readings. But I agree it looks like you can get pretty good results.

ONE:
What you can do is use a while loop waiting for the first pulse and then wait until the last pulse, for an idea look at this code from Gadjet, he made a chronograph with a similar operation, you would just need to adapt the design, this might not be as accurate for an 1". Also it will be the issue of having ties between cars. This is short as I don't like this option.
TWO:
Another option, although using what you don't want to use, would be using the interrupts on the Arduino. I am basing the following on the fact that you are using two cars.
What you can do is have a finish line for both vehicles and detect a break with a interrupt, one interrupt pin per lane(UNO has to interrupts).
The trick here is that you place both the outputs from one lane onto a single interrupt pin with a edge detector type of circuit1 to generate a pulse while the vehicle crosses a point, especially important as it will be in the inch area for a while. The code handles the double pulse on one pin. I know this works as I used this on a ballistic chronograph which works in microseconds detecting shots >2000fps over a 0.406 foot distance.
1 This is an example of the circuit you would use at the output of each sensor before the OR gates:

The hardware would just become a duplicate for each lane, and to combine the input on one pin you can use an OR gate IC or you can use diode OR gate:

Interrupts are actually easy to use with Arduinos, and there are a lot of examples out there.
Have a look at the below flow chart to get an idea of operation in the code:

A small thing would be that the code ignores a interrupt once the cars have passed so it doesn't calculate a second time.

Building upon Nick Gammon's excellent answer at How many interrupt pins can an Uno handle? here's some untested code:
 const int events = 256; // events to store
 unsigned volatile int index;
 byte pinStates[events];
 unsigned int times[events];

 ISR (PCINT1_vect) //  Watch for pin changes on the C port (Uno pins A0-A5)
 {
   if (index == 0) { // start clock
    TCCR1B = bit(CS12) | bit (CS10) ;    // clock/1024 for <4.19s x 64us
    //TCCR1B = bit(CS12);                // clock/256  for <1.05s x 16us
    //TCCR1B = bit(CS11) | bit (CS10) ;  // clock/64   for <0.25s x 4us
    //TCCR1B = bit(CS11) ;               // clock/8    for <0.03s x 0.5us
    //TCCR1B = bit(CS10) ;               // clock/1    for <0.004s x 62ns
   }
   times[index] = TCNT1;
   pinStates[index] = PORTC;
   index = (index+1) & 0xff; // increment and protect from overflow

 }  // end of PCINT1_vect

void setup ()
  {
  // activate pin change interrupts on port C / pins A0-A5

  PCICR   =  bit (PCIE1);    // enable PCINT[14:8] pin triggers
  PCMSK1 |=  bit (PCINT8) |
             bit (PCINT9) |
             bit (PCINT10) |
             bit (PCINT11) |
             bit (PCINT12) |
             bit (PCINT13);     // enable individual pins

  // stop and clear 16 bit timer  CS1[0-2]=0; TCNT1 = 0;
  TCCR1A = 0;  // no comparisons, normal WGM mode, stop the counting
  TCCR1B = 0;
  TCNT1  = 0;  // Clear the counter

  pinMode (A0, INPUT_PULLUP);
  pinMode (A1, INPUT_PULLUP);
  pinMode (A2, INPUT_PULLUP);
  pinMode (A3, INPUT_PULLUP);
  pinMode (A4, INPUT_PULLUP);
  pinMode (A5, INPUT_PULLUP);

  index = 0 ; // nothing happened yet

  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {

   // check index, parse and report times, check for arming, etc...

  }

The point is to use the pin change interrupt to record state changes on the pins and the times.   The clock/1024 prescaler would give a 1/16MhZ*1024*65536= 4.19s window at 64us resolution timing counts, but you could go to higher resolution with a tighter window by using a smaller prescaler.
Also, if you wanted longer timing windows, you could cascade timer1 into timer0 (messing up millis(), etc.,) and get 24 bits of range before overflow, but a better way than cascading timers might be to add another interrupt to increment a variable.  For much longer timing windows add another quick interrupt to handle for timer1 overflow.
...
volatile unsigned long int t1Cycles,times[events];
...

ISR(TIMER1_OVF_vect){t1Cycles++;}

void setup(){
    ...
    TIMSK1 = bit(TOIE1);
    t1Cycles = 0;
    ...
}

ISR (PCINT1_vect)
{
    ...
    times[index] = t1Cycles << 16 | TCNT1; // store 32 bit count of clocks
    ...
}

This is still untested, but it looks like it could be capable of 268 seconds worth of 62ns resolution multichannel timing.  With the longer period, you could move the conditional clock-starting code out of the pin-change ISR.

I think I would use a much lower prescaler. Since you have kept the timer stopped until the first pulse, it won't take 4 seconds for the car to cross to the second laser.

One certainly could use a lower prescaler.  I chose the slower speed because my kids just did a pinewood derby race, and wanted to allow plenty of time to measure the slow cars to cross the line.

Are you trying to catch all entries? In that case 4s might be too little. You could catch overflows ... wait you just edited that in. Excellent. Tip: make t1Cycles volatile. Also I think you want to shift t1Cycles left 16, as Timer 1 is a 16-bit timer.

Yes, catching all entries was what I was aiming at.  Thanks for the tips.

I made more edits and it seems to compile for an Uno.  To test it on the AT90usb1286 hardware I've got, I'd need to switch things over to port B.

I chose the slower speed because my kids just did a pinewood derby race - so, not quite 100mph?

One option, if you want very-real-time processing, for a task like this that break neatly into chunks: Have one Arduino per vehicle.
Arduinos are cheap. If they are too expensive, use AtTiny's - they can be had for about a dollar a piece (depending on your currency). You can share a clock/power between a large number of them.
You can either have a "master" Arduino talk to each individual one, to collect the information, or have daisy-chained bus - each one can pass it's data to the next one in the chain (once is has the data, and the next one in the chain indicates it's ready for it).

I think my objection to this would be synchronizing them. Especially if they are each doing different lanes. If they didn't agree exactly on what the time was, they might report the runner-up as the winner.


text:
How do I use Sound Sensor LM393 + Speaker in Arduino
I have this voice sensor:

I need to know how bytes pass through soundsensor into arduino and get this bytes and put out in a speaker.
I read on the net a Lib PCM thats converts chars in voices, but how do I extract bytes from sound sensor in analog-in?

The board you have, if the same in the image has a D0 and A0, and from powers of deduction the D0 will give you true and false according to a set trigger level. You would also probably look what that library you mention uses as a sensor or the general way people use it and also how it expects signal information from a sensor.

for an example, after coding connect a bulb,and clap then the bulb wile turn on.

Oh, the joys of buying something off the Internet with no datasheet, no part number and no clue how to use it. And then expecting somebody else to tell you how it works.
That module looks like a KY-038, made by Keyes. No guarantees, though, because I'm not telepathic.
Bytes don't "pass through the soundsensor". Bytes don't pass anywhere, in fact. That board has an analogue output, A0, which is the amplified audio sensed by the microphone. It swings between 0 and 5 volts, and is 2.5V when no sound is being picked up. The board also has a digital output, D0, which is active-low when the intensity of the sound picked up by the microphone exceeds a thershold. I have no idea what this threshold is or what volume it represents, or if it can be changed.
Have a look at the pages on AnalogRead() for information on how to convert analogue audio to a digital signal.
I don't know what you mean by "a Lib PCM thats converts chars in voices" - 'chars' as in the C-type chars or do you mean literal 'characters from a voice', i.e. speech recognition? I cannot tell if you have misunderstood something or there's an unfortunate translation coincidence which is confusing matters.

thanks for this help, now i understand. sorry for something, english not is my natural language.

I guarantee you speak English better than I can speak any other language, so there is no need to apologise. I was keen to help but I didn't know how. If you have any other questions please ask.

Thanks man, i undestood that analog reads and then i will use this to put the sound out. I will try soon. But for my project i will have to change arduino to raspberry. I will need a camera module and my uno dont have enough pins and clock power haha, but thanks you a lot.

This post was awhile ago, but I wanted to offer some more definitive info for others like myself who were trying to identify it. What you have there is the Keyes KY-037 "high-sensitivity voice sensor" module. Mine came with the Inland Arduino Uno RFID Learning Kit.
Apparently the KY-037 and the KY-038 are the same except the KY-037 has a higher sensitivity microphone. I could not find any specs to quantify what that sensitivity difference is, however. Both have a LM393 voltage comparator on the board. The same Arduino code ought to work for both.
Here are a few helpful links I found, some also showing a bunch of the other Keyes modules and how to use them:
http://linksprite.com/wiki/index.php5?title=Advanced_Sensors_Kit_for_Arduino
http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Lectures/022-Basic%20Definitions%20and%20Concepts%20Sensors%20and%20Actiators%202013-10-10.pdf  (Page/slide 40)
http://tkkrlab.nl/wiki/Arduino_37_sensors

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


text:
Serial monitor disconnecting itself
Problem: can't print to the serial monitor, it appears that the serial monitor disconnects itself after uploading a program.
I'm brand new to arduino, and I'm trying to upload a basic program to print to the serial monitor.
I use an arduino uno and my OS is Ubuntu.
I am connecting the arduino to my PC via USB.
Using Arduino Studio Release 0.0.5 experimental build 0.0.5-16058
(I am able to communicate via the digital output pins, tested by making a simple circuit to make the led light blink)
Here is the program:
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    Serial.print("test");
    delay(500);
}

Here is the result of the build, look at the last line and it says the serial monitor was disconnected? Why would this happen automatically?
[2/2/2016 8:51:26 PM] - Start Building
[2/2/2016 8:51:26 PM] - CPP File Created [/tmp/build1454471486915/test.cpp]
[2/2/2016 8:51:26 PM] - test.cpp compiled
[2/2/2016 8:51:26 PM] - CDC.cpp compiled
[2/2/2016 8:51:27 PM] - HID.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial0.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial1.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial2.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial3.cpp compiled
[2/2/2016 8:51:27 PM] - IPAddress.cpp compiled
[2/2/2016 8:51:27 PM] - Print.cpp compiled
[2/2/2016 8:51:27 PM] - Stream.cpp compiled
[2/2/2016 8:51:27 PM] - Tone.cpp compiled
[2/2/2016 8:51:27 PM] - USBCore.cpp compiled
[2/2/2016 8:51:27 PM] - WInterrupts.c compiled
[2/2/2016 8:51:27 PM] - WMath.cpp compiled
[2/2/2016 8:51:27 PM] - WString.cpp compiled
[2/2/2016 8:51:27 PM] - abi.cpp compiled
[2/2/2016 8:51:27 PM] - hooks.c compiled
[2/2/2016 8:51:27 PM] - main.cpp compiled
[2/2/2016 8:51:27 PM] - new.cpp compiled
[2/2/2016 8:51:28 PM] - wiring.c compiled
[2/2/2016 8:51:28 PM] - wiring_analog.c compiled
[2/2/2016 8:51:28 PM] - wiring_digital.c compiled
[2/2/2016 8:51:28 PM] - wiring_pulse.c compiled
[2/2/2016 8:51:28 PM] - wiring_shift.c compiled
[2/2/2016 8:51:28 PM] - CDC.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HID.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial0.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial1.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial2.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial3.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - IPAddress.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Print.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Stream.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Tone.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - USBCore.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WInterrupts.c.o linked to core.a
[2/2/2016 8:51:28 PM] - WMath.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WString.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - abi.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - hooks.c.o linked to core.a
[2/2/2016 8:51:28 PM] - main.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - new.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.ino linked to core.a
[2/2/2016 8:51:28 PM] - wiring.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_analog.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_digital.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_pulse.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_shift.c.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.elf linked to core.a
[2/2/2016 8:51:28 PM] - test EEPROM
[2/2/2016 8:51:28 PM] - test.hex builded
[2/2/2016 8:51:28 PM] - Uploading...
[2/2/2016 8:51:30 PM] - Uploaded
[2/2/2016 8:51:30 PM] - [arduino ide - serial monitor] Serial monitor connected to /dev/ttyACM0
[2/2/2016 8:51:36 PM] - [arduino ide - serial monitor] Serial monitor disconnected from /dev/ttyACM0

Are you using the Arduino IDE? If so, what version? If not, what are you using?

Yes, ArduinoStudio Release 0.0.5 experimental build 0.0.5-16058

Does the serial monitor disconnect when you hold open the monitor and after that hold the reset button?

I'm not sure why your IDE is doing that, but the official Arduino IDE from Arduino.cc works on Ubuntu and does not have that issue. Download from Arduino Software download page.

I thought arduino studio was the official IDE, I'll download it and try it when I get home. Thank you for the suggestion

@JamesWierzba "Arduino Studio" is from Arduino.org, whereas this answer links to the standard IDE produced by Arduino.cc. Neither is more official than the other; the original Arduino company split into two factions and are now offering competing products and software.

I edited my answer to clarify that I was referring to the version from Arduino.cc. Arduino.cc has a forum where you can ask questions like that. Arduino.org does not appear to have a forum (as far as I can see).

I downloaded the Arduino IDE you suggested and printing to the serial monitor now works. Thanks


text:
Can I connect an Arduino wifi module directly to my android phone?
I would like to use my arduino even where there's no wifi router. I've only found people saying that it needs to connect to a router, but isn't the phone like a router when it's in tethering mode? Do I still need a mobile internet connection or can I do it directly?

A phone running in wifi tethering (mobile hotspot) mode is no different to a wifi access point or router. So yes, you can use that.
Chances are though that you will need a mobile internet connection in order to activate mobile hotspot mode in the first place.

My Galaxy Mini 2 lets me turn mobile router while not connected to mobile connection. The matter's that the example sketches that I've seen by now are all something like this: connect to a router, get the ip, and then from android you put the ip and connect to the arduino. I'd like to skip the ip part: arduino connects to the mobile router, and (since when you connect to a router you need to send data back and forth from router to user and vice versa) they exchange data even if the mobile phone has no connection. Can I do this?

You need the IP. Without that you don't know where to send data. You may be able to find it in the tethering settings under the list of connected devices depending on the version of Android.

So I always need an internet connection. I thought it would have worked like bluetooth, since router and user need to talk to each other, but what you're saying suggests me I can't. Unless I can use the "internal IP" (don't know if it is its name), the one that is always 192.something. If I can use that, isn't it given before the connection to the internet starts?

An IP is an IP. Every device connected on a network needs one. The phone can hand one to the Arduino through DHCP. You don't need an internet connection for that, not if you can turn on mobile hotspot without one. It sounds like you need a crash course in how networks work. Browse around wikipedia a bit and learn the basics first.

If you are using the Arduino UNO WiFi Board (http://www.arduino.org/products/boards/arduino-uno-wifi) with the built in ESP8266 chip then your phone can connect directly to the Arduino's network and you can interact with it that way.
With the default firmware, this board can simultaneously connect to a local WiFi network, and create its on access point. This is very handy because it means that you can connect and access its hosted web pages even without a WiFi router with no extra setup steps, or special configuration.

Sounds like the OP wants the opposite.  Not using a phone to connect to the ESP8266 module (as AP or captive portal).. but use the ESP8266 to connect to the phone and use it as an AP.

@whispers That could be, but the question isn't clear, and often when the question isn't clear it is because the OP didn't know that the other method was even an option.


text:
Why the serial connection only work when Tx and Rx are shorted?
I have a Arduino Pro Mini 3.3V connected to a sim800l chip using a serial connection of 9600bps. When I connect the Arduino to the device, it seems I don't receive anything on the Arduino Rx pin.
I then connected a FTDI that listen the sim800l Tx pin:

The FTDI is able to receive data so this means the sim800l is working well by receiving data from the Arduino and responding accordingly.
So normal logic would say that the Arduino Rx pin is not working but when I connect the Arduino Rx and Tx pin together:

I'm able to receive what I send on Tx on the Rx pin.
Why would that be?
I tried with AltSoftSerial and SoftwareSerial. The Arduino is powered by a FTDI connected to my computer via USB. The sim800l is powered by a second FTDI that is also powered by my computer USB. So all component uses the same ground and I verified that with my multi-meter.
Here is the code I use:

AltSoftSerial sim800Serial(8,9); // RX, TX

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

while(1)
{
  if(sim800Serial.available())
  {
    Serial.write(sim800Serial.read());
  }

  if(Serial.available())
  {
    sim800Serial.write(Serial.read());
  }
}

Please complete the circuit with VCC and GND so we understand the complete connection.

As well as the code you wrote to receive data from the device

connected to some device Y  - what device? Part number? Datasheet?

Mikael Patel is right - if you didn't connect the grounds the device may well not work. However the Pro Mini can talk to itself because the grounds are connected internally.

I added more details to my question that answer yours. Let me know if I need more clarifications.

Are those grounds all physically connected in your circuit or are you relying on the grounds provided by the various USB modules being linked via your computer's ground?

with power off, I measured all ground and they are shorted and have a very little resistance

I also tried putting all devices on the exact same ground without success.

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


text:
Converting TinkerKit to native Arduino pins
Over the years, I have acquired many TinkerKit modules for my Arduino Uno. My only issue is that I need to find a way to code using the native syntax, and not the less-powerful TinkerKit variation. To do this, I need to know if TinkerKit maps its 3-pin connector to the Arduino Board's pins (ex: 1, 3, 5). If it does, what are the mappings?
Thanks in advance!

The TinkerKit Sensor Shield helps understand the mapping. There is also the TinkerKit Header File with symbol mapping.


text:
Arduino throwing error while using modbus RS485 code
I have been trying to make a communication with my industrial drive. All I want to do is read a few values of drive, like current, voltage etc.
For that I am using a library:
I don't understand why it's happening. When the same code I have used before and the sketch was uploaded on the board, very well.
Here's the code from an example:
#include <SimpleModbusMaster.h>

// led to indicate that a communication error is present
#define connection_error_led 13

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate

// If the packets internal retry register matches
// the set retry count then communication is stopped
// on that packet. To re-enable the packet you must
// set the "connection" variable to true.
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  // leave this last entry
  TOTAL_NO_OF_PACKETS
};

// Create an array of Packets for modbus_update()
Packet packets[TOTAL_NO_OF_PACKETS];

// Create a packetPointer to access each packet
// individually. This is not required you can access
// the array explicitly. E.g. packets[PACKET1].id = 2;
// This does become tedious though...
packetPointer packet1 = &packets[PACKET1];
packetPointer packet2 = &packets[PACKET2];

// The data from the PLC will be stored
// in the regs array
unsigned int regs[9];

void setup()
{
  // read 3 registers starting at address 0
  packet1->id = 2;
  packet1->function = READ_HOLDING_REGISTERS;
  packet1->address = 0;
  packet1->no_of_registers = 3;
  packet1->register_array = regs;

  // write the 9 registers to the PLC starting at address 3
  packet2->id = 2;
  packet2->function = PRESET_MULTIPLE_REGISTERS;
  packet2->address = 3;
  packet2->no_of_registers = 9;
  packet2->register_array = regs;

  // P.S. the register_array entries above can be different arrays

  // Initialize communication settings etc...
  modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS);

  pinMode(connection_error_led, OUTPUT);
}

void loop()
{
  unsigned int connection_status = modbus_update(packets);

  if (connection_status != TOTAL_NO_OF_PACKETS)
  {
    digitalWrite(connection_error_led, HIGH);
    // You could re-enable the connection by:
    //packets[connection_status].connection = true;
  }
  else
    digitalWrite(connection_error_led, LOW);

  // update the array with the counter data
  regs[3] = packet1->requests;
  regs[4] = packet1->successful_requests;
  regs[5] = packet1->total_errors;
  regs[6] = packet2->requests;
  regs[7] = packet2->successful_requests;
  regs[8] = packet2->total_errors;
}

Also, here is the error I am receiving upon uploading the sketch
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
SimpleModbusMasterExample:110: error: 'packetPointer' does not name a type
SimpleModbusMasterExample:111: error: 'packetPointer' does not name a type
SimpleModbusMasterExample.ino: In function 'void setup()':
SimpleModbusMasterExample:120: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:127: error: 'packet2' was not declared in this scope
SimpleModbusMasterExample:136: error: invalid conversion from 'int' to 'HardwareSerial*'
SimpleModbusMasterExample:136: error: invalid conversion from 'Packet*' to 'unsigned char'
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:143: error: too few arguments to function 'void modbus_configure(HardwareSerial*, long int, unsigned char, long int, long int, unsigned char, unsigned char, Packet*, unsigned int, unsigned int*)'
SimpleModbusMasterExample:136: error: at this point in file
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h: In function 'void loop()':
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:125: error: too many arguments to function 'void modbus_update()'
SimpleModbusMasterExample:143: error: at this point in file
SimpleModbusMasterExample:143: error: void value not ignored as it ought to be
SimpleModbusMasterExample:155: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:158: error: 'packet2' was not declared in this scope

I would guess that it's not your code that has changed but the library you are using. Are you sure you have the right version of the right library?

The code you are using is the example provided with the SimpleModbusMaster library found on GitHub: https://github.com/angeloc/simplemodbusng
It appears that the SimpleModbusMaster library isn't installed. This can happen if you install a new version of the Arduino IDE.
To install this library:

Go to the link above and download the zip of the code.
Extract the contents and then copy the folder "SimpleModbusMaster".
Paste the folder into the Arduino/libraries folder located on your computer.  (On my computer it is: C:\Program Files (x86)\Arduino\libraries).
Restart the  Arduino IDE. You can go straight to the example code by selecting: File > Examples > SimpleModbusMaster > SimpleModbusMasterExample

This procedure compiled for me with no errors.

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
Read RFID Card Number in Processing over Serial
I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.
Its program for Arduino is below:
int count = 0; // count = 0

char input[12];                                         // character array of size 12

boolean flag = 0;                                       // flag =0

void setup()
{
   Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
}

void loop()
{
   if(Serial.available())

{

count = 0;

while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

{
input[count] = Serial.read();
count++;
delay(5);
}

//Serial.print("Card ID - ");

Serial.print(input);      // Print RFID tag number

}

}

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match.
Hence the mouse doesn't get unlocked.
The program for processing is as below:
import processing.serial.*;
import java.awt.AWTException;
import java.awt.Robot;

Robot robot;
boolean locked = false;
Serial port;
void setup()
{
  println(Serial.list()); //Prints available ports

  port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
  try
  {
    robot = new Robot(); //Creates robot
  }
  catch (AWTException e)
  {
    e.printStackTrace();
  }
}

void draw()
{
  if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
  while (port.available() > 0)
  {
    String input = port.readString();
    //println(input);
    if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
  }
}

void keyPressed ()
{
  if (key == 'l')
  {
    locked = true; //Locks it
  }

  if (key == 'u')
  {
    locked = false; //Unlocks it
  }

  if (key == ESC)
  {
    key = 0; //Disables escape as quit
  }
}

Please point the incorrect syntax and suggest correct one.

input has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before Serial.print(input), you write input[12] = 0. Also the argument to string.equals() should be a String as well; you must write the statement like this: input.equals(String("11006F26DC84"));


text:
How to latch a 200mS LOW pulse?
Trying to latch a 200 mS, LOW event to log the event.  LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.
Is a D Latch suitable for this application?  It has been years since my digital class; help most appreciated.
How would you proceed?

Just as a side-note; you know the arduino chips have build in watchdog timers, right?

I am using Switchdoc Labs, "Dual Watchdog Timer" with an Arduino Mega running a Data logger/web server.

Project web page: http://tinyurl.com/Data500

I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.
D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).
You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.

I tried a S-R Latch (74LS279); so far it is not working.  What voltage should I expect on a LOW to the S input?  Measured 150mV, is this a failed 74LS279?

First, power from 5 volts.     Second : Tie all unused inputs HI. On the SR latch that you are using, R must be high (except when resetting). When S goes low, the Q output should be near 5 volts.

I have the 74LS279 wired and working; however, there is not enough drive from the external Watchdog timer output.  Will two inverters in series give me more drive?  Measured 2.5 volts at the bottom of the pull-up resistor.   Need to go to the Arduino Mega reset and to the S input of the Latch.  --Thank you for the help!

Documentation on the Dual WatchDog is poor. The output is reported as "pulled to ground",  "otherwise high-impedance". You didn't say what value of pull up resistor you are using.  Measuring 2.5 volts indicates that your pull up resistor might be too large of a resistance.

Normal operation of Arduino (program running) Q= HIGH, S" HIGH, and R= LOW.  When a WATCHDOG reset occurs I see Q go momentarily LOW (0.565 Volts. --HIGH being 4.77 Volts.) Observation made with voltmeter.  Problem is that it happens so fast by the time the Arduino reads the pin for Q status; it is already a HIGH.  I never get a Q value Of LOW when I read the pin connect to Q.  I am trying to do a conditional based on the status of Q. Suggestions?

You Do NOT want R = Low. . .  Let us try again.  S= Hi . .  R = Hi (presuming that Q=LO after a reset on R). . .  . .When watchdog goes low , (this is tied into the Arduino Reset), and also, S is pulled low by watchdog.  S going low  causes Q to go HI. Q stays HI until R is pulled low by operator (human).

Now using a D-Latch (74LS74) with an inverter (74LS04) it appears to be working; needs some tweaking and testing.  Weblink has two files of what I am doing with D-Latch code wise and the hook-up to the Arduino Mega-and-SwitchDoc Labs, "Dual Watchdog Timer.".   http://tinyurl.com/74ls74


text:
Detecting Motion behind a robot
I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side.
When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance <= 50 cm and > 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it.
 I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.

PIR sensors only detect moving heat sources. That is, moving relative to the PIR sensor. If the PIR sensor is moving then everything is moving relative to it, so who knows what it will be detecting. PIR is not, IMHO. a good choice for this kind of thing.

Dont worry about that. The if statement conditions state that when only one PIR detects motion, then the robot turns towards that side. Then it again checks the outputs.

Couldn't you point the PIRs slightly to the back. So you essentially split the 360degrees into three sections.

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

This is a basic problem of only having two sensors.  There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors.  Anything else is, and always will be, ambiguous.
If you think of it as a circle divided in two, you have only three possible conditions:

That is, left, right or somewhere.  Not ideal.
So you need more data to be able to make a decision.  That means more sensors.  The ideal scenario is four sensors - left, right, front and rear.  That gives you many possible scenarios, including:

As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on.  For instance, using sailing terminology, those 8 circles would mean (in order):

Motion on the left beam
Motion on the port bow
Motion dead ahead
Motion on the starboard bow
Motion on the starboard beam
Motion on the starboard quarter
Motion dead astern
Motion on the port quarter

Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off.  You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.

OK that is a good answer, I had thought of a similar answer but using only 3 PIR and 1 ultrasonic. Do u think it is possible?

3 PIR could be possible, but harder to manage. You could either have the three as an equilateral triangle, but then you won't really know if it's left or left and behind, etc. You could have three of the four laid out as above - just the 4 with one missing - and assume that if the front is off the rear must be on when both left and right are also on - which is most likely the case. So you could save one PIR that way.


text:
Precision voltmeter using Arduino
I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision.
The voltage will not be greater than 1V-1.2V.
I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.
Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why.

A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage.  Using a divider on a small voltage will only make it smaller and harder to measure.
To get the most out of your measuring you need to have the reference voltage as close to the highest voltage you want to measure as possible.  The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.
So you need to change the reference voltage - the voltage that the ADC uses as its upper measurement voltage.  That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: analogReference())
So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps.  That's 1.1/1023=0.00107V per bit of precision.
The formula is:
V = ADC / 1023 * Vref

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc.  That's plenty of resolution to meet your 2 decimal places requirement.
One thing to note though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips).  If you need better stability and accuracy then it could pay to use an external voltage reference chip.  These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current).  Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external ARef pin and switch the analog reference to the EXTERNAL mode.
You could use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.

Great answer, Majenko! Just to add to it, see my post about ADC conversion on the Arduino - in particular the part about setting up reference voltages. That link takes you to the post about the TL431 voltage reference chip.

Majenko, do you have any documentation or rationale for your claim that “the internal 1.1V reference isn't that stable or accurate” ?  Per spec sheet, the 1.1V reference is an “internal bandgap reference... through an internal amplifier” which does not suggest  instabiliry or inaccuracy.

@jwpat7 Well, table 29-11 lists the voltage as between 1.0 and 1.2 with a typical of 1.1. That's a variance of as much as 20% in the actual voltage, and no practical way of measuring it. When you're working with voltages as low as 0.8V max that variance can have a big effect on your readings.

@jwpat7 Also you might like to take a look at figure 31-318 which shows the variation in bandgap voltage at different levels of Vcc and different temperatures.


text:
SoftwareSerial library
How do I rectify this error?
Clearly it says there is some error in the library, so how do I correct it?
C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

Sounds like you have some corruption in the file. Try reinstalling.

you mean retry installing the library ? @Majenko

Or the whole IDE since it comes with the IDE

The other possibility is a syntax error in your sketch? I'm not sure how the IDE builds, but if it doesn't compile each file separately the error may come from another place and the most likely place to look is in your code. Before you reinstall take a look at the file that is generating the error and see if you notice something wrong. Just for the practice.

Which version of the IDE are you using? Please post all the output from the compiler. Please edit your post to do this and format the output using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

I'm not sure how the IDE builds - see How the IDE organizes things.

Show us the first handful (10 or so) of lines of the file C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp

there is only this 1 error ---
C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
{
// Disable further interrupts during reception, this prevents
// triggering another interrupt directly after we return, which can
// cause problems at higher baudrates.
setRxIntMsk(false);
// Wait approximately 1/2 of a bit width to "center" the sample
tunedDelay(_rx_delay_centering);
DebugPulse(_DEBUG_PIN2, 1);

for (uint8_t i=8; i > 0; --i)
{
  tunedDelay(_rx_delay_intrabit);
  d >>= 1;
  DebugPulse(_DEBUG_PIN2, 1);
  if (rx_pin_read())
    d |= 0x80;
}

First few lines of my library

Then there is a huge chunk of the file missing - 220 lines to be precise (that is line 221 you have there). A reinstall of the IDE should have fixed it. Did you do it?

Yeah it worked! Done compiling successfully... Can you please explain how downloading a new IDE solves the problem ? @Majenko

The file was corrupt. You replaced it with a new copy. How it got corrupted is anyone's guess.

As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is.  However, here are links to three instances of the same error:
• error: expected unqualified-id before 'if' on stackoverflow
• Arduino: error: expected unqualified-id before 'if' (using ping sensor), also on stackoverflow
• error: expected unqualified-id before 'if' on arduino.cc.
In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function.  You may have put some executable statements outside of loop() or setup(), etc.

Still problems related to my library...i reinstalled my IDE and in the new one SoftwareSerial.h doesnot exist..what should i do?

You may need to separately download and install SoftwareSerial.  You can get SoftwareSerial.cpp and .h from github and follow the directions at arduino.cc, Installing Additional Arduino Libraries.  Note, arduino library downloads from github normally are zip files; I didn't see a zip file in this case, so adapt the instructions accordingly.

Your copy of the SoftwareSerial library has become corrupted. Why is anyone's guess: maybe your hard drive is dying?
Replacing the file with a good copy will solve the problem. The simplest way to do that is to reinstall the IDE.


text:
Atlas Scientific pH project - serialEvent3 problems
I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true.  I am not sure if it is actually capturing the values from the probe.  What I want is for every loop through it should grab a pH value and that is not happening right now.  Most times through the loop the serial3 port is not providing any values.  Here is my code:
String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

void setup() {
  Serial.begin(38400);
  Serial3.begin(38400); // pH stamp
}

void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
  sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
  sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
}

void loop() {
  getPh();
  if (sensor_string_complete == true) readph();
}

void getPh() {
  Serial.println("we are here");
  Serial3.print("r");
  Serial3.print(13);
}

void readph(){
  Serial.println("read ph here");
  if (isdigit(sensorstring[0])) {
    pH = sensorstring.toFloat();
    Serial.println(pH);
  }
  else{
    Serial.println(sensorstring);
  }

  sensorstring = "";
  sensor_string_complete = false;
}

This returns values such as
we are here
we are here
we are here
read ph here
7.0
we are here
read ph here
7.0
we are here
we are here
we are here
read ph here
7.0
I want this to return these values every loop.  I expect to see:
We are here
read ph here
7.0
We are here
read ph here
7.0
Any help on this would be great.  Thanks so much!

On a typical Arduino, the delay between loop() ending and loop() running again is a few microseconds.  Serial.println() in getPh() is interrupt-driven so that call too takes only a few microseconds.  Writing two bytes with Serial3.print() at 38400 bps will take about half a millisecond.  In short, there is plenty of time for loop() to run several times before  serialEvent3() sets sensor_string_complete.
To call  getPh() once and readph() once per loop(), instead of
if (sensor_string_complete == true) readph();

say
while (!sensor_string_complete) {}
readph();

This will stall the loop while the pH sensor takes and reports a reading.
Note, in getPh() instead of using two separate Serial3.print() statements, you can just say Serial3.print("r\r").


text:
Using Bluetooth module HC-05 when Arduino is powered using a battery
I have a project that involves sending messages from an Android device to an Arduino using a bluetooth module. I am using an HC-05 bluetooth module and an Arduino Mega 2560.
It works as long as I power the Arduino to my laptop using a USB cable. However, I need to use an external power source and have been using a 6F22 9V battery connected through the VIN pin for this purpose, without facing any problems. But on connecting the HC-05, it does not even light up.
The Arduino is also connected to four dc motors, five servo motors (all of which are externally powered, only get digital signals from the Arduino), and seven HC-SR04 ultrasound sensors, whcih are powered through the 5V pin.
I have connected the HC-05 to the Arduino as follows:
HC-05   Arduino
VCC      3.3V
GND      GND
TX       RX
RX       TX           through a voltage divider
I am new to all this, and would be grateful for any help. Thank you.

6F22 (PP3) batteries are among the wimpiest of batteries available.  They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.
Use a better battery.  I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.
Either that or a 7.2V "2S" Li-Ion battery pack.

Thank you for the reply! Is the problem occurring because the current provided by the 6F22 is not enough?

Quite possibly. Try a more powerful battery and see if the problem goes away.


text:
Arduino Due: Interrupt-based ADC hangs processing
I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:
#define SAMPLE_BUFFER_SIZE 800
volatile int sample_buffer[SAMPLE_BUFFER_SIZE];
volatile bool sample_buffer_full = 0;
volatile int sample_buffer_idx = 0;

void adcm_init() {
    pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it
    adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed
    adc_disable_interrupt(ADC, 0xFFFFFFFF);
    adc_set_resolution(ADC, ADC_12_BITS);
    adc_configure_power_save(ADC, 0, 0); // Disable sleep
    adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values
    adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption
    adc_stop_sequencer(ADC); // not using it
    adc_disable_tag(ADC); // it has to do with sequencer, not using it
    adc_disable_ts(ADC); // deisable temperature sensor
    adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7);
    adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode
    adc_disable_all_channel(ADC);
    adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled
    adc_enable_interrupt(ADC, ADC_IER_DRDY);            // Data Ready Interrupt Enable
    NVIC_EnableIRQ(ADC_IRQn);
    adc_start(ADC);
}

void ADC_Handler(void)  {
    if (!sample_buffer_full) {

        if ((adc_get_status(ADC) & ADC_ISR_DRDY) == ADC_ISR_DRDY) {

            sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC);
            sample_buffer_idx++;

            if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) {
                sample_buffer_full = 1;
                sample_buffer_idx = 0;
            }
        }
    }
}

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

void loop() {
    Serial.print("Loop\n");
    if (sample_buffer_full) {
        for (int i = 0; i < SAMPLE_BUFFER_SIZE; i++) {
            Serial.print(sample_buffer[i]);
            Serial.print(" ");
        }
        Serial.print("\n");
        sample_buffer_full = 0;
    }
}

This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.
The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.
What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.
If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).
The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.
Any ideas? I'm really at a loss here...

You only want two samples?

@NickGammon No, of course not. I'd like hundreds of them. Sorry, that was just me testing the code (edited question and changed sample number to 800).

I'm no Due expert, but where do you link ADC_Handler as being the interrupt handler for those interrupts?

I've spotted a few threads that mention that handler but they have it inside extern "C" declarations.

@NickGammon It's defined in the ATMEL source code as void ADC_Handler        ( void ) __attribute__ ((weak, alias("Dummy_Handler")));

Try making it extern "C" - from what I have just read Dummy_Handler consists of: while(1) { }

In your interrupt handler, ADC_Handler(), you set sample_buffer_full when the buffer is full.  I don't see anywhere in the code where  sample_buffer_full ever gets reset (cleared) once it's been set.
While sample_buffer_full is set, it disables the body of the interrupt handler – ie, the handler's structure is
if (!sample_buffer_full) { ...body of handler... }

– and in particular, prevents adc_get_latest_value(ADC); from occurring.  The source code of adc_get_latest_value(); is like
uint32_t adc_get_latest_value(const Adc *p_adc) {
  return p_adc->ADC_LCDR;
}

which accesses the ADC data register.  According to section 43.6.4 Conversion Results on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf,

The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an
  interrupt.
Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets sample_buffer_full, then spins in ADC_Handler().  That is, repeatedly executes ADC_Handler() without clearing the EOC bit.
Note, for  oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion.  See thread #137635, speed of analogRead, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond.  Also see edaboard.com/thread283843 and forum.arduino.cc #186169
Edit note: Although sample_buffer_full does get reset, that reset happens after a time-consuming for-loop.  Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before sample_buffer_full gets cleared.  One unhandled conversion is enough to lock up the interrupt handler.  Here are some alternative approaches to consider:
• Use a circular buffer, and never stop filling it.  This is ok if you are only interested in the most recent data, rather than a complete waveform record.
• Set or reset sample_buffer_full as now; and remove the initial if test from the handler.  Instead, put an if before sample_buffer_idx++;, to not increment if the buffer is full.
• Turn off ADC's freerun mode.  This is a reasonable thing to do when not taking data.
• Turn off ADC's interrupt when not taking data.  Also reasonable.
• Use multiple buffers.  Reasonable, but by itself doesn't avoid the problem.
• Read the latest value every time the handler executes [for example, say int datum = adc_get_latest_value(ADC); as the first statement in the handler] and then only store that value in certain cases.  An easy and effective way to avoid problem.

Sorry, I copied my code wrong. There should be a line sample_buffer_full = 0; inside my loop code (I've edited my question). The code with that line does not work.

Also, many thanks for the DMA buffers suggestion. I'd already seen some code examples use that, but I was trying to get it to work this way first before moving on to other more advanced options.

Ohh! I see! Well caught, thank you very much. That might just explain the problem, yes...

Yes, I tried your last suggestion and it works perfectly, which means your answer was spot on. You certainly deserve an upvote and an accepted answer. Thank you very much!


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

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

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

Why isn't the motor completely turning off?

is that REALLY exactly how you have the cct?

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

And you forgot your flyback diode...

Also did you consider the inertia of the motor?

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

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

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

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

My precious reputation :(

Have an upvote, my friend.

There are multiple things wrong with your drawn schematic:

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


text:
Arduino MP3 Player
I want to make a MP3 player with arduino. My problem is what board should I use? There is the SparkFun MP3 Player Shield, SparkFun Audio-Sound Breakout - WTV020SD. Then I want to attach a 2.8 TFT touch screen to control volume,change track etc. Can I attach it to for example on top of MP3 player shield?I'm thinking in this one https://www.adafruit.com/products/1651. And finally what speakers can I use with which board? I want some good small speakers, two to be exact.
I don't really need help with electronics and programming. Just need to know wich are the best components that can work with each other without spending a lot of money. Thank you.
Best Regards

If you don't need help with electronics then you'll already know that you should be reading datasheets and schematics.

I would recommend you do not use speakers but instead send the output to a 3.5mm stereo plug, so you can use headphones or speakers.
Is a 2.8" inch display really necessary?  You could probably get away with a 1" display and at a guess that would use less power.
Another idea may be to look at a Bluetooth interface for sending the sound to the headphones or speakers.
You could also look at a WIFI interface to provide additional control interface and to allow downloads straight to the device.  (ESP8266 would probably be the easiest interface).
Something you didn't mention was the power source.  Are you going to have internal batteries with a USB charging and power socket, so you can hook it to a PC or Batter Pack.

I would recommend you the VS1003 chip ($2.30 on ebay) or module ($7 on ebay). It can play MP3, WMA, MIDI, WAV and can record and encode ADPCM. It's even programmable (own filters etc). See this project.


text:
c expected ; before ) token
void GravaFicheiros(CONFERENCIA *co)
{

    int i, ii, iii;

    FILE *fp;

    fp = fopen("grabameisso", "wt");

    fprintf (fp, "%s\n", co->nomeconf);

    int k = NSessoes(co);
    fprintf (fp, "%d\n", k);

    for (i = 0; i < k; i++)
    {

        fprintf (fp, "%s\n%d\n%d\n", co->sessoes[i].tema, co->sessoes[i].hora, co->sessoes[i].auditorio);

        int a = NArtigos(co, i);

        fprintf (fp, "%d\n", a);

        for (ii = 0; ii < a; ii++)
        {

            fprintf (fp, "%s\n", co->sessoes[i].artigos[ii].titulo);

            int aa = NAutores(co, i, ii);

            fprintf (fp, "%d\n", aa);

            for (iii = 0; iii < aa, iii++)
            {

                fprintf (fp, "%s\n%d\n", co->sessoes[i].artigos[ii].autores[iii].nome, co->sessoes[i].artigos[ii].autores[iii].idade);
            }
        }
    }

    fclose(fp);
    return;

You did not actually ask a question. Please read How do I ask a good question. I'm going to close this question. Please put a little more effort into your "question" next time, such as actually asking one.

Although you didn't ask a specific question I assume you want to know why there was an error in your code.
One of your for loops is missing a semi-colon.

for (iii = 0; iii < aa, iii++) //this line gives the error

Should be:
 for (iii = 0; iii < aa; iii++) //the comma should be a semi-colon

When it says ; expected before token ). It means quite literally that there is a ; missing before a ).