body:
I'm hoping to get some help with this as I am unable to get the CAN to Initialize.

I have the sparkfun Can-Bus shield: https://www.sparkfun.com/products/13262

and an Arduino Leonardo board.

I'm using the following code to try to connect my 2008 Audi S6 to the Arduino board:

    #include <Canbus.h>
    #include <defaults.h>
    #include <global.h>
    #include <mcp2515.h>
    #include <mcp2515_defs.h>
    #include <Canbus.h>
    char UserInput;
    int data;
    char buffer[456];  //Data will be temporarily stored to this buffer before being written to the file

    //********************************Setup Loop*********************************//

    void setup(){
    Serial.begin(9600);
    while(!Serial);
    Serial.println("CAN-Bus Demo");

    if(Canbus.init(CANSPEED_500))  /* Initialise MCP2515 CAN controller at the  specified speed */
      {
    Serial.println("CAN Init ok");
      } else
      {
        Serial.println("Can't init CAN");
      }

      delay(1000);

    Serial.println("Please choose a menu option.");
    Serial.println("1.Speed");
    Serial.println("2.RPM");
    Serial.println("3.Throttle");
    Serial.println("4.Coolant Temperature");
    Serial.println("5.O2 Voltage");
    Serial.println("6.MAF Sensor");

    }

    //********************************Main Loop*********************************//

    void loop(){

    while(Serial.available()){
       UserInput = Serial.read();

    if (UserInput=='1'){
     data=Canbus.ecu_req(VEHICLE_SPEED, buffer);
     Serial.print("Vehicle Speed: ");
     Serial.print(data);
     Serial.println(" km/hr ");
     delay(1000);
    }
    else if (UserInput=='2'){
     data= Canbus.ecu_req(ENGINE_RPM, buffer);
     Serial.print("Engine RPM: ");
     Serial.print(data);
     Serial.println(" rpm ");
     delay(1000);

    }
    else if (UserInput=='3'){
     data= Canbus.ecu_req(THROTTLE, buffer);
     Serial.print("Throttle: ");
      Serial.print(data);
     Serial.println(" %% ");
     delay(1000);

    }
    else if (UserInput=='4'){
     data =Canbus.ecu_req(ENGINE_COOLANT_TEMP, buffer);
     Serial.print("Engine Coolant Temp: ");
     Serial.print(data);
     Serial.println(" degC");
     delay(1000);

    }
    else if (UserInput=='5'){
     data=Canbus.ecu_req(O2_VOLTAGE, buffer);
     Serial.print("O2 Voltage: ");
     Serial.print(data);
     Serial.println(" V");
     delay(1000);

    }
    else if (UserInput=='6'){
     data=Canbus.ecu_req(MAF_SENSOR, buffer);
     Serial.print("MAF Sensor: ");
     Serial.print(data);
     Serial.println(" g/s");
     delay(1000);

    }
    else
    {
      Serial.println(UserInput);
      Serial.println("Not a valid input.");
      Serial.println("Please enter a valid option.");
    }

    }
    }

Overall, I just can't get the CAN to initialize. I've looked online and just can't seem to find a solid solution. I've tried other libraries as well to no avail.

Please assist!

title: Can BUS Shield on Arduino Leonardo - Can't init CAN

Answers: 2

body:
Had this problem myself. Found this fixed it

Change the following line...

    _delay_us(10);

To...

    _delay_us(50);

In the `MCP2515.c` file in the library

body:
Increasing that delay in the MCP2515.c file also fixed this issue for me.
I am running the sparkfun Can-Bus shield on an Arduino pro-mini, and here is my serial monitor output before the change, and after:

12:56:38.580 -> CAN Read - Testing receival of CAN Bus message
12:56:39.556 -> Can't init CAN
13:01:40.992 -> CAN Read - Testing receival of CAN Bus message
13:01:42.016 -> CAN Init ok


body:
An XBee Pro S1 module sits on a DIP socket on-board a Personal Weather Station (PWS) to transmit data.
Instead of letting the station transmit data wirelessly via the XBee, I would like to read that data off the socket pins on which it sits, via an Arduino UNO.

Is this possible? If so, what should I look into?<br>
I am new to wireless communication with a µC, so any help would be appreciated.

title: Intercept Data being sent to XBee Module via UNO

Answers: 0


body:
I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze.
                   Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

title: How to switch program in arduino using android app?

Answers: 1

body:
Once I made a sketch to run multiple programs. I wrote a `setup` and `loop` function for every different "program", (e.g. `setup_p1`, `setup_p2`, ... `loop_p1`, ...) and then wrote a simple `main` sketch to handle them all.

In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.

I choose to use a callback because it's faster than just checking the mode every time, at least in my case

    // callback for loop function
    typedef void (*loopfunction)();
    loopfunction currentloop;

    void setup()
    {
      // Set dip-switch pins as input
      pinMode(MODE_PIN2,INPUT_PULLUP);
      pinMode(MODE_PIN1,INPUT_PULLUP);
      pinMode(MODE_PIN0,INPUT_PULLUP);

      // Concatenate the dip-switch values
      byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

      // choose the correct mode
      switch(mode)
      {
        case 0: // Shutdown - do nothing
                break;
        case 1: // Program 1
                setup_p1();
                currentloop = loop_p1;
                break;
        case 2: // Program 2
                setup_p2();
                currentloop = loop_p2;
                break;
        ...
      }

      // Not a valid program: halt
      if (!currentloop)
      {
        while(1);
      }
    }

    void loop()
    {
      // Execute the current loop
      currentloop();
    }


body:
I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.

    #!/usr/bin/python3
    import RPi.GPIO as GPIO
    import time

    # this many mm per bucket tip
    CALIBRATION = 0.200
    # which GPIO pin the gauge is connected to
    PIN = 17
    # file to log rainfall data in
    LOGFILE = "log.csv"

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # variable to keep track of how much rain
    rain = 0

    # the call back function for each bucket tip
    def cb(channel):
     global rain
     rain = rain + CALIBRATION

    # register the call back for pin interrupts
    GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

    # open the log file
    file = open(LOGFILE, "a")

    # display and log results
    while True:
     line = "%i, %f" % (time.time(), rain)
     print(line)
     file.write(line + "\n")
     file.flush()
     rain = 0
     time.sleep(5)

    # close the log file and exit nicely
    file.close()
    GPIO.cleanup()

title: Can anyone explain how this code can be converted to work on a Arduino Uno

Answers: 1

body:
This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes.  if there is a specific programming problem it should be addressed separately instead of handing out working code.

    const int CALIBRATION = 0.200;   //Calibration Constant
    int pin = 2;                     //Pin it's on, this is int0 for uno.
    volatile int rain = 0;           //Used in interrupt routine

    void setup() {
        Serial.begin(9600);
        pinMode(pin, INPUT);
        attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
    }

    void loop() {

         /* Output OR LOG DATA HERE
            Also You need a Time Library and RTC (Real Time CLock) the above
            code is for a raspberry pi that has all that. */

    }

    void cb() {
        rain = rain + CALIBRATION;
    }


body:
I'm a beginner using Arduino with a Teensy 3.2 board and programming it as a usb keyboard. I have two 4 button membrane switches. Their button contacts are on pins 1-8, and the 9th pin holds a soldered together wire of both membrane switches' "ground" line or whatever it's true name is; the line that completes the circuit.

Basically when you press the buttons they are supposed to simply type "a, b, c..." respectively. I've been told I need to use a matrix for this.

I'm looking for an example of how to code a keyboard matrix that effectively supports a one row/9 column line (or vice versa?) I've been unable to find that solution online.

All I have so far is this code which, when the button on the second pin is pressed, sends tons of "AAAAAAAAAAAAAAAA" keystrokes.

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(2, INPUT_PULLUP);
      Keyboard.begin();
    }

    void loop() {
      //if the button is pressed
      if(digitalRead(2)==LOW){
        //Send an ASCII 'A',
        Keyboard.write(65);
      }
    }

Would anyone be able to help?

title: Arduino keypad matrix example? ( teensyduino )

Answers: 1

body:
By your description, you don't have a matrix.  You have them wired as just 8 straight switches.

A matrix would be if you had the 4 switch pins of one keypad wired to the same switch pins of the other keypad, and the two common connections from the keypads wired to two separate IO pins.

At the moment your code is responding whenever a button is in the low state. Instead it needs to respond only when the button *transitions* from the high state to the low state.  To do that you need to know what state all the buttons were in the previous pass through loop to compare them to what they are in this pass through loop - and if any have changed then they have either been pressed or released.

You should also implement debouncing to that you don't get false presses.

If you don't want to learn how to do all that yourself I have a handy library that will do it all for you:

* https://github.com/MajenkoLibraries/DebouncedInput

If you want to convert your setup to an actual matrix to save on IO pins you want to read the Arduino Keypad tutorial:

* http://playground.arduino.cc/Main/KeypadTutorial


body: I want to make simple client-server program where arduino behave as a client. For example I have a LED connected in arduino board that is controlled by a switch. With the switch I can turn off and on the LED. Now I want to send the status of that LED to another computer wirelessly (let's say within the Local network). That computer will act as a server and update the change as soon as the LED changes its status. I am not expecting any complete code, I just want to know how could it be done in general? May be some links can help me? Because this is my first time working with client-server in arduino sketch, I need some kind of guidelines. Thank you.

title: Sending data from Arduino to the server where arduino (sketch) acts as a client

Answers: 2

body:
A simple HC-05 module will give you a wireless bluetooth connection.  They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console.  Obviously they can read data too.

    SoftwareSerial bt_serial(2, 3); // RX | TX
    bt_serial.begin(9600);

    [...]

    if (led_state != last_led_state)
    {
        if (led_state == HIGH)
            bt_serial.print("1");
        else
            bt_serial.print("0");
        last_led_state = led_state;
    }

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job.  For example, some python code:

    import serial
    import sys

    serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

    try:
        serial_port.open()
    except:
        print("Failed to open port")
        sys.exit(2)

    while (True):
        try:
            led_state = serial_port.read()
            if (led_state != 0):
                print("LED is on")
            else:
                print("LED is off")
        except:
            pass

    serial_port.close()   # yes, it never gets here

body:
Even though I like Kingsley's answer I thought I'd add to this using Wi-Fi becuase you had mentioned LAN.

These two links should be enough to help you:
[WifiChatServer][1]
and [C# Telnet Library][2]

Those links can sort of be dissected to fit your needs, but if you need some actual code just tell me.

Now I am aware that **the Arduino is acting as a server and the computer acts as a client**, but I believe this setup is better because it's easier to manipulate connecting to servers on the computer rather than on the arduino side.

  [1]: https://www.arduino.cc/en/Tutorial/WiFiChatServer
  [2]: http://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library


body:
I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.

So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?

Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.

I've tried a bunch of different things but I've come to a dead end.

EDIT:

main program:

    #include "_v0_0_0.h"
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library
    #include <SPI.h>

    #include "Point.h"
    #include "Rectangle.h"
    #include "SomeView.h"

    #define  TFT_CS  4
    #define  TFT_RST 0
    #define  TFT_DC  10

    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
    SomeView a_view;

    void setup()
    {
     tft.initR(INITR_BLACKTAB); // initializes the display
    }

    void loop()
    {
     a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
     while (true) {}
    }

SomeView.h:

 #include "Rectangle.h"

 class SomeView {
 private:
  Rectangle a_rectangle;
 public:
  SomeView();
  void draw();

  const Rectangle& getRectangle() const {
   return a_rectangle;
  }

  void setRectangle(const Rectangle& rectangle) {
   a_rectangle = rectangle;
  }
 };

SomeView.cpp:

 #include "SomeView.h"

 SomeView::SomeView() :
   a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
 }

 void SomeView::draw() {
  a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
  a_rectangle.draw();

  a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
  a_rectangle.draw();
 }

Rectangle.h:

    #include "Point.h"
 #include <Adafruit_GFX.h>    // Core graphics library
 #include <Adafruit_ST7735.h> // Hardware-specific library
 #include <SPI.h>

 class Rectangle{
 private:
  Point p1;
  Point p2;
 public:
  Rectangle();
  Rectangle(Point& p1, Point& p2);
  void setCorners(const Point& p1, const Point& p2);
  void draw();

  // ... getters and setters for the points
 };

Rectangle.cpp:

    #include "Rectangle.h"

 Rectangle::Rectangle() : p1(), p2()
  {
  }

 Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
  {
  }

 void Rectangle::setCorners(const Point& p1, const Point& p2) {
  this->p1 = p1;
  this->p2 = p2;
 }

    // this is where I want to use a function from the adafruit library
 void Rectangle::draw() {
  Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

 }

title: Is there a way to use functions defined in a library in any class?

Answers: 2

body:
Yes, there is a way.

However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.

Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.

Your PC, for example.

C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly.
From that perspective, C++ can be seen also as a superset of C, only much more complex.

Have a look at [this explanation][1], for example.
It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.

If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.

For a more systematic approach, try [this][2].

  [1]: http://karwin.blogspot.fi/2012/11/c-pointers-explained-really.html
  [2]: http://www.cplusplus.com/doc/tutorial/

body:
There are two basic methods to do what you want:

1. Inheritance
2. Pointer passing

Inheritance involves making your new class a *child* class of the Adafruit TFT class.  You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class *plus* your extra functions overlaid over the top:

    class Rectangle : public Adafruit_ST7735 {
        ...
    };

You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class *instead* of the Adafruit class in your sketch.

* Inheritance tutorial: http://www.cplusplus.com/doc/tutorial/inheritance/

That is fine if you just want one class that uses the functions from the Adafruit class.  The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time.  For instance, you might have:

    class Rectangle {
        private:
            Adafruit_ST7735 *_tft;

        public:
            Rectangle(Adafruit_ST7735 &tft) : _tft(&tft) {}
    };

Then in your function you can use:

    void Rectangle::draw() {
        _tft->drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);
    }

You would, of course, construct your class with:

    Adafruit_ST7735 myTFTScreen(blah blah blah);
    Rectangle myRect(myTFTScreen);

Then call `myRect.draw();`.


body:
In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.

     void setup() {
       Wire.begin(8);                // join i2c bus with address #8
       Wire.onReceive(receiveEvent); // register event
       Serial.begin(9600);           // start serial for output
    }

    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
       char c = Wire.read(); // receive byte as a character
       Serial.print(c);         // print the character
    }
     int x = Wire.read();    // receive byte as an integer
     Serial.println(x);
    }

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

title: What is the purpose of the howMany integer in the wire.onReceive() function from the example code?

Answers: 2

body:
It tells you how many bytes have been received, and consequently how many you can read with `Wire.read()`.

Before you have read anything with `Wire.read()` `Wire.available()` will return the same value.  As you read from the buffer `Wire.available()` will decrease, but `howMany` will stay the same.

body:
The reference page <https://www.arduino.cc/en/Reference/WireOnReceive> states:

> Parameters
>
> handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: `void myHandler(int numBytes)`

I suggest you look at the reference pages for the functions in future before asking what they do.


body: I have 2 motors connected to a dual H-Bridge motor driver and the H-bridge connected to an arduino uno, It was working fine at first but now my motors are spinning very slow and the car bearly moves, I have changed the batteries  but still moves slow and with no power, please help

title: H-Bridge L298N motor driver

Answers: 1

body:
You can try to bisect the problem.

Remove the Arduino and drive the motors with wires: replace the input for the pwm signal with a +Vcc and you will get the same as if the Arduino was outputting a PWM with 100% duty cycle.

This should allow you to diagnose if there is a problem with the driver/motors.

If that shows no problem and the wheels spin as expected, then you have some issue (either sw or electrical with the Arduino).

But at least you can halve the complexity of the problem.


body:
I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.

I'm trying to connect to a computer's power button so I can turn it on remotely.

I have found out that the relay basically does the opposite to the digital pin's output

Normally open Relay

HIGH = Open

LOW = Closed

I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.

Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.

title: Relay doing opposite to digital pin

Answers: 5

body:
You could use a less invasive way to turn on your computer: [wake on LAN][1]. In this case you only need to generate the magic packet.

It won't work in forcibly turning off the PC, but it's more generic and doesn't require HW hacking.

  [1]: https://en.wikipedia.org/wiki/Wake-on-LAN

body:
To ensure that relay doesn't switch between NO-NC when controller is *away* relay will need some memory.

Imagine having a 1 bit memory driving relay. If arduino dies/restart, its own GPIO may change, but relay's memory will remember last state and stay there, till controller instructs otherwise, granted relay circuit and its memory element don't lose power.

This also means there will be at least 2 lines required from uC to control this relay now.

I'd prefer to use some kind of serial shift register, e.g. [CD4094](http://pdf.datasheetcatalog.com/datasheet2/e/0zfy3x112ch42r82d060wl0jtocy.pdf), [CD4042](http://pdf.datasheetcatalog.com/datasheet2/9/0oqf0076icwadgde9su7g9oihq3y.pdf), [CD4099](http://pdf.datasheetcatalog.com/datasheet2/c/0ho1jgpu09kii6i650li4579diky.pdf) etc because that allows me to control more than one relays from same 2 lines on uC.

You may find some other part more suitable for your application.

body:
The relay module you have is this one from SainSmart:

* http://www.sainsmart.com/arduino/arduino-components/relays/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html

The schematic is like this:

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

As you can see you connect VCC to +5V and IN2 to your IO pin.  Setting the IO to LOW will then turn on the LED and the optocoupler together.

But that's not the only way you can connect it up.

Connect VCC to the IO pin and IN2 to GND instead.  Then you set your output HIGH to turn it on.

The arrangement shown in the schematic is commonly done because some MCUs are able to sink more current than they can source thorugh an IO pin.  That is not the case with an Arduino which has symmetric IO pins that can sink and source the same amount of current.

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

body:
I've solved the problem,
Thanks to everyone who helped.

I don't need a NOT gate anymore, here's what I added to make it work:

void setup() {

  startup();

}

void  startup() {

  digitalWrite(relay1, HIGH);

  digitalWrite(relay2, HIGH);

}

void loop() {

}

(I removed the rest of the code to keep it simple and easy to understand)

body:
Try This:

    const On  = LOW;    // For non inverted logic swap on and off.
    const Off = HIGH;
    const pump = 5;

    void setup() {
      pinMode(pump, OUTPUT);    // sets the digital pin 13 as output
    }

    digitalWrite(pump, On);
    digitalWrite(pump, Off);


body:
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! :)

title: Altering code to run a timer while checking for a data input

Answers: 4

body:
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](http://www.gammon.com.au/tips#trap13)

> 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](http://www.gammon.com.au/blink)

body:
You can find some 3rd party library that does software emulation of threads.
For example: [ArduinoThread][1].
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.

  [1]: https://github.com/ivanseidel/ArduinoThread

body:
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.

body:
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!


body:
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){}
    }

title: Problem assign float to an embed class within the Linked-list libary

Answers: 1

body:
One possible error is a memory leak as you did not allocate the memory to the class
Try

    CsC *c=new CsC();


body:
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);
    }

title: Formatting and code errors?

Answers: 2

body:
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.

body:
Building furhter onto [@CharlieHanson's answer][1], 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).

  [1]: https://arduino.stackexchange.com/a/17289/14429


body:
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.

title: How can I connect more sensors when my lcd is blocking pin access?

Answers: 2

body:
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

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


body:
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!

title: How to resolve my Timer Interrupt issue

Answers: 2

body:
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?

body:
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);
    }


body:
I am using Arduino UNO and trying to interface 2 16-bit [ADS8319](http://www.ti.com/lit/ds/symlink/ads8319.pdf) 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.

<!-- language: c -->

    #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 :

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

  [1]: https://i.stack.imgur.com/w9F3v.png
  [2]: https://i.stack.imgur.com/jb2d8.jpg

Your helpful suggestions and comments would be appreciated !
Thankyou.

title: Interfacing ADS8319 with Arduino UNO

Answers: 1

body: 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.


body:
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.

title: How is AVR Assembly in Eclipse or at Linux command line done?

Answers: 2

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

  [1]: http://ChibiOS

body:
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.


body:
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:

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

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][2]. 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.

  [1]: https://i.stack.imgur.com/TiksO.jpg
  [2]: https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor

title: TMP36 probe reading 0 on analog

Answers: 3

body:
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:

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

Split rail:

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

  [1]: https://i.stack.imgur.com/9qMjR.jpg
  [2]: https://i.stack.imgur.com/PPDh9.jpg

body:
I figured it out. I had the temperature sensors wired wrong.

Old (Bad):

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

Good:

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

  [1]: https://i.stack.imgur.com/ys4yN.jpg
  [2]: https://i.stack.imgur.com/sOWWZ.jpg

body:
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.


body:
I recently bought this linear actuator and motor controller from Pololu:

 - [Linear actuator][1]

 - [Motor Controller JRK21v3][2]

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][3]

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

1. Fully extended : 0 V
2. At Rest : 2.35V
3. 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:

<!-- language: c -->

    //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?

  [1]: https://www.pololu.com/product/2305
  [2]: https://www.pololu.com/product/1394
  [3]: http://www.pololu.com/docs/0J38/5

title: Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller

Answers: 2

body:
The [Pololu jrk 21v3](https://www.pololu.com/product/1394) 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](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=971&bih=588&q=RC+low-pass+filter&oq=RC+low-pass+filter&gs_l=img.12..0j0i30l6j0i5i30l3.963.963.0.2484.1.1.0.0.0.0.80.80.1.1.0....0...1ac..64.img..0.1.80.SfBLFQdVhSA) 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.

body:
I got this working using the [Servo library][1].

 - 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][2] 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.

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: https://www.arduino.cc/en/Tutorial/Knob


body:
I want to detect if a seat is occupied by a person. This is [the answer][1] 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.

  [1]: https://arduino.stackexchange.com/questions/1288/detect-and-stream-if-a-chair-is-occupied/1308#1308

title: Detect if a chair is occupied using Arduino with some sensors

Answers: 2

body:
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.

body:
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.


body:
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

title: Gain on a receiver

Answers: 1

body:
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.


body:
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.....

title: GPS coordinates

Answers: 1

body: 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.


body:
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.

title: Read function in Software Serial

Answers: 1

body: 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.


body:
I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in [my earlier post][1]. 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.

  [1]: https://arduino.stackexchange.com/questions/17206/pushing-accelerometer-data-in-packets-from-an-arduino-due-to-the-pc-and-unto-pro

title: Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python

Answers: 3

body:
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/][1]

  [1]: https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/

body:
     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)

body:
MATLAB has a [free add-on for connecting to Arduino hardware][1].

  [1]: http://www.mathworks.com/hardware-support/arduino-matlab.html


body:
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.

title: Errors when deploying Simulink model to Arduino Due

Answers: 0


body:
[![enter image description here][1]][1]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 :(

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

title: How to extract number from a string?

Answers: 1

body:
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`).


body:
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?

title: Why can't I print this text to LCD?

Answers: 1

body: 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.


body: 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?

title: How much voltage/current do I need for multiple chips?

Answers: 1

body:
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][1], for example.

  [1]: http://tobiscorner.floery.net/powerrgb/


body:
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][1] 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?

  [1]: http://rayshobby.net/cart/image/cache/data/acc/rf_pair-500x500.JPG

title: Synchronization and Implementing hamming code on Software Serial

Answers: 3

body:
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.

body:
You can use this info and code: [Hamming(8,4) with Arduino][1].

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).

  [1]: http://hykrion.com/arduino/hamming-8-4.html

**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.

body:
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][1] 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!

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/HammingCodec_8_4/HammingCodec_8_4.hh


body:
The goal is to read the MAC address from a [DS2502-E48 ](http://pdfserv.maximintegrated.com/en/ds/DS2502-E48.pdf)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()
    {

    }

title: Please explain this OneWire communication with Arduino Uno and DS2502-E48

Answers: 2

body:
I found a nice writeup on this on a [blog][1].  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.

  [1]: https://hclxing.wordpress.com/2014/02/09/hacking-a-dell-power-adapter-part-iii/

body:
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.


body:
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. [![L298N][1]][1]

My question is, do I need to add extra hardware or is it enough on its own?

Thanks in advance!

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

title: Using L298N to control DC Motor

Answers: 1

body:
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).


body:
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!

title: C++ Namespace/scope problem when trying to attach arduino interrupt

Answers: 2

body:
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.

body:
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.


body:
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)
<!-- language-all: lang-cpp -->

    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.

title: Comunication between Android and Arduino

Answers: 0


body:
**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

title: Adding more storage to microprocessor 3.3v trinket

Answers: 0