text:
Altering code to run a timer while checking for a data input
I am rather new to the Arduino world and am looking for a way to create my own tipping rain gauge with only one Arduino(micro).
I have had some help from a friend to get a loop that checks for when a switch is closed, which signals that the bucket has tipped and thus "x units" of rain have fallen. The code I have for sensing this is:
void loop()
{
  /*
    digitalWrite(4, HIGH);
    delay(500);
    digitalWrite(4, LOW);
    delay(6500);
  */
  int analogValue = digitalRead(8);

  if (analogValue==HIGH)
  {
    Serial.println(count);
    count++;
    delay(250);
  }
}

Then I developed a code to count up in 0.5 second intervals so that I could essentially time stamp when the switch from the first loop was closed/activated. The code for the timer is as follows:
void loop()
{
  while (ssec < 10)
  {
    Serial.print(hour);
    Serial.print(":");
    Serial.print(minute);
    Serial.print(":");
    Serial.print(sec);
    Serial.print(".");
    Serial.print(ssec);
    //Serial.print(" s");
    //Serial.println();
    ssec += 5;
    delay(500);
    Serial.println();
  }
  if (ssec == 10);
  {
    sec++;
    ssec = 0;
    //Serial.print(sec);
    //Serial.print(".");
    //Serial.print(ssec);
  }
  if (sec == 60)
  {
    minute++;
    sec = 0;
  }
  if (minute == 60)
  {
    hour++;
    minute = 0;
  }
  if (hour == 24)
  {
    Serial.println();
    Serial.print("DAY ");
    Serial.print(day);
    Serial.print(" COMPLETED!");
    Serial.print("Data Points: ");
    //Serial.print(count);
    Serial.println();
    Serial.println();
    hour = 0;
    day++;
  }
}

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.
Are there any ways to essentially run these side by side? Or a library I can use that will run the timer while i have the arduino looking for the switch to close, and I can simply call the timer when I need it?
Thank you for any and all help! :)

What's with the double-spacing? It makes it hard to read.
if(ssec==10);

That is wrong.
Arduino programming traps, tips and style guide

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:
How to do multiple things at once ... like cook bacon and eggs

I couldn't understand how to format the code and it was just coming up as a big chunk of text, so i just spaced it out.

This site does explain how to do that (and I edited it for you). Basically you select the code and click on the "code" button which indents it all 4 spaces. The indentation is what is needed, not lots of new lines.

You can find some 3rd party library that does software emulation of threads.
For example: ArduinoThread.
With the use of such library I successfully developed an app that was switching LEDs on and off and at the same time listened to any data coming from Bluetooth (serial port). It is worth a try.

No, this is really not a problem that calls for threads.  Jumping right to that for a problem of this simplicity is skipping over some of the key basics of embedded development, and not something that should be encouraged.

If you do not need to know the timing when the event occurs with a high resolution, and do not have anything else you need to do, you can simply delay in short intervals and check the condition in between them.  Of course you will not know when the event occurred more precisely than knowing it happened sometime in the interval since the previous check.
Another approach is to not use the delay mechanism, but rather continually check the input in a loop, and also check the elapsed time so that you can accomplish your periodic events when intervals of time have elapsed.  Do be aware of the millis() overflow eventuality if taking this approach.
If you had important work to do while waiting, you could accomplish the check with a pin change interrupt, and record a timestamp in the interrupt service routine, but if all you would be doing in the foreground is running a delay, this is inferior to the previous approach.  Using an interrupt service routine (or any more elaborate form of threading) also requires care to ensure consistency of data shared between the main and interrupt or alternate thread context.
Ultimately the best solution for an actual real-world embedded application like this is typical to try to have the processor in a low powered sleep mode most of the time.  Typically you would have a low power real time clock running, but the processor's high speed clock and associated logic stopped.  Your tilt sensor would be wired as an interrupt that the MCU is configured to wake up to normal operation in response to.  On wakeup, it would read the clock to accomplish a timestamp, then go back to sleep.  You can also use various mechanisms in the real time clock or in the MCU to wake up periodically to announce the passing of time intervals.  Wakeup on a small MCU is typically a fairly efficient process - it can be beneficial in terms of net power consumption to go (at least partially) to sleep even for a fraction of a second.

Just in case the OP goes looking for it, there is no RTC on 8-bit AVRs (UNO, Mega2560 et al) nor the Arduino 101.  There is an RTC on the 32-bit SAM-based boards (Due et al).

Yes, you can run the two loop() function side-by-side with a Multi-tasking Scheduler.
Please see https://github.com/mikaelpatel/Arduino-Scheduler. There are plenty of examples to get you started but basically you call Scheduler.start() with loop() functions. You will have to give them different names.
The Scheduler will context switch between the loop() functions on yield() or delay().
Cheers!


text:
Problem assign float to an embed class within the Linked-list libary
I have successfully implemented some code which uses a linked-list.  Everything is working, except assigning a value to a float within the embeded class.  When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect.  However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug.  I am using codebender on Chrome, and I have tried Firefox (both given same results).
Main Sketch https://codebender.cc/sketch:175995
Example of library working https://codebender.cc/sketch:176008
Can anyone help?
typedef void(*GF)(void);

#include "LinkedList.h"

class CsC {
    public:
        float PerS;
        GF FunctionToCall;
};

LinkedList<CsC*> TaskList = LinkedList<CsC*>();

void LEDON()
{
    digitalWrite(13,HIGH);
}
void after(float interval, String intervalDescription, GF func);

void after(float interval, String intervalDescription, GF func)
{
    float multi = 1;
    if(intervalDescription == "mins") multi *= 60;
    float delayMS = multi * interval;
    CsC *c;
    //Error if either of these lines uncommented
    //c->PerS=10000;
    //c->PerS=delayMS;
    c->FunctionToCall=func;
    TaskList.add(c);
    Serial.print(".");
}

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Serial.println("Start write task list");

    after(35,"secs",LEDON);

    Serial.println("Done");
    Serial.println("Start prog");
}
void loop()
{
    Serial.print("List=");
    Serial.print(TaskList.size());
    while(TaskList.size()>0){
        CsC *c=TaskList.shift();
        long timeout=millis()+10000;
        //long timeout=millis()+((long)(c->PerS*1000.0));
        while(millis()<timeout){
            //To indicate it is running, and to save time, I have used a delay here
            digitalWrite(13,HIGH);
            delay(250);
            digitalWrite(13,LOW);
            delay(250);
        }
        c->FunctionToCall();
    }
    Serial.print(".");
    Serial.println("complete");
    while(1){}
}

Have you considered allocating memory for c?

I thought in c++ i did not have to allocate memory.  If I did allocate memory beforehand, how would I do it?

With the new operator. And you deallocate it with the delete operator.

My mistake, I will try tonight

One possible error is a memory leak as you did not allocate the memory to the class
Try
CsC *c=new CsC();

source: Stack Exchange

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

sort: votes


text:
Formatting and code errors?
Hello I have managed to get both the Adafruit Datalogging shield walk-through and this individual code working http://www.learn.parallax.com/reed-switch-arduino-demo separately, but trying to combine the two together I get these errors. I think I have it all arranged correctly but any help would be greatly appreciated. Board Arduino Uno and Adafruit Datalogger shield.
Errors:
Temp_and_Reed_Switch_data_logging_shield.ino:55:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:58:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:61:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:66:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:70:1: error: expected unqualified-id before 'for'
Temp_and_Reed_Switch_data_logging_shield.ino:70:21: error: 'i' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:70:30: error: 'i' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:80:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:84:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:85:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:87:1: error: 'Wire' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:88:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:95:1: error: 'logfile' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:97:1: error: 'serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:98:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:104:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:105:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:107:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:108:13: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:114:1: error: expected declaration before '}' token
Multiple libraries were found for "SD.h"

 Used: C:\Users\Andrew\Documents\Arduino\libraries\SD

 Not used: C:\Program Files (x86)\Arduino\libraries\SD

'Serial' does not name a type

Program:
//  SD card datalogger
// SD card attached to SPI bus as follows:
// MOSI - pin 11
// MISO - pin 12
// CLK - pin 13
// CS - pin 10

#include "SD.h"
#include <Wire.h>
#include "RTClib.h"
#include <SPI.h>

#define LOG_INTERVAL  1000 // mills between entries
#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 4
#define greenLEDpin 5

// The analog pins that connect to the sensors

#define tempPin 1                // analog 1

RTC_DS1307 RTC; // define the Real Time Clock object
const int chipSelect = 10;
const int switchPin = 2;     //     // Reed switch to digital pin 2

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while (1);
}
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println();
  //If we set WAIT_TO_START to anything but 0, the Arduino will wait until the user types something in.
#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START
}

// initialize the SD card
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(10, OUTPUT);

// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
  Serial.println("Card failed, or not present");
  // don't do anything more:
  return;
}
Serial.println("card initialized.");

// create a new file on SD Card called Logger number
char filename[] = "LOGGER00.CSV";
for (uint8_t i = 0; i < 100; i++) {
  filename[6] = i / 10 + '0';
  filename[7] = i % 10 + '0';
  if (! SD.exists(filename)) {
    // only open a new file if it doesn't exist
    logfile = SD.open(filename, FILE_WRITE);
    break;  // leave the loop!
  }
}

if (! logfile) {
  error("couldnt create file");
}

Serial.print("Logging to: ");
Serial.println(filename);

Wire.begin();
if (!RTC.begin()) {
  logfile.println("RTC failed");
#if ECHO_TO_SERIAL
  Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
}

logfile.println("millis,time,temp,reedswitch");
#if ECHO_TO_SERIAL // attempt to write out the header to the file
serial.println("millis,time,temp,reedswitch");
if (logfile.writeError || !logfile.sync()) {
  error("write header");
#endif   //ECHO_TO_SERIAL
}

pinMode(redLEDpin, OUTPUT);
pinMode(greenLEDpin, OUTPUT);

pinMode(switchPin, INPUT);        // switchPin is an input
digitalWrite(switchPin, HIGH);    // Activate internal pullup resistor
long lastDebounce1 = 0;
long debounceDelay = 500;    // Ignore bounces under 1/2 second

// If you want to set the aref to something other than 5v
//analogReference(EXTERNAL);
}

void loop(void)
{
  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.get()); // seconds since 2000
  logfile.print(", ");
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
#if ECHO_TO_SERIAL
  Serial.print(now.get()); // seconds since 2000
  Serial.print(", ");
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
#endif //ECHO_TO_SERIAL

  delay(10);
  int tempReading = analogRead(tempPin);

  // converting that reading to voltage, for 3.3v arduino use 3.3
  float voltage = tempReading * 5.0 / 1024;
  float temperatureC = (voltage - 0.5) * 100 ;

  logfile.print(", ");
  logfile.println(temperatureC);
  logfile.print(", ");
  logfile.print(reedswitch);
#if ECHO_TO_SERIAL

  Serial.print(", ");
  Serial.println(temperatureC);
  Serial.print(", ");
  Serial.print(reedswitch);
#endif //ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);
}

Everything you have written between the end of setup() (line 55) to the start of loop() (line 117) is not in a function.
If you are struggling to combine two or more programs, start small and work your way to the full code.

Building furhter onto @CharlieHanson's answer, what you should do in order to fix this is probably following changes (please note that I wrote this in order to try to get rid of the errors, the flow of the program may still not be correct, that depends entirely on how you put together the code from the files):
1. Remove the bracket at line 52, just a few lines down in the setup()-method, below this code:
#endif //WAIT_TO_START

2. (Maybe not nessecary, but for manageability) Move this code:
long lastDebounce1 = 0;
long debounceDelay = 500;

-from where it currently is (just a few lines above the beginning of the loop()-method) to the other variable declarations (above the error()-method).

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


text:
How can I connect more sensors when my lcd is blocking pin access?
So, I have a lcd that takes up the whole board of an arduino mega. I want to connect a temperature sensor and make a really lame weather station, but the lcd screen is totally in the road. It's a shield so this is to be expected.
I've come up with wacky ideas, like soldering to the rear of the board but I think that's a bad idea. Surely there must be a better way? The lcd shield exposes no pins.

Which shield are you referring to?

Just solder some wires to the LCD shield. This way you won't "ruin" the main arduino board

What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.
They are generally available as "screw terminal" shields, such as this one from iTead:

http://www.itead.cc/mega-proto-screw-shield.html

Like this? http://www.jaycar.com.au/Kits,-Science-%26-Learning/Electronic-Project-Kits/Computer-%26-Programming/Terminal-Shield-for-Arduino/p/XC4224

@LewisCianci Yep, except that's for the Uno not the Mega, so it would only give you access to a tiny proportion of the possible pins.

I see... I've had a look online briefly and the Mega 2560 compatible screw terminal shields have to be soldered together. Is there one that comes presoldered? EDIT: Sorry just realised that your link is for the Mega. My bad. EDIT UNO MAS: Why is it that these pre-made ones have to be soldered? I have a soldering iron but I don't really like working in such tiny spaces incase i solder two pins together or something :( but if i have to, I will

Uno shields are mostly all compatible with the Mega shields. So if the LCD is compatible with Uno and Mega then using a Uno proto shield it should not be a issue.

Sandwich an arduino protoshield in between and add the sensors to this board, or add some wires, so the sensor can be places "outside".


text:
How to resolve my Timer Interrupt issue
I am trying to work with arduino timer1 interrupts to make an led blink every bit on an 8 bit number, depending on whether its a 1 or 0. However, im trying to make a basic blinking program, and it does not seem to be working.
#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=1;
}

void loop()
{
    digitalWrite(13,val);
    while(!val);
    val=0;
}

The LED doesnt blink at all! Any help would be appreceitated!
thanks!

Try this instead.
#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=!val;
}

void loop()
{
    digitalWrite(13,val);
}

I'm not surprised the LED doesn't blink - the entirety of your logic in the loop() function is so bizarre as to elicit the question:
WTF?
Let's take a look at it line by line:
digitalWrite(13,val);

Set the LED to whatever val is - val starts as 0, so the LED is off.
while(!val);

While val is not anything except 0, so while val is zero, do nothing. (The interrupt would escape you from this if your val was volatile)
val=0;

Set val to 0.
So how can val be anything except 0 when you do the digitalWrite?


text:
Interfacing ADS8319 with Arduino UNO
I am using Arduino UNO and trying to interface 2 16-bit ADS8319 ADCs with it via the SPI interface.
I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15).
I am using the following code to get the values from the ADCs.
#include <SPI.h>
#define CONVPIN 7
#define SELPIN 8
#define SELPIN2 4
#define MISOPIN 12
#define SCLKPIN 13

int adcvalue;
byte byte1; byte byte2;
const float aRefVoltage = 5;
float volts = 0;

void setup() {

  // put your setup code here, to run once:
  pinMode(SELPIN, OUTPUT); // ADC's selection pin
  pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin
  pinMode(CONVPIN, OUTPUT); // ADC's conversion pin
  pinMode(SCLKPIN, OUTPUT); // ADC's clock pin
  pinMode(MISOPIN, INPUT);  // ADC's data out
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(CONVPIN, LOW);
  digitalWrite(SELPIN, HIGH);
  digitalWrite(SELPIN2, HIGH);
  digitalWrite(CONVPIN, HIGH);
  digitalWrite(SELPIN, LOW);

  delay(1000);

  byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8
  byte2 = SPI.transfer(0x00);  //transfer (read) the second 8 bits. D7-0

  adcvalue = (byte1 <<8) | (byte2 & 0xff);  // combine the 2 bytes to make our 16 bit word
  Serial.print("Voltage Value: ");
  Serial.println(adcvalue,BIN);
  volts = (adcvalue*aRefVoltage/65535);
  Serial.print(" Sensor Volts: ");
  Serial.println(volts,5);
  delay(1000);
}

However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.
Below is the screenshot for my schematic :

Your helpful suggestions and comments would be appreciated !
Thankyou.

Thanks for the sketch, it helped writing one for ADS8830.

Can you share complete circuit diagram, i want to do work on similar project but with different ADC

After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.


text:
How is AVR Assembly in Eclipse or at Linux command line done?
I'm trying to learn AVR development in C and Assembly for the Arduino Uno (Atmel 328p microprocessor) in Linux.
I've found many good guides on how to install and setup the AVR plugin for Eclipse, and I've no problem building and uploading C code.
However there doesn't seem to be any menu options for creating an assembler project, nor can I seem to find the correct syntax for using the cli avr-as for assembling my programs into a .hex file.

In some cases you can simply feed a gcc variant with an .S file instead of a .c one and it will figure out what to do with it.  But that depends on having valid assembly files, and a compatible build setup.

If you don't mind using make, I'd recommend copying the Makefiles from ChibiOS. For me it works quite well and it's much more aligned to my daily experience with Linux.

The Arduino IDE and the arduino eclipse plugin support assembly.
Taken from the platform.txt
"{compiler.path}{compiler.c.cmd}" {compiler.S.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

compiler.S.flags is empty and so is compiler.S.extra_flags and builds.extra_flags
leaving us with something like
avr-gcc -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {includes} "{source_file}" -o "{object_file}"

Which is something I think you can handle.


text:
TMP36 probe reading 0 on analog
I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.
Here is an image of my circuit:

and my code:
int length = 5;
float airTemp = 32;

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

void loop()
{
  // loads current temperature into array
  int reading;
  float voltage;
  float temp[length];
  for (int i = 0; i < length; i++)
  {
    reading = analogRead(i);
    Serial.print(reading);
    voltage = reading * 5.0;
    voltage /= 1024;
    temp[i] = (voltage - 0.5) * 100;
  }

  // turns on/off fans based on current temperature
  for (int i = 0; i < length; i++)
  {
    pinMode(i, OUTPUT);
    if (temp[i] > airTemp)
    {
      digitalWrite(i + 8, HIGH);
    }
    else if(temp[i] <= airTemp)
    {
      digitalWrite(i + 8, LOW);
    }
  }
  delay(1000);
}

I learned how to read the temperature from here. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.

Nice example @user2985955. Did you know you can improve the precision of the analog readings by using an aref voltage? See http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ and https://123d.circuits.io/circuits/1147792-simple-temperature-sensor/

The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.
In other words, it is wired wrongly.

Thanks. I realized this just before you answered and posted some pictures to help anyone else.

Make sure your breadboard isn't one of the ones with split power rails.  If the coloured lines on the + and GND rails have a break in them you will need to bridge that break with wire.
Solid rail:

Split rail:

Right now I've only designed the circuit online in an emulator which has a solid rail. I'm pretty sure it is a programming problem on my end.

@user2985955 It would have been nice to know that little nugget before...  Have you considered that the simulator you're using doesn't work?  Try it on real hardware and then come back with your real results.

I figured it out. I had the temperature sensors wired wrong.
Old (Bad):

Good:


text:
Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller
I recently bought this linear actuator and motor controller from Pololu:

Linear actuator
Motor Controller JRK21v3

There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System
I would like to program this using PWM method because I would like to keep the Serial RX for other sensors.  From my little experiment, by using a potentiometer, I noticed this pattern:
Position: Voltage

Fully extended : 0 V
At Rest : 2.35V
Fully Retracted  : 4.77V.

For this system, I will be controlling it using a PS2 controller. So, by using only the Y_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:
//Move Linear Actuator with PS2 on JRK21v3 Controller

#define pwm 6           //red wire
#define dir 7           //yellow wire

//PS2 controller
#include <SoftwareSerial.h>
#include <Cytron_PS2Shield.h>

Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin

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

  ps2.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS);  // 0 - 255
  Serial.print("Y_axis:");
  Serial.println(Y_axis);

  analogWrite(pwm, Y_axis);
}

When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?

The Pololu jrk 21v3 motor controller supports four input modalities: via USB, via TTL-level serial, via RC / pulse width control, and via the mode you are trying to use, an analog 0-5V input.
It appears you are trying to use a PWM output to produce an analog signal control mode.  A PWM signal is a pulsed digital output rather than an analog signal.  The 21v3 may be jittering its control setpoint back and forth between 0V and 5V at a high frequency, which will make the linear actuator jitter.
Try adding an RC low-pass filter to the PWM output, ie between your PWM pin 6 and the input to the 21v3.  (Note, it might make more sense to use a software-serial output to control the 21v3, instead of using a PWM output with a low-pass filter, which may still allow use of hardware serial for your other sensors...)
To verify if an RC filter will work, try at first with large R (eg 5KΩ to 10KΩ) and large C (eg 5μF to 10μF) to see if the jitter goes away.  If so, you then can tune the filter to find how small you can make R or C and still avoid jitter.  A filter with smaller RC will allow higher-frequency control than will one with larger RC, but may be more prone to jitter.  R should be somewhat less than the input impedance of the 21v3's analog input.  To determine that value, look at the data sheet of whatever chip that input goes into.

Thanks. Yes, I agree that the motor jitters since PWM is a pulsed type signal. But how is that different from the controlling it via the serial pin RX, TX? Aren't the signals from those pins in digital form too instead of analog? That would cause the motor to jitter too right? I dont think arduino outputs analog signal, am I right?

True, most Arduino devices don't output analog signals.  (Due and Teensy, perhaps others, have some DAC outputs.)   ¶ The Pololu Jrk 21v3 has a processor on it.  When that processor receives motor speed setpoint information via USB or serial it controls an attached DC motor to that speed.  When it gets a hobby-RC pulse train it measures the duty cycle and proportionally controls an attached DC motor.    When it gets an analog voltage level it  measures the voltage and proportionally controls an attached DC motor.   When it gets PWM that you've called analog it controls speed erratically.

The jitter would not be from the frame rate of the pwm on the actiator but from the sampling effects of the driver reading a pwm signal (rather than an analog one) at uncoordinated instants in time.  Try servo pwm mode.

I got this working using the Servo library.

You set the input method to PWM.
Connect your RX on the motor controller and hook it up to the servo pin.
Connect the ground of the Arduino to the ground of the JRK 21v3.
Then use the knob servo sample by hooking up a pot to a Arduino.
The calibrate the JRK 21v3 by selecting learn.

Now you can use the actuator as a servo.


text:
Detect if a chair is occupied using Arduino with some sensors
I want to detect if a seat is occupied by a person. This is the answer that I found on Stackoverflow.
However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.

All sensors have their downsides. And will sometimes falsely trigger. You can probably detect some false triggers with additional software. e.g. a load cell that continuously gives the same value would suggest a very inactive person, or a box. Also a box tends to not be not as heavy as a person (though maybe as heavy as a little child). In the original question cost was a major factor. In your case accuracy seems to be more important. Could you maybe elaborate on what it is you need to achieve? CapSense was actually be a suggestion that came to my mind when reading your title.

I guess that CapSense-Library is not applicable in my case. - why not? How about a heat sensor anyway? If the person is not wearing really thick clothing their rear end will tend to warm the chair (and the sensor). However it might take a while to cool down afterwards.

As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.
Sensing the presence of something is actually twofold.  First you need to know if there is something there, and secondly you need to try and identify what it is that's there and if it fits your criteria.
With passive sensors of the type used by Arduinos it all comes down to a matter of probability.
If you have force sensors, you know when something is there, but you can't work out what is there, only that it weighs a certain amount.
Using capacitative sensors you can get an idea about what the something is made of - how much does it affect the capacitance, etc.
Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.
So combining them all together you can work out the likelihood that it is a human if:

It weighs enough to be a human
It has a suitable dielectric response to be a human
It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.
So it's all a case of improving that probability by adding more sensors of different types, until you are almost certain that it is a human.  You will never be 100% certain, of course.

I've also been trying to figure out a suitable idea for the same question.

Image processing would be so accurate in this but there are some problems with this approach, since there is a lot of code work and in case we want to implement this system in restaurant people might not agree.
Pressure sensors would work better for the  idea but there are some issues with this approach also. Just as mentioned in the question if there is some kind of a weight in the chair there will be an issue. also there are several chairs for a table in case of a restaurant so if we need to know whether the table is empty or not we will have to check whether all the seats are empty or not. In this case we need to pair the chair to the table using some method. we can also take this approach assuming that the chairs of the table will never change i.e. the same set of chairs remain for the same table.

The best approach for this particular scenario would be the sensors being in the table, or having a set of sensors such as a pressure sensor, thermal sensor, IR and verifying the seat is occupied.

Also there will be an issue if a device is connected to the chair since it needs power to work, once it the battery is drained you will have to charge it too


text:
Gain on a receiver
I'm doing a project on the arduino with simple 433MHz antenna modules. And I was wondering if someone could offer clarifications on how receivers work.
I read that high gain receivers can pick up a very narrow beam of radio power and thus, can transfer data at high rates. Given that this signal is tightly focused to the transmitting end.
And a low gain receiver can pick up a much wider beam of radio power.
My question is the following. When they say "narrower beam" does that represent the amplitude of the signal or the number of different waves that are being transmitted? OR does it refer to the number of DIFFERENT frequencies it can pick up? Sorry, if my question is confusing. Happy to clarify any part of it.
My Source: http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html

Think of the receiver as a camera with a telephoto lens.
With the lens zoomed out you can see a large area.  You get visual information from all over.
With the lens zoomed in you can only see a very small area. The visual information you receive is only from a very small field of vision and things outside that field never get to you.
It's exactly the same with radio waves except that the shape of the antenna affects the zoom instead of lenses.

Oh ok, that makes more sense. So just to clarify, with a low gain receiver then, it can pick up many different frequencies from all directions while HGAs do the opposite right?

Low gain is zoomed out. It can receive from many directions. High gain is zoomed in, and receives from less directions. Both are tuned to a specific range of frequencies. Eg a satellite dish is high gain but a car aerial is low gain.


text:
GPS coordinates
how do I compare coordinates I receive from the GPS module with the coordinates that I had hardcoded into the arduino, for example:
if (GPS reading <= hardcoded)
   movecarforward();
else
   movecarback();
the coordinates I get keep going up and down which makes it difficult for me to compare and excute the function below.Please help.....

You could check out the codes for this reverse geocaching project at https://learn.adafruit.com/reverse-geocache-engagement-box/software or the dog collar project at https://learn.adafruit.com/gps-dog-collar to get some help. For my GPS project I just wanted to display the distance and speed, so all I had to do was save the current location, subtract it from the previous location and add it to distanceTraveled. It'd be helpful if you could share your code here.


text:
Read function in Software Serial
I have a question regarding how the read function works in Software Serial.
recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte.
For instance:
int x = rx.read(); //if the read is supposed to read 60, x prints 111100
int x = rx.read(); //if the read is supposed to read 226, x prints 11100010
How come the first statement doesn't print 00111100?
Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.

For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.

I understand they can be omitted, but does the variable just do that for me?

No it is the print that does it. An int is 16 bits and that is set in stone.

OO that makes sense. So int returns the whole byte, but print discards leading 0s. Gotchya, thanks.


text:
Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python
I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in my earlier post. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.
The accelerometer data is stored in arrays of xArray[k] for the x-coordinate values, yArray[k] for the y-coordinate values and zArray[k] for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

I hope this is helpful to you.
First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.
Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20
Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.
This is what I did in Matlab. YPR = Yaw, Pitch, Roll
data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

Then you have to set up the plot and force matlab to update the plot in real time.
%set() is used to set graphic object properties
       set(plotGraph1,'XData',time,'YData',Y,'color','r');
       set(plotGraph2,'XData',time,'YData',P,'color','g');
       set(plotGraph3,'XData',time,'YData',R,'color','b');
       drawnow;           %force matlab to updata plot instantaneously

The link below is a good place for you to get going. But you need to make some modifications to it though.
https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/

Thanks @goddar..will have a look and tell you how it turned out. Cheers

So @goddar ..I tried out the matlab code but I couldn't get it working properly, I mucked around with that of python , could only get it reading out values rather slowly and with the unbuffered data sketch in my first post http://arduino.stackexchange.com/questions/17206/pushing-accelerometer-data-in-packets-from-an-arduino-due-to-the-pc-and-unto-pro?lq=1 but when I tried it with the buffered data  sketch it froze.....the data couldn't even read out but there were no errors on the stacktrace. Below is the python sketch

Sorry for the late reply. I did some work on this mainly on Matlab and Im not that familiar with python. In the matlab you have to make sure that you set matching COM port and baud rate. You can use Test and Measurement Tool toolbox to check whether connection is made between your device and the computer. Once connected, you should first try to read the data continuously without plotting it yet. Once you can get there, just follow the link that I provide above. You need to do some modifications to it.

In Matlab, set InputBufferSize to 50000 and set ReadAsyncMode to 'continuous'.

 import serial #import Serial Library
 import numpy  # Import numpy
 import matplotlib.pyplot as plt #import matplotlib library
 from drawnow import *

 accelX = []
 accelY = []
 accelZ = []

arduinoData = serial.Serial('COM4', 115200)
plt.ion()    #Tell matplotlib you want interactive mode to plot live data
cnt = 0
def makeFig():         #Create a function that makes our desired plot
#plt.ylim(0,1000)                #Set the limit on the y axis
plt.title('Sensor data')         #Set the title
plt.grid(True)                   #Set The grid
plt.ylabel('Axis Acceleration')  #Label the y axis
plt.plot(accelX,'ro-', label='Raw X Acceleration') #Set the line plot
plt.ylim(0, 1000)
plt.legend(loc = 'upper left')
plt2 = plt.twinx()  #Create a new object of plt2
plt2.plot(accelY, 'b^-', label='Raw Y Acceleration')
#plt2.ylim(0,1000)
plt2.legend(loc='center right')
plt2.ticklabel_format(useOffset=False) #Compel matplotlib not to autoscale
#plt3 = plt.twinx()
plt.plot(accelZ, 'go-', label='Raw Z Acceleration')
plt.legend(loc='upper right')
plt.ylim(0,1000)

 while True: #While loop that loops forever
   while(arduinoData.inWaiting() == 0):   #Wait here until there is data
    pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from serial
dataArray = arduinoString.strip().strip('\n')  #Split into an array
# Ensure that you are not working on empty line
if arduinoString:
    dataArray = arduinoString.split(",")
# Ensure that index is not out of range
if len(dataArray) > 1:
    xAxis = int(dataArray[0]) #Convert first element to int insert in xAxis
    yAxis = int(dataArray[1]) #Convert second element to int insert in yAxis
    zAxis = int(dataArray[2]) #Convert third element to int insert in zAxis
    print xAxis, ",", yAxis, ",", zAxis
    accelX.append(xAxis)   #Build our x axis array by appending to accelX
    accelY.append(yAxis)   #Build our y axis array by appending to accelY
    accelZ.append(zAxis)   #Build our z axis array by appending to accelZ
    drawnow(makeFig)       #Call drawnow to update our live graph
    plt.pause(.0000001)
    cnt=cnt+1
    if(cnt>50):
        accelX.pop(0)
        accelY.pop(0)
        accelZ.pop(0)

Hi all, so after tweaking that sketch, it did generate the graph for the buffered data but it's still rather slow but it works..If anyone has an idea that could make it plot the graph faster please do help out. Thanks

MATLAB has a free add-on for connecting to Arduino hardware.


text:
Errors when deploying Simulink model to Arduino Due
I am trying to connect an Arduino Due to Simulink to run it in external mode. I am unable to successfully deploy to hardware.
I'm testing it with a blinking light model: A pulse generator connected to a digital output pin. This is the error message:
  ### Starting build procedure for model: due_blink
   Code Generation  1
  Elapsed: 8 sec
  ### Generating code into build folder: C:\Users\Dana\Documents\MATLAB\due_blink_ert_rtw
  ### Invoking Target Language Compiler on due_blink.rtw
  ### Using System Target File: C:\Program Files\MATLAB\R2015b\rtw\c\ert\ert.tlc
  ### Loading TLC function libraries
  ### Initial pass through model to cache user defined code
  ### Caching model source code
  ### Writing header file due_blink.h
  ### Writing header file due_blink_types.h
  .
  ### Writing header file rtwtypes.h
  ### Writing source file due_blink.c
  ### Writing header file due_blink_private.h
  ### Writing source file due_blink_data.c
  ### Writing header file rtmodel.h
  .
  ### Writing source file ert_main.c
  ### TLC code generation complete.
  ### Evaluating PostCodeGenCommand specified in the model
  ### Using toolchain: Arduino ARM v1.6.1 | gmake (64-bit Windows)
  ### 'C:\Users\Dana\Documents\MATLAB\due_blink_ert_rtw\due_blink.mk' is up to date
  ### Building 'due_blink': C:\PROGRA~1\MATLAB\R2015b\bin\win64\gmake -f due_blink.mk all
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-gcc -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "due_blink.o" "due_blink.c"
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-gcc -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "due_blink_data.o" "due_blink_data.c"
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/arm-none-eabi-g++ -fno-threadsafe-statics -fno-rtti -fno-exceptions -Os -c -w -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -Dprintf=iprintf -DARDUINO=161  -MD -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER='"Unknown"' -DUSB_PRODUCT='"Arduino Due"' -D_RUNONTARGETHARDWARE_BUILD_ -D_ROTH_DUE_ -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -D__MW_TARGET_USE_HARDWARE_RESOURCES_H__ -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMW_TIMERID=9 -DMW_TIMERCOUNT=131250 -DMW_SAM_CLOCKID=TC_CMR_TCCLKS_TIMER_CLOCK3 -D_RTT_BAUDRATE_SERIAL0_=9600 -D_RTT_BAUDRATE_SERIAL1_=9600 -D_RTT_BAUDRATE_SERIAL2_=9600 -D_RTT_BAUDRATE_SERIAL3_=9600 -D_RTT_ANALOG_REF_=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMAT_FILE=0 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=0 -DEXIT_FAILURE=1 -DEXTMODE_DISABLEPRINTF -DEXTMODE_DISABLETESTING -DEXTMODE_DISABLE_ARGS_PROCESSING=1 -DRT -DSTACK_SIZE=64 -DMODEL=due_blink -DNUMST=1 -DNCSTATES=0 -DHAVESTDIO -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/include -IC:/MATLAB/SupportPackages/R2015b/arduinobase/toolbox/target/supportpackages/arduinobase/blocks/sfcn/include -IC:/Users/Dana/Documents/MATLAB/due_blink_ert_rtw -IC:/Users/Dana/Documents/MATLAB -IC:/PROGRA~1/MATLAB/R2015b/extern/include -IC:/PROGRA~1/MATLAB/R2015b/simulink/include -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/src/ext_mode/common -IC:/PROGRA~1/MATLAB/R2015b/rtw/c/ert -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/libsam -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/CMSIS/Include -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/system/CMSIS/Device/ATMEL -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino -IC:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/variants/arduino_due_x -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../include -IC:/MATLAB/SupportPackages/R2015b/arduino/toolbox/target/supportpackages/arduinotarget/registry/../scheduler/include -o "USBCore.o" "C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp"
  <command-line>:0:13: error: initializer fails to determine size of 'STRING_PRODUCT'
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp:69:34: note: in expansion of macro 'USB_PRODUCT'
   const uint8_t STRING_PRODUCT[] = USB_PRODUCT;
                                    ^
  <command-line>:0:13: error: array must be initialized with a brace-enclosed initializer
  C:/MATLAB/SupportPackages/R2015b/arduino-1.6.1/hardware/arduino/sam/cores/arduino/USB/USBCore.cpp:69:34: note: in expansion of macro 'USB_PRODUCT'
   const uint8_t STRING_PRODUCT[] = USB_PRODUCT;
                                    ^
  gmake: *** [USBCore.o] Error 1
  ### Build procedure for model: 'due_blink' aborted due to an error.
  Error(s) encountered while building "due_blink":
  ### Failed to generate all binary outputs.
  Component: Simulink | Category: Model error

I have the Arduino Due board selected in the settings, with the correct COM port. When running the same model with an Arduino Uno, ld.exe crashes with exit status 255.
I can connect to the board in the Matlab command window and manually change the pins to HIGH or LOW, so it must be a problem with Simulink.
Any help would be appreciated.


text:
How to extract number from a string?
Using LabVIEW I am sending string of data through Xbee like,

u123
r64
r89
u34
r179

And my arduino is receiving this data.
I want my arduino to read this data as a string
and I want to extract numbers from these strings and feed it into two different servos.
For example from u123 I want to extract 123 and feed it to servo1 and from r64 I want to extract 64 and feed it to servo2 and so on.
Arduino IDE Serial Monitor is showing nothing but Arduino's Xbee is receiving and sending data. Don't know why :(

It's not clear what you're asking. Is "Arduino IDE Serial Monitor is showing nothing..." an additional question or did my answer not address your question? What are you expecting to happen? What did you try to accomplish that? What happened instead?

First collect all of the characters up to the new-line (`\n' or line-feed) into an array of characters, and put a zero byte after the last one.
Since It looks like all of the strings you need to parse consist of one a single letter followed by the value you want, value = atoi(inputArray[1]; will return the value as a 16-bit int. If it could be larger than 32767 but less than 65536 (probably not if you're driving a servo with it), then cast the value to unsigned.
If there might be an unknown number of characters (non-digits) preceeding the value, the C function size_t strcspn(const char *string, const char *cset) will return the length of the leading sub-string of string that does not contain characters in cset. So value = atoi(inputArray[strcspn(inputArray, "0123456789")]); will do the same thing, but calculating the array index of the first digit in the string.
(For completeness, note there is a companion function, size_t strspn(const char *str, const char *cset);, that returns the leading sub-string of 'string' consisting only of characters in cset).


text:
Why can't I print this text to LCD?
I've been working on this for 4+ hours, and have gotten nowhere.
I have an array of weather conditions, and a number is sent over serial port to indicate which member of the array to print to the LCD.
I'm guessing the problem is in how I'm defining the array. These are my current 2 guesses for how to define it:
String weatherConditions[49] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

or:
char weatherConditions[49][16] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

I've tried many other ways of defining the array (including "char* weatherConditions"), but I'm sure most of them were just ignorant guesses.
Later in the code I have this to display a member of the array:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(weatherTodayHigh);lcd.print("/");lcd.print(weatherTodayLow);lcd.print(" ");lcd.print(weatherConditions[weatherCurrentConditionsCode]);
lcd.setCursor(0, 1);
lcd.print(weatherTomorrowHigh);lcd.print("/");lcd.print(weatherTomorrowLow);lcd.print(" ");lcd.print(weatherConditions[weatherTomorrowConditionsCode);
break;

Everything I try ends up causing nothing to be printed on the 1602 LCD display (I have 15 other scrollable "screens" that are displaying just fine on the LCD). The earlier text on this screen (the highs and lows for today and tomorrow) is displaying fine, but after that, where the weather condition text is supposed to be shown, there is nothing.
I'm able to easily display the same weather condition text on the serial monitor (for that I was using "String weatherConditions[49] = {..." and then "Serial.println(weatherConditions[currentValue]);").
How can I get members of a text array to be printed on the LCD?

Sounds like you're out of SRAM.

That's very possible. I'm so glad you mentioned it. The IDE was giving me warnings about low RAM whenever I uploaded. I've never seen that before. I'll take a closer look at it tomorrow.

Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.

Try using const char weatherConditions[49][16] or PROGMEM. Those might be more convenient than using EEPROM.

Does const char not use SRAM? I thought I read that it does? I was deciding between PROGMEM and EEPROM (both of which I'm not fluent with), and I happened to find a nice short EEPROM code for storing and reading strings. It ended up to be way easier than I would've thought, so i stuck with that. Maybe I'll post the code in my answer because it might be helpful for others who stumble upon this question.

Adding const doesn't seem to do anything in this case (I think it doesn't optimize when used on arrays). The only downside with EEPROM is, you have to fill the EEPROM with your data before uploading your main program. But use whatever is easiest for you. Best of luck


text:
How much voltage/current do I need for multiple chips?
I have a Huzzah ESP826 Wifi breakout chip which requires 3.3V power voltage and peaks at 500mA of current, and an LED strip which requires 12V and 1A.  How can I power both with one dc jack (I have a 12V 5A power supply) on one breadboard?

You need a voltage regulator for the esp. Preferably a dc-dc step down, which will neither waste power nor heat up. Other, passive solutions are possible but not desirable. The regulator can be found on ebay amazon etc.
EDIT:
One more thing about the LEDs: depending on the model you have, they might or might not work with 3.3V input (I'm assuming you want to drive the LEDs from the esp).
In case they take only 12V input, you will need some interface solution, like this one, for example.


text:
Synchronization and Implementing hamming code on Software Serial
I want to learn and use Hamming Code. Would it be wise to
alter the Software serial library to do this or just change the data being
transmitted in the actual Arduino sketch?
Also, for means of better synchronization, what would be the best method with regards to these tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here?
EDIT
For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem?

Could look something like this:
class HammingStream : public Stream {
public:
  HammingStream(Stream& ios) : m_ios(ios) {}
  virtual size_t write(uint8_t byte);
  virtual int read();
  virtual int available();
  virtual void flush();
protected:
  Stream& m_ios;
  uint8_t encode4(uint8_t nibble);
  uint8_t decode8(uint8_t code);
};

size_t HammingStream::write(uint8_t byte)
{
   m_ios.write(encode4(byte >> 4));
   m_ios.write(encode4(byte & 0xf));
   return (1);
}

int HammingStream::read()
{
  if (available() == 0) return (-1);
  uint8_t nibble = decode8(m_ios.read());
  return ((nibble << 4) | decode8(m_ios.read());
}

int HammingStream::available()
{
  return (m_ios.available() / 2);
}

void HammingStream::flush()
{
  m_ios.flush();
}

Then you could:
HammingStream HammingSerial(SoftwareSerial);
HammingSerial.println(F("hello world"));

The above leaves out the encoding/decoding but also error detection. Hamming decoding can capture up to two bit errors and do one bit correction (on 4-bit data).
An example of implementation of the coder may be found in Cosa. Here Hamming(8, 4) is used to improve VirtualWire performance. Please note that the coder table is adjusted for RF and avoiding DC signal (i.e. long periods of zero or one).
Cheers!

You can use this info and code: Hamming(8,4) with Arduino.
There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.
You can use any class that derives from Stream (like Serial or SoftwareSerial).
Edit: If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:
Tx:
#include <hamming.h>

Hamming hamming(&Serial);
char message[] = "Hello World!!";

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

void loop()
{
  hamming.write(message);
  delay(1000);
}

Rx:
#include <hamming.h>

Hamming hamming(&Serial);
char message[Hamming::SIZE];

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

void loop()
{
  if(hamming.isMessageReady())
  {
    hamming.read(message);
    Serial.println(message);
  }
}

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".
P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.

This is a good link. However, in the case of future link death, it would be good if you could edit your answer to include a summary of the info and the salient part of the code required.

The SoftwareSerial can only transmit and receive EIA-232 formatted packets.  That is what it is written to do, and that is what it does.
It cannot transfer any other format.
If you want to use other encoding techniques you will have to use a different method than SoftwareSerial.
That might involve writing your own bit-banging routines in your sketch or in your own library, or using SoftwareSerial as a basis to adapt into your own library.
Note that the SoftwareSerial library is written in such a way that EIA-232 packets are a requirement - the falling edge of the start bit triggers reception of one packet - any other encoding that doesn't have that kind of start bit arrangement would require some completely different method of arranging the reception.

So I could just make a simple function inside my sketch, that when I transmit a number, it automatically reorganizes the data chunk with parity bits in it. And then transmits this new data as if it's just the payload. And then I can have the receiver sketch pick up this received data, and process it in another function inside the sketch right? Or would this not be a smart thing to do?

I'd much rather just make my own library. But would this library just restructure the data and call SoftwareSerial's write function(essentially the same thing as what i explained above)? Or would I have to completely rework the write function all together?

Hello, is there any advice you can give me about my EDIT. Also, would it not be wise to not implement use any NRZ coding on Arduino? @Majenko

authors: ნიკო ნარიმანიძე


text:
Please explain this OneWire communication with Arduino Uno and DS2502-E48
The goal is to read the MAC address from a DS2502-E48 chip.
I think I accomplished this goal too with the following code, but I can't get behind at how this works.
I had a similar program with a PIC chip as reference.
I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses.
Where'd I normally attain the information so that I know I have to write: cc ,f0 , 0, 10 , read a random byte, and then I'm at the right position for MAC.
#include <OneWire.h>

OneWire ds(2);
void setup()
{
  Serial.begin(9600);

  byte i;
  byte dataLength;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
    Serial.print("No more addresses.\n");
    ds.reset_search();
    delay(250);
    return;
  }

  ds.reset();
  ds.select(addr);

  delay(1000);     // maybe 750ms is enough, maybe not

  present = ds.reset();
  if (present != 1 )
  {
    Serial.println("No device present, exiting...");
    return;
  }

    ds.write(0xCC);//SKIP_ROM
    ds.write(0xF0);//READ_MEMORY
    ds.write(0);  // ?
    ds.write(10); // ?
    ds.read();    // ?
    dataLength = ds.read();

    for ( i = 0; i < dataLength; i++) {
    data[i] = ds.read();
    if ( i>3){
      Serial.print(data[i], HEX);
      Serial.print(" ");
    }
  }
}

void loop()
{

}

From the DS2502 datasheet:

Skip ROM [CCh]
This command can save time in a single-drop bus system by allowing the bus master to access the
  memory functions without providing the 64-bit ROM code. If more than one slave is present on the bus
  and a read command is issued following the Skip ROM command, data collision will occur on the bus as
  multiple slaves transmit simultaneously (open drain pulldowns will produce a wired-AND result).
READ MEMORY [F0h]
The Read Memory command is used to read data from the 1024-bit EPROM data field. The bus master
  follows the command byte with a 2-byte address (TA1=(T7:T0), TA2=(T15:T8)) that indicates a starting
  byte location within the data field. An 8-bit CRC of the command byte and address bytes is computed by
  the DS2502 and read back by the bus master to confirm that the correct command word and starting
  address were received. If the CRC read by the bus master is incorrect, a reset pulse must be issued and the
  entire sequence must be repeated. If the CRC received by the bus master is correct, the bus master issues
  read time slots and receives data from the DS2502 starting at the initial address and continuing until the
  end of the 1024-bit data field is reached or until a reset pulse is issued. If reading occurs through the end
  of memory space, the bus master may issue eight additional read time slots and the DS2502 will respond
  with a 8-bit CRC of all data bytes read from the initial starting byte through the last byte of memory.
  After the CRC is received by the bus master, any subsequent read time slots will appear as logical 1s until
  a reset pulse is issued. Any reads ended by a reset pulse prior to reaching the end of memory will not have
  the 8-bit CRC available.

So you are telling it that you want to read the memory from whatever device is on the bus, not any one specific one (since you are not needing to provide the ROM ID to identify the exat item on the bus), starting from address ((0 << 8) |10) = 10.
From the DS2502-E48 datasheet you can see the layout of the memory:

The data record starts with a length byte (0Ah) and the 4-byte UniqueWare Project ID 00001129h. The
  next 6 bytes contain the 48-bit node address which consists of an incrementing 24-bit extension identifier
  and the IEEE-assigned 24-bit company ID value 006035h. An inverted 16-bit CRC ends the data record.
  The remaining bytes of the 32-byte memory page remain unprogrammed. Neither the 24-bit extension
  identifier nor the 24-bit company ID are related to the 64-bit ROM registration number. The ROM
  registration number is used to provide a unique address to access the DS2502-E48 when multidropped on
  a 1-Wire bus.

So translating that into something more pictorial:
// Length byte
0x00: 0x0A

// UniqueWare PID
0x01: 0x00
0x02: 0x00
0x03: 0x11
0x04: 0x29

// Serialization ("extension") number
0x05: 0x??
0x06: 0x??
0x07: 0x??

// Company ID Value
0x08: 0x??
0x09: 0x??
0x0A: 0x??

// 16-bit CRC
0x0B: 0x??
0x0C: 0x??

// All the rest is EEPROM data
0x0D - 0x7F: 0x??

So by starting at address 10 (0x0A) you are reading the last byte of the company ID, the CRC, and then whatever else is in the memory after that.
To read the entire MAC address (least significant byte first) you should be starting to read at address 5.

I found a nice writeup on this on a blog.  To quote his experimental findings:

Comparing to the OneWire spec, we can tell it’s writing 0xCC, which
  should be SKIP_ROM. Following that is 0xF0 (ReadMem), and two bytes
  starting address: 0x08, 0x00.

Based on this, the zero and 10 that you are writing are apparently an address value.


text:
Using L298N to control DC Motor
I am developing a system where I want to control the direction of the DC motor (12V) from Arduino Mega/Uno. For that, I am using L298N H-bridge chip without the board as shown below.
My question is, do I need to add extra hardware or is it enough on its own?
Thanks in advance!

Did you already read the L298 datasheet?

In theory, this particular device should work on its own.  However you should search for and read the datasheet for it. (I'll leave you to do that yourself, just to make sure you really do read it.)
You should consider a heatsink too by the way, and provision for things like a fuse on the power, and whether you will be using a separate 5V for the logic (again you need the datasheet for that).


text:
C++ Namespace/scope problem when trying to attach arduino interrupt
I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:
error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'
This is the cpp file:
#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;

RpmDriver::RpmDriver(int Pins[])
{
    pin=Pins[0];
    currentRpm=0;
    pinMode(pin,INPUT);
    lastMillis = millis();
    attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}

bool RpmDriver::GetData(char* dest,char* format)
{
    sprintf(dest,format,currentRpm);
}

void RpmDriver::RPMInt()
{
    double RPMConstant=40000;
    unsigned long newMillis=millis();
    unsigned long t = newMillis-lastMillis;
    t=100;//temp
    currentRpm=(t==0)?0:(int)RPMConstant/t;
    lastMillis=newMillis;
}

and the header file is
#pragma once
class RpmDriver
{
public:
    RpmDriver(int pins[]);
    ~RpmDriver(void);
    bool GetData(char*,char*);
private:
    void RPMInt(void);
};

Any help much appreciated!

See my post Calling an ISR from a class

You can't.
Simply because a class member is not the right format of function for attachInterrupt.
You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class.  How you arrange it so that it knows where your objects are is up to you.

If you have only one object then assign it to a global pointer in your library using the constructor
If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.

You should qualify RpmDriver::RPMInt() as static.
Static member functions are very much like plain functions, only using
their class as a sort of namespace. Obviously, you will not be able to
access any member data, but this should not be a problem as it seems
your class is not storing any data anyway.


text:
Comunication between Android and Arduino
I am trying send data from an Arduino to an android device with bluetooth.
I want to send a date y and when it arrives, turn on a led, but when I send the data nothing happened.
This is my code for Arduino (I use the bluetooth module hc-05)

char entrada;
void setup()
{
pinMode(8,OUTPUT);
Serial.begin(9600);
digitalWrite(8,LOW);
}
void loop()
{
   if(Serial.available()>0)
{
 entrada=Serial.read();
 if(entrada=='1')
 {
    digitalWrite(8,LOW);
    Serial.println("1");
  }
 }

And in the side of android i have this codec with my handler and thread for inputstream and outputstream
public void run()
    {
        byte[] espera=new byte [256];
        int esperaalmacen;
        while (true) {
            try {
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera).sendToTarget();
            }catch (IOException e){}
        }

And in my activity main I have:
       @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
        }
    }

My modulo I have configured as slave.

What is pin 8 doing? And why is it set to LOW two times but never set HIGH?

have you tried establishing a master-slave setup using I2C?

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


text:
Adding more storage to microprocessor 3.3v trinket
Project:
I'm a software guy trying to learn more about hardware so I've decided to do a project that uses a small micro controller which plays short sound clips over a .5w speaker.
The microcontroller I've selected is Adafruits 3v Pro Trinket along with their 2.5w mono amplifier. The microcontroller however does not have much storage that I could put sound clips on. I'm considering buying a micro sd card breakout board but I'm not sure if this would work (or how to even wire it to the microcontroller). I don't necessarily need to be able to remove the storage and I only need ~16mb so does anyone have suggestions on other chips I could get in place of using an SD Card? I've been searching on Adafruit but haven't been able to find anything.
Rational:
I would love to use a larger micro controller with a build in sd card slot but I need to be able to stick this inside a 1.5" diameter tube, so space is tight and hence the small micro controller.
Links to parts:

Microcontroller: https://www.adafruit.com/products/2010
Amp: https://www.adafruit.com/products/2130
Speaker: https://www.adafruit.com/products/1890
SD Breakout: https://www.adafruit.com/products/254

16 megabits or 16 megabytes? The price difference is not trivial.

Honestly, SD is the easiest interconnect your going to get for memory of any substantial size.   The board you linked is small, and since it's made for arduino, there's going to be some library somewhere along with documentation on how to do it.   Personally, I think you've found the right solution.


text:
Particle-like wifi configuration
Can anybody tell me how the Particle (Photon/Core) WiFi setup works?
I am looking to mimic this WiFi configuration format for my own device.
The basic steps are as follows:

Power device on; put in "listening mode" if not already active;
Connect smartphone to the wireless network that you want to connect your device to;
Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";
Enter wireless password;
Wait for device to be discovered by the App; device is now connected to WiFi.

How is the information (SSID, password) transferred from the smartphone to the device?
Thanks in advance.

Are you on about WPS?

What does this have to do with Arduinos?

@NickGammon It has as much to do with Arduinos as the Intel Edison, Galileo and the Teensy range. Those are welcome here, should the Particle/Spark system not be too?

Oh well, what is the question here? Any idea how does particle (photon/core) wifi works - that's too broad then.

I've edited the question so that it asks about the wireless setup, which I think is a valid and non-broad question. I'd also like to know the answer!

The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : SimpleLink.
The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.
I've found on the George Howkins Depletion Region blog  multiple articles that explain how the CC3000 SimpleLink works.

CC3000 Smart Config - transmitting SSID and keyphrase
CC3000 advertises presence on network via DNS-SD

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config


text:
Can I access individual pixels on my 16x2 LCD display
I have a generic 16x2 LCD display connected to my Arduino.  I can use the standard LCD library to display characters, but are there way to turn on and of individual pixels?

It's possible to define custom characters for “generic 16x2 LCD displays” [ie, displays based on HD44780 or equivalent controllers], but only up to eight such characters at the same time.  See LiquidCrystal.CreateChar for details.  See page 2 and part of page 1 of the Print degree symbol ° on LCD arduino.cc thread for create-character examples that don't use the library.  Page 1 of that thread also shows a table of all the characters built into typical HD44780 controllers, some of which may perhaps meet your needs.
For pixel-by-pixel LCD control, look at graphics LCDs, eg the KS0108 or LCD12864 and similar.

I am attempting to make a bar graph, so the 'CreateChar' function is great, but I wish I had more than 8 characters (20 would be ideal.)  Still, this might be the way to go.  \Unfortunately, none of the predefined characters works well for bar graphs.

I don't see why you'd need 20 different symbols for a simple bar graph. You can only have 5 different widths (horizontal bar), or 8 different height (vertical bar). Just do a google image search to see some examples.


text:
Teensy and MS5803 sensor
I'm trying to use the MS5803 pressure sensor with a Teensy 3.2. Compiling the Sparkfun, or other, libraries, however, results in no output.
Can you provide guidance on how to modify the libraries to work with the Teensy (t3_i2c)?

Why not ask on the Teensy forum? In any case links to the sensor, the libraries, and providing your code would make your question more meaningful.


text:
Connecting two arduinos using WiFi
I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.
In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.
How can I do that with that specific WiFi modules? Thanks in advance

You could have them both communicate with the same WiFi AP, or you could set one to be in SoftAP mode and connect the other to it. The choice is yours.

@Majenko The second option looks way more attractive to me, can you share a tutorial of how to do it? Thanks.

No, I can't. I never use the modules connected to an Arduino - I program them direct.

Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware
Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en over serial connection
Step 3: write a TCP server:
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    print(payload) //This payload will be send to your arduino over soft serial
    conn:send("<h1> Hello, NodeMCU!!! </h1>")
  end)
  conn:on("sent",function(conn) conn:close() end)
end)

Step 4: write a TCP client:
suc = false;
function sendData( host, pathData )
    suc = false;
    print("GoSending!");
    -- A simple http client
    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload)
        if(string.find(payload, "200 OK")~=nil) then
            suc = true;
            print("AllDone")
        else
            suc = false;
        end
    end)
    conn:on("connection", function(c)
        print("connected");
        conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
            .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
        end)
    conn:on("disconnection", function()
        if(suc==false) then
            print("ErrorSending")
        end
    end)
    conn:on("reconnection", function() print("reconnection") end )
    conn:connect(80,host)
end

Step 5: Connect your esp boards with software serial to the arduino
Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)
Step: 7 Parse the Data on sofserial read on the second arduino
Step 8: DONE!
EDIT:
Ok more infos on step 6.
If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection.
So, this is some example code for your ardoino if you got the script from above:
SoftwareSerial wifi(3, 2); // RX, TX

//at some time in your programm
//Build up your string that will be send over serial
String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
String i2 = i1+dataToSend;
String i3 = i2 +"\");";
wifi.println(i3);

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)
More infos on step 7.
the script on top will always print all incoming data. So you just have to read serial data on wifi:
if (wifi.available())
    Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

Info: I've build this on my own... dont know if this is best practice :)

Thanks for your answer!! Can you provide some more info about steps 6 and 7? Thanks

Add edit part. Hope this will help you :)

I'll send you a link with all the code so you can check it out :)
Link of the codes of my project

ok I have made a google docs: https://docs.google.com/document/d/169xH-7LIu8VFCNlZT9u4TPeKOL4auB6sJ9U0x2Te9ZA/edit?usp=sharing
I can not test this code. If you got problems, just change the google docs and mark your part.


text:
Arduino Mega, Ubuntu, Time.h: No such file or directory
I'm using an Arduino Mega with Ubuntu 15.10.
Sadly I've got an error during compilation, that the Time.h library cannot be found. The verbose compile output shows:

/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall
-fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560
-DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105
-D__PROG_TYPES_COMPAT__
-I/usr/share/arduino/hardware/arduino/cores/arduino
-I/usr/share/arduino/hardware/arduino/variants/mega
-I/usr/share/arduino/libraries/LiquidCrystal
-I/usr/share/arduino/libraries/SPI
/tmp/build6998056390288565759.tmp/Home_Guard.cpp -o /tmp/build6998056390288565759.tmp/Home_Guard.cpp.o
**Home_Guard.ino:2:20: fatal error: Time.h: No such file or directory**
compilation terminated.

I've already tried to use "time.h" instead of "Time.h" but it doesn't help.

ok. It seems that the Ubuntu arduino package does not contain this library. The file Time.zip has to be downloaded from the authors website: http://www.pjrc.com/teensy/td_libs_Time.html and added in the Arduino GUI menue bar: Sketch -> Import Library -> Add Library

Since Time.h is a third party library that is not surprising.  NO Arduino package on ANY operating system contains Time.h since Time.h isn't written by Arduino.


text:
What is the best arduino board for a robotic arm?
In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).
So, what's the most suitable arduino board to build this arm?
I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.
My regards.

There is no Arduino that runs on 12v. To power higher voltage motors you'll have to learn about transistors. The question of which Arduino to use depends on how many input/output pins you need and the form factor. If you need lots of pins then go with the Mega or Due. If you don't need a lot of pins and size doesn't matter then go with the Uno. If you want a small size go with the Nano or Mini (these are harder to prototype with).

Thank you. I thought that mega can run on 12V. It's their (the university staff) to make or find the transistors.
We will see if UNO is suitable.
Thanks again.

@Jerry The UNO does run on 12V. It dissipates lots of power but it does run on 12V.

I'm sorry. I misunderstood the question. Doesn't it technically accept 12v power, but "runs" at 5v?

@Jerry yes, that's correct. However here I think the question is mixing power supply for the controller and power supply for the actuation. See my answer below.

This attitude that part of the problem is the staff's job, and that you will somehow select the controller in intentional ignorance of that, is going to cause untold headaches, delay, and team conflict in your project - if it doesn't ultimately cause you to abandon the effort unfinished.  You all need to sit down together, define the problem, and figure out the constrains which that imposes on each system, and the inter-relation between the decisions made for each component.

If you buy something like an Uno or a toy robot arm now, accept that you are doing it to learn about the issues (which can indeed be a good idea when you have no perspective) but be realistic that it is not necessarily going to be part of the final implementation, and be prepared to change based on what you learn.

I am voting to close this because a question like "what is the best Arduino?" is likely to have a lot of different answers, mainly opinions rather than facts. In addition, there is no real criteria for making a decision, such as size, cost, complexity of the program, and so on.

If you are hoping to drive the arm straight from the Arduino, that's not going to work.
What you should do is:

Define the maximum weight and size of the load your arm will carry.
Define expected precision and speed of the movements.
Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
Figure out size and materials of each part of the arm
Calculate the torque required at each joint (yes, you need some basic physics calculation)
Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.
You might have already answered some of those steps, then I suggest you list here your choices.
Similarly, if you are referring to some link you found (instructables, etc.) please post it.
As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).

Thank you for the answer.
Can we use something like 'arduino motor shield'?
these physics calculations is the staff job, they asked me the board and kits that can do this work.
They want something like this Robotic arm on amazon
I did not find any instructions that suitable for this project.

@HorizonDragon If the "staff" haven't specified the kind of information Igor has mentioned then you cannot do the job properly. Go back to them and ask them for more detail so you can know what kind of power is being expected.

@HorizonDragon that link you posted would be even scarier for me :-) because it relies on levers to perform combined movements, instead of having a motor at each joint. It's an approach pulled out by kits that want to stay on the cheap side and has the advantage of being lightweight. The drawback is that even if you have apparently several dofs, in practice they have mechanical constraints on which movements they can perform and are not so easy to control.

@HorizonDragon something like this [1] might be easier to deal with, albeit more expensive.  [1] http://www.ebay.com/itm/1-Set-6DOF-Aluminium-Mechanical-Robotic-Arm-Clamp-Claw-Mount-Robot-Kit-/271968122257?hash=item3f52903591:g:tCQAAOSwosFUVJ-~

Best answer is Arduino Uno because it is enough for your application.
But all Arduino are works on 5 volt or 3.3 volt.
For operating 12 volt devices use transistors or MOSFETs.

If you're going to use transistors/mosfet I would say arduino Nano plugged into a breadboard is easier to use. Or use an Arduino Uno with a motor driver board. (But I think it's better not to since they are limited in the amount of motors they can drive, and you'll be very likely driving servo's, not DC/Steppers).


text:
Playing Melody with Tone() without using delay()
Is there a method to play a Melody with Tone() without using the delay() function?
tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration;
**delay(pauseBetweenNotes);**

Yes. The same method as is used in the BlinkWithoutDelay example sketch.

As others have noted, this can be done using the same method as used in the standard 'BlinkWithoutDelay' example sketch, and combining that with a state-machine type approach. In a simple state machine you'd assume you can be in one of two states: outputting a tone, and not outputting a tone.
Applying these ideas to your code snippet above:
// BEFORE SETUP
const int tonePin = 8;
unsigned long previousMillis = 0;
const long interval = pauseBetweenNotes;
const long interval = noteDuration;
boolean outputTone = false;                // Records current state

// IN LOOP
unsigned long currentMillis = millis();

if (outputTone) {
// We are currently outputting a tone
// Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
    }
} else {
// We are currently in a pause
// Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        tone(tonePin, melody[thisNote]);
        outputTone = true;
    }
}

Adding a bit to kabdulla's great example, to be able to use a MelodyArray
// declaring variables
const int tonePin = 10;
unsigned long previousMillis = 0;
const long pauseBetweenNotes = 250;   // interval between notes (ms)
const long noteDuration = 400;        // (ms)
boolean outputTone = false;                // Records current state
const int MelodyLength = 2;
const int Melody[MelodyLength] = {880, 698};
int MelodyIndex = 0;
unsigned long currentMillis;

void setup() {
}

void loop() {
  currentMillis = millis();
  PlayMelody();
}

void PlayMelody() {
  if (outputTone) {
    // We are currently outputting a tone
    // Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
      previousMillis = currentMillis;
      noTone(tonePin);
      outputTone = false;
    }
  } else {
    // We are currently in a pause
    // Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
      previousMillis = currentMillis;
      tone(tonePin, Melody[MelodyIndex]);
      outputTone = true;
      //Update to play the next tone, next time
      MelodyIndex = MelodyIndex + 1;
      if (MelodyIndex >= MelodyLength) {
        MelodyIndex = 0;
      }
    }
  }
}

this is a minimal modification of the basic Arduino toneMelody example to a non-blocking version
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

unsigned long previousMillis = 0;
unsigned long pauseBetweenNotes;
int thisNote;

void setup() {
}

void loop() {

  // iterate over the notes of the melody:
  unsigned long currentMillis = millis();
  if (thisNote < 8 && currentMillis - previousMillis >= pauseBetweenNotes) {
    previousMillis = currentMillis;

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    pauseBetweenNotes = noteDuration * 1.30;

    thisNote++;
  }
}

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


text:
arduino serial comminucation
my vb.net app produce this result as 2d array :
01110000000111000
01110000000111000
01110000000000000
01110111000111000
01111111100111000
01110011100111000
01110011100111000
01110011100111000
01110011100111000
01110011100111000
00000000000000000
i want to send every single column to my arduino over serial port and use the column to turn on this leds :
* leds connected from pin 2 to pin 13

anyone can help me ? :(

And what have you tried so far? What part of it are you having problems with?

the problem is how to send array over serial port and recieve it in arduino  ? i've no idea how to do that :|
*i am new with arduino.

So basically everything then?  We can't help you with the VB side of things - try stackoverflow.com for that. For the Arduino side of things, this may help: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

I don't see resistors in your LED circuits.  You run the risk of damaging your Uno if you drive LEDs without series resistors to limit current.  Eg 330Ω for 10 mA, 3300Ω for 1 mA, etc.