body:
I'm currently working on my own arduino library and I'm becoming exasperated with the following problem: I want to store data with the extended database library (https://code.google.com/p/arduino-edb/) on a sd card. I tried to follow and adapt the instructions on [this][1] page and I gave my custom library a property "File dbFile" as well as a property "EDB db". Additionally I have to pass two function pointers to the constructor of the EDB library. So my custom library got two more properties: a writer and a reader function. My class looks roughly like that:

    class myLib
    {
       public:
          myLib();
          ~myLib();
          void configWriter( unsigned long address, byte data );
          byte configReader( unsigned long address );
          File dbFile;
         EDB configDB;
    }

...so far so good. But here comes the pain in the ... When I'm trying to instantiate a new EDB object in the constructor of my class by passing two pointers to the member functions I'm constantly getting an error. Here is how I call the constructor of the EDB library:

    configDB = new EDB( &myLib::configWriter, &myLib::configReader );

I get the following error:

> no matching function for call to 'EDB::EDB()'
>
> [...] note: candidates are:
>
> note: EDB::EDB(void (*)(long unsigned int, uint8_t), uint8_t (*)(long
> unsigned int))
>      EDB(EDB_Write_Handler *, EDB_Read_Handler *);

The prototype of the EDB constructor looks like this:

> EDB(EDB_Write_Handler *, EDB_Read_Handler *);

EDB_Write_Handler and EDB_Read_Handler are defined like so:

> typedef void EDB_Write_Handler(unsigned long, const uint8_t);
> typedef uint8_t EDB_Read_Handler(unsigned long);

So I assume that my constructor call doesn't work because the functions that I'm passing are from a foreign class: (myLib::*) and not just (*)

I have no idea how to solve that problem. Does someone of you have any idea?

Thanks,
Andy

EDIT:
Here is a Minimal, Complete, and Verifiable example:

myLib.h:

    #ifndef myLib_h
    #define myLib_h

    #include "Arduino.h"
    #include <SPI.h>
    #include <SD.h>
    #include <EDB.h>

    #define SD_CS 4
    #define SD_SS 10

    class myLib
    {
      public:
        myLib();
        ~myLib();
        void begin();
        void configWriter( unsigned long address, byte data );
        byte configReader( unsigned long address );
        File dbFile;
        EDB * configDB;

    };

    #endif

myLib.cpp:

    #include "myLib.h"

    myLib::myLib( void )
    {}

    myLib::~myLib()
    {}

    void myLib::begin()
    {
      // Init SD
      pinMode(SS, OUTPUT);
      SD.begin(SD_CS);

      // Load Config
      configDB = new EDB( &myLib::configWriter, &myLib::configReader );
      dbFile = SD.open("config.db", FILE_WRITE);
    }

    void myLib::configWriter( unsigned long address, byte data )
    {
      dbFile.seek(address);
      dbFile.write(data);
      dbFile.flush();
    }

    byte myLib::configReader( unsigned long address )
    {
      dbFile.seek(address);
      return dbFile.read();
    }

Arduino sketch:

    #include <SPI.h>
    #include <SD.h>
    #include <EDB.h>
    #include "myLib.h"

    myLib* a;

    void setup()
    {
      a = new myLib();
      a->begin();
    }

    void loop()
    {
    }

  [1]: http://blog.brauingenieur.de/2014/01/20/extended-database-library-using-an-sd-card/

title: Pass a member function pointer to a method of a foreign class (EDB Lib)

Answers: 2

body:
Can you post a  [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? We don't care what the functions do, just make up an example that demonstrates the message.

---

Having said that, this looks wrong:

    class myLib
    {
       public:
          myLib();
          ~myLib();
          void configWriter( unsigned long address, byte data );
          byte configReader( unsigned long address );
          File dbFile;
          EDB configDB;
    }

> Here is how I call the constructor of the EDB library:

     configDB = new EDB( &myLib::configWriter, &myLib::configReader );

OK so myLib is a **class**, not an **instance of a class**.

> The prototype of the EDB constructor looks like this:

        EDB(EDB_Write_Handler *, EDB_Read_Handler *);

So you want an **instance** of EDB_Write_Handler.

---

Let's say that EDB needed a dog and a cat. You don't pass "dog" and "cat" you pass "Fido" and "Fluffy". They are instances of the classes.

---

You have this:

    configDB = new EDB( &myLib::configWriter, &myLib::configReader );

The constructor for EDB expects two functions:

    EDB(EDB_Write_Handler *, EDB_Read_Handler *);

These are declared like this:

    typedef void EDB_Write_Handler(unsigned long, const uint8_t);
    typedef uint8_t EDB_Read_Handler(unsigned long);

These are **static** functions, that is, they cannot be class functions. Why not? Because a class function has an implicit pointer **this** which points to this instance of the class.

So, you cannot pass a non-static class-function to the EDB constructor.

Now you can make the functions configWriter and configReader static, but then they can't access class variables (eg. dbFile) because they belong to an **instance** of the function.

I've tried fiddling around with your code, but without a clear understanding of your intentions, I can't get it to compile. Do you mean to **derive** your class from EDB?

Why do you even want a class `myLib`? Are you planning to have multiple instances of it? If so, why? If not, why make a class?

body:
The problem here is a common one with C++.  It basically boils down to how C++ handles member functions.

You define a member function as, say,

    class myLib {
        void myFunc(int val);
    };

When you call the function it's actually not defined as that - it's instead had its definition change to:

    void myFunc(myLib *this, int val);

The addition of the `myLib *this` is an *implicit* parameter, and it's how C++ keeps track of its object instances when calling different functions.

So a function which expects a parameter of `void (*func)(int)` won't accept your method because it's actually `void (*func)(myLib *, int)`.  Hence the error you are seeing.

There is no easy, clean, way around it that I have found as yet, I am afraid.  The closest you can do is to move the reader and writer functions outside of your class and store a global pointer to the actual class, something like:

    static myLib *globalLib;
    void globalConfigWriter( unsigned long address, byte data ) {
        globalLib->congigWriter(address, data);
    }
    byte globalConfigReader( unsigned long address ) {
        return globalLib->configReader(address);
    }

Then in the constructor for your lib you can do:

    myLib::myLib() {
        globalLib = this;
    }

You then register the global reader and writer functions with the EDB constructor instead of the class member functions.

It does have the rather major down-side that there can only be one instance of your class since there is only one global pointer and only one pair of reader / writer functions.  There are ways of supporting a finite number of instances, but it basically involves having a reader/writer pair for each instance and allocating one to an instance when it's constructed and de-allocating it when its destructed.  Keeping track of them and knowing which object is associated with which function pair is tricky at best...


body:
I have a problem with Servo library. This is my (very short XD) "code":

    #include <Servo.h>

    void setup() {
      Servo.attach(9, 554, 2400);
    }

    void loop() {
      Servo.write(2000);
    }

And it returns:

    Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    sketch_aug24a.ino: In function 'void setup()':
    sketch_aug24a:4: error: expected unqualified-id before '.' token
    sketch_aug24a.ino: In function 'void loop()':
    sketch_aug24a:8: error: expected unqualified-id before '.' token
    expected unqualified-id before '.' token

Like there is no included library. What can I do with it ?

title: Arduino Servo.h library returns error in compilation

Answers: 1

body:
`Servo` is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:

    #include <Servo.h>

    Servo sv;

    void setup() {
      sv.attach(9, 554, 2400);
    }

    void loop() {
      sv.write(2000);
    }

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)


body:
I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.

I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.

So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.

However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.

I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.

So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).

So my questions are:

 - Am I right that I2C will not work?

 - If I am wrong does anyone have a working end to end example?

 - If I am right is there an approved way to do ESP to ESP serial comms?

title: ESP8266 as I2C client

Answers: 3

body:
I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

> Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

> If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.

My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC

body:
The issue with the ESP8266 is that it is multitasking, and only 80% of the CPU time is available to developers. This manifests as an outage of 100-200us every 500ms or so, which rather complicates all sorts of software serial interfaces, such as I2C, SPI and UART. As a bus master the ESP8266 hides these issues as it is responsible for the bus clock, but as a bus slave it needs to halt data transfer for the duration of these random events.

A typical solution for this inter-CPU issue is to provide an external RAM cache to act as a mailbox, where each CPU will periodically check to see if any actions are outstanding and leave any requested data.

Has anyone explored this option for the Arduino to ESP8266 interface?

body:
> I am not certain, but I get the same impression as you.
> It seems that the Expressif SDK only supports master mode.

Sorry no.
Espressif SDK supports Slave Mode too.
official the Master works with 50 kHz (CPU 80MHz), and  100 kHz in technical referenz  and unofficial in my test with !1.2MHz you must switch then to the 160 MHz CPU and you must work for delays with
asm ("nop") 12.5 ns at 80MHz and 6.25 ns at 160 MHz
then you can toggle the pins at 80 MHz with 700 kHz and with 160 MHz with 1400 kHz. because there are instruction to the gpio ( toggle output low, "opendrain" clear output with pullup high ) it will be a netto rate of
620 kHz, and 1260 kHz.

[![a stable 120 kHz is done][1]][1]

best wishes
rudi ;-)

[![I2C Slave ESP8266 ][2]][2]

  [1]: https://i.stack.imgur.com/NZnJQ.png
  [2]: https://i.stack.imgur.com/BoZVs.png


body:
I got this question from my teacher the other day and I can't figure it out:

> If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

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

In short, the project includes an Arduino Uno with two ultrasonic sensors.

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

title: Two sensors on one input

Answers: 8

body:
There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.

The active solution requires a device called a *multiplexer*.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.

The passive solution is called *open drain* or *open collector* (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

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

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.

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

body:
This solution only actually uses one pin, but only works with simple things like push buttons (which are either open, or closed).

Connect a (different) resistor in series (end-to-end) with each switch. Connect the loose end of each resistor together to +5V. Connect the loose end of those two switches together, then via another resistor to ground. Where the two switches meet, connect them to an analog pin on your Arduino.

For example, you might use a 20k resistor with button A, and a 10k resistor with button B, and a 10k resistor connected to ground. They should be pretty close to the same value, and at least 1k each.

Use the ReadAnalogVoltage sketch to measure the voltage with different combinations of button presses (no button pressed, A, B, A+B), then, in your final sketch, you can compare the value read with the values in this table - pick the closest one, because actual readings may vary slightly. For the resistors above, you should get about: (no button = 0v; A=1.7v, B=2.5v, both 3v). Sort these numerically (which in this case they already are), and work out the values exactly between each pair (up to 0.85 is closest to 0=> no button; else up to 2.1=> button A; else up to 2.75 is closest to B; otherwise, both are pressed.

The circuit described looks like this:

[![Switch circuit][1]][1]

The wire leading off to the right goes to the analog pin on the Arduino. Switch A is on the left.

The results can be used either in a table, with a loop, or in an if/else if statement (I used this technique on a 12-key keypad, so the list was a lot longer).

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

Read up about voltage dividers https://learn.sparkfun.com/tutorials/voltage-dividers and, for both buttons being pressed at the same time, resistors in parallel https://learn.sparkfun.com/tutorials/series-and-parallel-circuits

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

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

Try the above logic use a 555 timer with  C1: 10uF, R2: 300k and R1: 30k for 1.1 sec switching time,now for approx every one second data from USS1 goes to SIN(Arduino IN) when the timer OUT is high and  similarly when timer OUT is LOW signal from USS2 goes to SIN(Arduino),,,

But you will not be able to know from which sensor is the output coming.

If you would like to know from which sensor the output is coming you can just add one INVERTER to one of the branch so so both the sensors will give different states i.e one will return HIGH and other will return LOW

hope this helps

Edited:Please note 555 timer design part is not complete ,,i am just giving an idea :)

body:
> If you have two sensors from two different outputs but want them to go
> into one input, what do you need, and how can you read the input?

If you want your teacher lose his mind answer his question with this:

What I need? :)

 - A wire

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

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

The solution is to use one trig for both ultrasonic sensor and two echos.

or one echo and two triggers.

ultrasonic sensor sends the pulse > pulse back > now echo pin is connected to second sensors trig > the Second Ultrasonic sensor sends the pulse then starts listening. When the second ultrasonic echo back, it sends to other Arduino pin, reverse it if you want it on one input pin :)

    #define trigPin 6
    #define echoPin 4
    #define echoPin2 7

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
       pinMode(echoPin2, INPUT);
    }

    void loop() {
      long duration, distance, distance2;
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(20);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      duration = duration + pulseIn(echoPin2, HIGH);
      distance2 = (duration/2) / 29.1;
      if (distance >= 200 || distance <= 0){
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println("cm");
           Serial.print(distance2);
        Serial.println(" cm");
            Serial.println("HHH");
      }
      delay(500);
    }

that's it.

body: A SPDT switch would fit nicely in your diagram where the question mark is.

body:
I ran into the same question, except I wanted to put 8 of the HC-SR04 sensors on pro-mini.

I used an I2C pin expander for the triggers, and an octal OR/NOR chip to multiplex the return.

Library, examples and pictures

https://github.com/arielnh56/SonarI2C
http://redhunter.com/blog/2016/04/28/sonari2c-multiple-hc-sr04-sensors-on-arduino-i2c/

body: The question is two Ultrasonic data get input on one.  Its simple.  You just need two IDs.  Creat a IDs of each sensors.  You can use I2C bus too.  You need to hub who keep the two input in raw.  And than digitally write with address and than do codding for read the data.  Howz my idea guys?

body:
The OP does not specify whether the focus is on hardware or software.

So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible.  Thus, the solution would be implemented in software.

Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin.

It is time-gated (the time for the sensor to react to an object at maximum range).  If detected, then set a variable saving the distance measured on sensor 1.

Then the same could be sent from the second sensor's trigger pin.  And if there is a reflection within the time-gate then that can be recorded in another variable.

It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin.


body:
Just looking for a second opinion on my circuit below. Wired up everything works great, but last night as i was unplugging the FTDI programmer something seemed to have happend, and the mini was bricked.

I'm not sure if it has to do with my wiring below, or if it was me unplugging the cable in a haphazard manner.

What I'm attempting to do is run my arduino from 12v wall supply, but also drive an LED strip with it. I'm just unsure if this is the best way to go about it, any advice is welcome.

Thanks
Justin

[![example layout][1]][1]

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

title: Powering Arduino Pro Mini + Driving LED Strip

Answers: 1

body:
According to the [schematics][1], the Pro Mini uses the [MIC5205][2], which is a linear regulator.
Using it directly with 12V is not a very good idea, in terms of power efficiency, as it will dissipate 35mW vs 25mW provided to the ATMega board.

From this perspective, I'd recommend a [step-down converter][3] for powering the Arduino.

However it will not cause any damage, at least at room temperature, as the power dissipation is well within operating margins, see calculation at page 8 of the MIC datasheet.

**Edit:** detailed pros and cons, power wise.

  [1]: https://learn.sparkfun.com/tutorials/using-the-arduino-pro-mini-33v
  [2]: http://www.micrel.com/_PDF/mic5205.pdf
  [3]: http://www.ebay.com/itm/LM2596S-ADJ-Power-Module-DC-DC-Buck-Regulator-3A-Adjustable-5V-12V-24V-/171819436954?hash=item28013c8b9a


body:
I am making a new library that will utilize PinChangeInt's library.
My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.)
Since i understand OOP i knew that i could go the route of make my own library.

The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

>C:\...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0':

C:\...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'

C:\...\RCRoomba_TestPulseV2.cpp.o: In function 'setup':

C:\...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'

Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.

Here is the .ino code.

for some reason UECIDE can't see the Pinchange and PPMint libraries

    #include "arduino.h"
    #include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
    #include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

    PPMintIn CH1(A0);

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

    void loop(){
    }

Here is the .cpp code

    #include "arduino.h"
    #include "ppmintin.h"
    #include "PinChangeInt.h"
    //defined these
    volatile int pwm_value = 0;
    volatile int prev_time = 0;
    uint8_t latest_interrupted_pin = 0;

    PPMintIn::PPMintIn(int pin){
        pinMode(pin, INPUT);\
        digitalWrite(pin, HIGH);
        _pin = pin;
    }

    void PPMintIn::rising(){
        PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
        PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
        PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
    }

    void PPMintIn::falling(){
        PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
        PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
        PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
    }

    void PPMintIn::begin(){
        PCintPort::attachInterrupt(_pin, &rising, RISING);
    }

    void PPMintIn::getSignal(){
        return(PPMintIn::pwm_value);
    }

Here is the .h code

    #ifndef PPMINTIN_H
    #define PPMINTIN_H

    #if defined(ARDUINO) && ARDUINO >= 100
      #include "Arduino.h"
      #else
      #include "WProgram.h"
    #endif
    #include "PinChangeInt.h"

    class PPMintIn{
    public:
        PPMintIn(int pin);
        void begin();
        void getSignal();
        int _pin;
        volatile int pwm_value;
        volatile int prev_time;
        uint8_t latest_interrupted_pin;
    private:
        void rising();
        void falling();
    };

    #endif // PPMINTIN_H

here is the full thing in github in case I didn't supply it here.
https://github.com/tisaconundrum2/PPMintIn

title: undefined reference to `PPMintIn::PPMintIn(int)'

Answers: 1

body:
<!-- language-all: lang-C++ -->

As both Majenko and I tried to explain in <https://arduino.stackexchange.com/questions/14480/pass-a-member-function-pointer-to-a-method-of-a-foreign-class-edb-lib> you can't pass a class member function where a static function is expected.

---

Your error is on:

    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

Error:

<!-- language-all: lang-none -->

    /home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
    /home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

---

<!-- language-all: lang-C++ -->

PCintPort::attachInterrupt expects a `PCIntvoidFuncPtr` variable:

    int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

That is:

    typedef void (*PCIntvoidFuncPtr)(void);

That is a static function (not a class function).

However you have it as a class function:

    class PPMintIn{
    public:
        PPMintIn(int pin);
        void begin();
        void getSignal();
        int _pin;
        volatile int pwm_value;
        volatile int prev_time;
        uint8_t latest_interrupted_pin;
    private:
        void rising();
        void falling();
    };

Now you can make `rising` and `falling` static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).

The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

---

Regarding one of the comments:

[![Error message][1]][1]

Unless your class implements `operator()` this line doesn't make sense:

    chan1(15);

---

*Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.*

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


body:
I'm trying to save SRAM on my Arduino pro mini by going through some libraries. I've noticed that to use my Arduino as a ROS node the library stores the topic name and message type as constants.

    class Publisher
    {
    public:
      Publisher( const char * topic_name, Msg * msg, int    endpoint=rosserial_msgs::TopicInfo::ID_PUBLISHER) :
        topic_(topic_name),
        msg_(msg),
        endpoint_(endpoint) {};

      int publish( const Msg * msg ) { return nh_->publish(id_, msg); };
      int getEndpointType(){ return endpoint_; }

      const char * topic_;
      Msg *msg_;
      // id_ and no_ are set by NodeHandle when we advertise
      int id_;
      NodeHandleBase_* nh_;

    private:
      int endpoint_;
    };

How can I store the constants to PROGMEM? Thank you

title: How to change the topic_name string to PROGMEM?

Answers: 1

body:
My take on this is that you cannot save more memory on `topic-name` nor `msg` parameters. Their memory usage is already optimized.

The `const` keyword in the constructor declaration `Publisher( const char * topic_name, Msg * msg, ...` just tells the compiler that the parameter won't be changed throughout their life cycle. But their values will be defined at run-time during object creation when you issue something like this:

    Publisher pb = new Publisher("topic", "message", ...);

So, they cannot be put into flash memory if they are not there already. But if the strings you pass on to the constructor are already in flash, then you're already saving those bits of RAM.

---
Finally, I just wanted to warn you not to modify 3rd party lib code extensively without comprehensive testing, like you are trying to do. You'll start to get strange behavior in your code. The slightest and simplest of changes may have unforeseen consequences.


body:
How do I figure out how to connect to my arduino using ethernet shield?

It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.

The client example works, so it's not broken or anything.

I'm using `Arduino 1.6.5` IDE on a `Mega 2560`. I'm trying to run the `Examples/Ethernet/WebServer` example.

title: Connecting to Arduino Ethernet Shield

Answers: 1

body:
Your question is kind of trivial, but from what I understood you're typing the IP address (that the Arduino displays on the serial monitor)  into your browser.

First, make sure you connect your Ethernet shield to your router using an ethernet cable. (Now it's connected locally...)

Second, even if you type in your Arduino's IP address into the browser, the browser will return nothing because the Arduino simply has nothing to display, and hasn't been programmed to accept requests.

To actually have the Arduino display something you can try the Webserver example sketch or you can follow this great [Tutorial][1] that I found very useful for beginners.

BTW ports are only used to expose your Arduino to the Internet, in other words if you don't portforward to your Arduino, your Arduino won't be able to get requests from outside your local network (Wi-Fi,Ethernet).

  [1]: http://startingelectronics.org/tutorials/arduino/ethernet-shield-web-server-tutorial/


body:
So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?

Note that the project just says "buzzer" - not any more details.

Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

title: Buzzer - Does the voltage change with the frequency?

Answers: 1

body:
No, the frequency of the "buzzer" has no relationship to the voltage.

The *duty cycle* of the generated tone is proportional to the *average voltage* though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the *average* voltage is 50% of the supply voltage.

If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.

Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.

The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to *droop*.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


body:
I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.

I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?

Is there any alternative solution for ultrasonic sensors?

title: UltraSonic sensor in rain?

Answers: 3

body:
> will the buzzer make continuous sounds

If you mean the sensor will detect the rain drops in the air
Nop it's tiny to read it in the air
But if there is drops on the sensor your sensor will not gives you the right reading

There is a water proof ultrasonic sensors available.

I am working on water level devices, after long path of searching in different ultrasonic sensors and after I tried a lot of method like using water proof Cloth, I found the best way is using water proof sensors PLUS water proof cloth.

water proof sensors work perfectly in high humidity but at the same time if there is a water drop on the sensor the reading will be different, and for that some cars manufacturers used not only one sensor, to avoid the errors. and calculate the differences.

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

The left car used old technology with separate sensors, but that's make errors the only good thing was to detect more things, in the next generation they mix them together.

water proof cloth will make the water drops not stuck at the sensor, but you will need to replace it every 5-6 months. "in your case because the sun will destroy the cloth" in my case and because my sensor inside tanks that's will least more.

I tried to spray the sensor with a different material to make my sensor not catch any water drops, it dose not work too.

And to make my cheap sensor water proof, I tried to use ceramic layers, and that's not work too, they use it with ultrasonic fog maker, these layers not work with cheap ultrasonic sensors, it's need a lot of power to vibrate it and different frequency. and of course you need to replace the layers "depending on the environment"

If you find ultrasonic car sensor with special material for water drops just let me know, I am searching on that too.

**NOTE** These days car manufacturer use different ways, in the past the cover was vibrate itself and made from aluminum, now they cover it and make different filters to ignore the plastic cover, How?! maybe it's different plastic or material maybe they find away to vibrate the plastic! sorry I could not find the secret.

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

body: It would probably be easier to use an IR distance sensor.  That would also be easier to waterproof.

body: Just a thought, a lot of cars use them, why not try your local salvage yard you may be able to get them on the cheap.


body:
I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used `PIOB->PIO_PER = 1<<27;` to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.

Here's my complete code:

    #include <asf.h>

    int main (void) {
      // Insert system clock initialization code here (sysclk_init()).
   board_init();
   sysclk_init();
   delay_init(sysclk_get_cpu_hz());
   PIOB->PIO_PER = 1<<27;
   PIOB->PIO_OER = 1<<27;
   while(1) {
        REG_PIOB_ODSR = 1<<27;
  delay_ms(1000);
  REG_PIOB_ODSR = 0<<27;
  delay_ms(1000);
   }
    }

Can anyone tell me how I can get this to work?

title: Enabling pins of Arduino Due with direct port manipulation

Answers: 2

body:
I suggest the following test:  Use `REG_PIOB_SODR = 1<<27;` to set the bit, and  `REG_PIOB_CODR = 1<<27;` to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)

Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:
>After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.

body:
        #define Led_ON  REG_PIOB_ODSR |= 0x8000000
        #define Led_OFF REG_PIOB_ODSR &= ~0x8000000
        //for Arduino Due
        PIOB->PIO_PER |= 0x8000000;//led
        PIOB->PIO_OER |= 0x8000000;//led
And then call Led_ON and Led_OFF


body:
I have written a codebender project which returns this error:

    Oops! Looks like there was a serious issue with your project.

    If you are not sure what could be wrong please contact us

    /mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()':
    Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster'
    Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster'

What does it mean by `vtable`?

The code uses basic classes and inheritance.

The program is designed to select and play the game of your choice.  I have only programmed the basic structure.

Class `games` contains a ref to the class `gamesMaster`.

Class `gamesMaster` contains a ref to `simpleTimer`.

Classes `playHiLow` and `playSimon` are children of `gamesMaster`.

Class `games` handles and input and outputs, `win` and `lose` control and keeps track of lives.

Class `gamesMaster` handles the `simpleTimer`, displays a new round, checks for the correct answer, and checks if game has finished successfully.

The `main()` function runs a routine in the `games` class.

The code is listed here: <https://codebender.cc/sketch:144869>

    class simpleTimer
    {
    private:
     unsigned long _previousMillis;
     unsigned long _interval;

    public:
     simpleTimer()
     {

     }
     void start(float mins)
     {
      _interval = (unsigned long) (mins * 60 * 1000);
      _previousMillis = millis();
     }
     bool stillRunning()
     {
      return (millis() - _previousMillis < _interval);
     }
    };

    class gamesMaster
    {
    public:
     unsigned short lives;
     gamesMaster()
     {
      timeOutTimer = new simpleTimer();
      gameTimer = new simpleTimer();
      gameTimer->start(1.5);
      lives = 5;
     }
     void right()
     {
      Serial.println("Correct");
     }
     void wrong()
     {
      Serial.println("Wrong");
     }
     void winGame()
     {
      Serial.println("**********");
      Serial.println("* WINNER *");
      Serial.println("**********");
     }
     void loseGame()
     {
      Serial.println("\\ /          \\ /");
      Serial.println(" X    LOST    X");
      Serial.println("/ \\          / \\");
     }
     void startTimeOut(float mins)
     {
      timeOutTimer->start(mins);
     }
     bool notTimedOut()
     {
      return timeOutTimer->stillRunning();
     }
     bool gameTimerOver()
     {
      return !gameTimer->stillRunning();
     }
     simpleTimer *timeOutTimer;
     simpleTimer *gameTimer;

     virtual void setupForNewRound(void);
     virtual bool checkAnswer(unsigned short);
     virtual bool reachedEnd(void);
    };

    class gameHiLow: public gamesMaster
    {
    public:
     gameHiLow() : gamesMaster() {}
     void setupForNewRound()
     {
      Serial.println("  ->(HiLow) New round");
     }
     bool checkAnswer(unsigned short answer)
     {
      Serial.println("  ->(HiLow) Correct Answer");
      return HIGH;
     }
     bool reachedEnd()
     {
      Serial.println("  ->(HiLow) End of game");
      return HIGH;
     }
    };

    class gameSimon: public gamesMaster
    {
    public:
     gameSimon() : gamesMaster() {}
     void setupForNewRound()
     {
      Serial.println("  ->(Simon) New round");
     }
     bool checkAnswer(unsigned short answer)
     {
      Serial.println("  ->(Simon) Correct Answer");
      return HIGH;
     }
     bool reachedEnd()
     {
      Serial.println("  ->(Simon) End of game");
      return HIGH;
     }
    };

    class games
    {
    private:
     unsigned short _gameToPlay;
     unsigned short _levelToPlay;
     gamesMaster *myGame;
     unsigned short _getAnswer()
     {
      if (Serial.available() > 0)
      {
       int inByte = Serial.read();
       Serial.println("  ->(games) Decode Answer");

       switch (inByte)
       {
        case '<':
         return 1;
         break;
        case '>':
         return 2;
         break;
       }

      }
      return 0;

     }
     bool _respond()
     {
      unsigned short answer;
      while(myGame->notTimedOut())
      {
       if((answer = _getAnswer()) != 0)
       {
        if(myGame->checkAnswer(answer) == HIGH) return HIGH;
       }
      }
      return LOW;
     }
    public:
     games(unsigned short gameToPlay, unsigned short levelToPlay)
     {
      _gameToPlay = gameToPlay;
      _levelToPlay = levelToPlay;
      switch(_gameToPlay)
      {
       case 1:
        myGame = new gameHiLow();
        Serial.println(" ->(game) play Higher or Lower Game");
        break;
       case 2:
        myGame = new gameSimon();
        Serial.println(" ->(game) play Simon Game");
        break;
      }
     }
     void play()
     {
      unsigned short answer;
      while(!myGame->gameTimerOver())
      {
       myGame->setupForNewRound();
       myGame->startTimeOut(.5);
       if(_respond() == HIGH)
       {
        myGame->right();
        if(myGame->reachedEnd())
        {
         myGame->winGame();
         return;
        }
       }
       else
       {
        myGame->wrong();
        if(--myGame->lives <= 0)
        {
         myGame->loseGame();
         return;
        }
       }
      }
      myGame->loseGame();
     }
    };

    //////////////////////////////////////////////////////////////////////////////////
    games *game;

    void setup()
    {
     Serial.begin(9600);
     unsigned short gameToPlay = 1;
     unsigned short levelToPlay = 1;
     game = new games(gameToPlay, levelToPlay);
    }

    void loop()
    {
     Serial.println("Let the games begin");
     game->play();
     Serial.println("Program Complete");
     delay(5000);
     exit(0);
    }

title: Problem with codebender project not compiling

Answers: 2

body:
As discussed here

https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable

declare these functions pure virtual:

    virtual void setupForNewRound(void) = 0;
    virtual bool checkAnswer(unsigned short) = 0;
    virtual bool reachedEnd(void) = 0;

body:
I agree with @GeryOshlike.  But that's not the only option.

Yes, you can make them *pure virtual*:

    virtual void setupForNewRound(void) = 0;
    virtual bool checkAnswer(unsigned short) = 0;
    virtual bool reachedEnd(void) = 0;

Or you can make them virtual with a default function:

    virtual void setupForNewRound(void) { }
    virtual bool checkAnswer(unsigned short) { return false; }
    virtual bool reachedEnd(void) { return false; }

Pure virtual will complain when you compile if you haven't implemented those functions in your child class.  By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.

If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route.  If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.


body:
I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?

Thanks in advance.

title: Atmega328 board output voltage

Answers: 1

body:
It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.

A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).


body:
I'm trying to make two Arduino cards communicate, one is a sender and the other only receive packet from the first one and then display them.

My problem is that the first recieved packet is not displayed unlike the other packets(displayed normally)

here's the output of my code :

[![serial monitor for both device][1]][1]

Here's my code of the reciever :

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

    void handle_rx() {

    Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

    if(mrf.get_bufferPHY()){
      Serial.println("Packet data (PHY Payload):");
      for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
          Serial.print(mrf.get_rxbuf()[i]);
      }
    }

    Serial.println("\r\nASCII data (relevant data):");
    for (int i = 0; i < mrf.rx_datalength(); i++) {
        Serial.write(mrf.get_rxinfo()->rx_data[i]);
    }

    Serial.print("\r\nLQI/RSSI=");
    Serial.print(mrf.get_rxinfo()->lqi, DEC);
    Serial.print("/");
    Serial.println(mrf.get_rxinfo()->rssi, DEC);
    }

Here is the complete sketch:

    /**
     * Example code for using a microchip mrf24j40 module to send and receive
     * packets using plain 802.15.4
     * Requirements: 3 pins for spi, 3 pins for reset, chip select and interrupt
     * notifications
     * This example file is considered to be in the public domain
     * Originally written by Karl Palsson, karlp@tweak.net.au, March 2011
     */
    #include <SPI.h>
    #include <mrf24j.h>

    const int pin_reset = 6;
    const int pin_cs = 7; // default CS pin on ATmega8/168/328
    const int pin_interrupt = 2; // default interrupt pin on ATmega8/168/328

    Mrf24j mrf(pin_reset, pin_cs, pin_interrupt);

    long last_time;
    long last_time2;
    long tx_interval = 1000;

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

      mrf.reset();
      mrf.init();

      mrf.set_pan(0xcafe);
      // This is _our_ address
      mrf.address16_write(0x4201);

      // uncomment if you want to receive any packet on this channel
      //mrf.set_promiscuous(true);

      // uncomment if you want to enable PA/LNA external control
      //mrf.set_palna(true);

      // uncomment if you want to buffer all PHY Payload
      //mrf.set_bufferPHY(true);

      attachInterrupt(0, interrupt_routine, CHANGE); // interrupt 0 equivalent to pin 2(INT0) on ATmega8/168/328
      last_time = millis();
      interrupts();
    }

    void interrupt_routine() {
        mrf.interrupt_handler(); // mrf24 object interrupt routine
    }

    void loop() {
        mrf.check_flags(&handle_rx, &handle_tx);
        unsigned long current_time = millis();
        if (current_time - last_time > tx_interval) {
            last_time = current_time;
            Serial.println("txxxing...");
            mrf.send16(0x4202, "abcd");
        }
    }

    void handle_rx() {
        Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

        if(mrf.get_bufferPHY()){
          Serial.println("Packet data (PHY Payload):");
          for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
              Serial.print(mrf.get_rxbuf()[i]);
          }
        }

        Serial.println("\r\nASCII data (relevant data):");
        for (int i = 0; i < mrf.rx_datalength(); i++) {
            Serial.write(mrf.get_rxinfo()->rx_data[i]);
        }

        Serial.print("\r\nLQI/RSSI=");
        Serial.print(mrf.get_rxinfo()->lqi, DEC);
        Serial.print("/");
        Serial.println(mrf.get_rxinfo()->rssi, DEC);
    }

    void handle_tx() {
        if (mrf.get_txinfo()->tx_ok) {
            Serial.println("TX went ok, got ack");
        } else {
            Serial.print("TX failed after ");Serial.print(mrf.get_txinfo()->retries);Serial.println(" retries\n");
        }
    }

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

title: First recieved packet not displayed (Arduino with MRF24j40MA)

Answers: 0


body: Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

title: Arduino ESP8266 receive email?

Answers: 1

body:
Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).

Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.

Note: once you connect to the IMAP server, the first command to send is the login command:

    foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.

Once you get the welcome message, you can start sending more commands:

Select the proper folder:

    . SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):

    . SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:

    * SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.

If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:

    . FETCH 5  BODY[TEXT]

or

    . FETCH 5  BODY[TEXT].PEEK

End IMAP session with:

    . logout

For experiments from Windows using telnet:

    telnet mailserver.domain.com 143

Reference:

https://www.skytale.net/blog/archives/23-Manual-IMAP.html


body:
I have a motor and gearbox that has limits and a pot built in.

I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.

I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.

I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.

I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.

How can I do that?

<!-- language-all: lang-none -->

    sensor       = pot on motor,
    where        = 0 to 5 input,
    vent1UPlim   = limits,
    vent1DOWNlim = limits

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.

<!-- language-all: lang-C++ -->

            //            pot           0-10v     ONE WAY
              if (sensorValue > (where + 0.5)) {
              if (digitalRead(vent1UPlim)==    HIGH) {
                DoneInitializationA=false;
                digitalWrite(vent1enable,      HIGH);
                delay(50);
                digitalWrite(vent1PWMA ,       HIGH);
                mydisp.drawStr(0, 2, "-close-|");
              }
              else {
                digitalWrite(vent1PWMA ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
              }
            }
            else {
              if (!DoneInitializationA)
              {
                digitalWrite(vent1PWMA ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
                DoneInitializationA=true;
              }
            }

               //                                   OTHER WAY
              if (sensorValue < (where - 0.5)) {
              if (digitalRead(vent1DOWNlim)==  HIGH) {
                DoneInitializationB=false;
                digitalWrite(vent1enable,      HIGH);
                delay(50);
                digitalWrite(vent1PWMB ,       HIGH);
                mydisp.drawStr(0, 2, "-open -|");
              }
              else {
                digitalWrite(vent1PWMB ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
              }
            }
            else {
              if (!DoneInitializationB)
              {
                digitalWrite(vent1PWMB ,       LOW);
                delay(50);
                digitalWrite(vent1enable,      LOW);
                mydisp.drawStr(0, 2, "       |");
                DoneInitializationB=true;
              }
            }

title: adding a dead band to my motor and gearbox

Answers: 1

body:
The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.

eg.

<!-- language-all: lang-C++ -->

    if (abs (sensorValue - where) >= 0.5) {
      {
      // do something

      if (sensorValue > where)
        {
        // one way
        }
      else
        {
        // other way
        }
      } // end of large enough to worry about

---

In response to this (since deleted):

> would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up **and** down).


body:
I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.

The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

title: Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer?

Answers: 2

body:
You could use the [Simulator][1] in [Atmel Studio][2] or something like [Virtual Breadboard][3] which looks good

The [Atmel Studio][2] simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the [Arduino plugin for Atmel Studio][4] useful.

I think there are quite a few other solutions if you search google.

  [1]: http://www.atmel.com/webdoc/simulator/simulator.wb_Simulator_Use.html
  [2]: http://www.atmel.com/microsite/atmel_studio6/
  [3]: http://www.virtualbreadboard.com/
  [4]: http://www.visualmicro.com/page/Arduino-for-Atmel-Studio.aspx

body:
To verify communication via COM port (to send messages as well as to receive) you can use arduino emulator from wokwi.com

with the Wokwi arduino emulator, it is easy to do the changes, add input devices as well.

**To create a COM port**
You just need to have a

    Serial.begin(9600);
    Serial.println("Text message");

you will be able to see the virtual serial window in the bottom right where you can see the messages printed out as well as you will be bale to key in the serial data you want to send to Arduino.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/KWfst.gif


body:
I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301
They write that the firmware has the version ServicePack 1.11.1.
The WiFi shield is connected to the Arduino and green status light is on.

I try to run this example code:

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
    }

    // check for the presence of the shield:
    if (WiFi.status() == WL_NO_SHIELD) {
      Serial.println("WiFi shield not present");
        // don't continue:
      while(true);
    }
    ...

It seems that Wifi.status() always returns WL_NO_SHIELD.
What can I do?

Thanks for help.

Answers: 1

body:
The problem is solved now.

- I imported the Adafruit_CC3000 library which can be downloaded here: https://github.com/adafruit/Adafruit_CC3000_Library
- I run the example but the output was chinese nonsense
- Instead of

    Serial.begin(115200);

   I used

    Serial.begin(9600);

   then the examples run without any problem

Thanks @Majenko. His question was very helpful.


body:
On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.

Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: https://arduino.stackexchange.com/questions/864/arduino-mega-timeout-communication-with-programmer-error

Is there anything else I should verify? Or is the Arduino always going to be damaged?

Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.

title: Reversed Input Voltage Arduino Mega timeout communication with programmer error

Answers: 3

body:
Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.

In short: *"It's dead, Jim!"*

body:
*Don't reprogram the bootloader.*

If you can upload sketches that is unnecessary.

It will probably be fiddly to identify and fix what has failed, but since you can reprogram it via USB it is still 99% working.

I suggest you get one of those USB charging wall-warts that provide 5 V, and just plug that into the USB port if you want to run it away from the PC. You know that the USB power part works.

body:
The Mega has a reverse polarity protection diode ([D1](https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf)) on the board, so you plugging in the wrong polarity barrel didn't damage anything.

So your current problem in unrelated to this.


body:
My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.

Or could that cause problems?

title: Removing the barrel jack connector?

Answers: 4

body: You can remove it safely without any issues, just make sure that there are no short circuits or any other components damaged while doing so

body: You'll likely do less damage de-soldering it than trying to snip it off. Use a de-soldering pump to remove as much molten solder as you can, then heat again with de-soldering braid to wick up the remainder. If the jack's solder terminals were bent over (to stabilize the part before it was soldered) you may need to straighten them with a tweezer-nosed plier. Then you should be able to lift the part off the board. Don't overheat the board or heat any other parts or solder joints than those you intend to remove.

body: De sdering would be safer.  You can then use the Vin pin to supply sour voltage (IIRC you can run as high as 12 volts with the uno)

body:
Unless you have some really specific reason to use a UNO, for example using the 2nd ATMega on the board, you would be much better off with an Micro Pro.

On ebay you can find both 3.3V and 5V versions.
You can even find ones that have redundant pins, to accommodate for a permanent installation of the ISP programmer.

Even if you happen to have a shield that is compatible with the UNO pinout, you could still wire it with a flat cable and save space.

Said this, using mechanical means on a PCB is always putting at risk the tracks, which might come off.

Desoldering is better, since it's reversible.

But you might find that it takes an unusually powerful soldering iron, compared to what is used nowadays for smd components, as you will have to heat up simultaneously several large pads, which have connected large tracks and ground areas that act as heat sink.

In case you do not have desoldering braid and or pump, there's a hackish method to remove large components with multiple pads: flood them in molten solder and literally shake them off the board by hitting the workbench sideways, while the solder is still fluid.

Not nice and at risk of adding splash shorts to the board, not to mention the splash damage to the operator: it can cause burns on unprotected skin or organs.

However, if done correctly, it works without pump or braid.


body: I have a shapeoko 2, and have been wanting to create a jogging pendant for it for a while.  Currently GRBL (the G code interpreter for arduino) doesn't support jogging the machine with a pendant.  I was wondering if it was possible to emulate arrow key inputs on the keyboard through an arduino.

title: Using an arduino to emulate keyboard inputs

Answers: 0


body:
Would it be possible to use to of [these][1] on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.

  [1]: http://www.ebay.com/itm/Bluetooth-Serial-Transceiver-Module-Base-Board-clear-button-For-Arduino-SWTG-/231608470902?hash=item35ecf0cd76

title: Bluetooth Trancievers for arduinos

Answers: 1

body:
The boards in your link look funny.  Typical boards like this include the "bluetooth circuit" which piggy-backs onto that board, and is soldered at all those little pads.

Have a look at say, the HC-05 board ~  https://www.google.com.au/search?q=hc05+bluetooth+module&tbm=isch

It's easy to see the part that's missing from the one in your link.

For these HC-05 boards, it's possible to pair two together.  They need to be configured as "Master" and "Slave" though.  Some bluetooth boards can do slave-mode only, so be careful before you purchase.


body:
#Context

I first ran a sketch (**on Arduino Uno**) without any custom data structure and list, so I was using a bunch of arrays, methods and other primitive variables. And it worked perfectly.

*My program acts like a menu which takes serial user input to perform actions. So you could have serial input "man r+(100,0,345)". Or just "man" to set this mode active, and later "r+(100,0,345)" to actualize the data in the "r" field in the "man" instance. I use a custom data structure to manage the input (class called Mode), and a linked list (class called ModeList).*

#Problem

I implemented some data structures (an object and a list) to manage incoming serial data, without modifying the rest of the program. But now, serial communication is not working properly: If I add `Serial.print("Allo")` *anywhere* in the sketch, it will print spaces for a while and stop, before I send any serial data. If it is in the `setup()` function, it prints spaces continuously with some characters from "Allo" from time to time. There's always a different problem along those lines, depending on where I put that simple print statement.

**Here follows the sketch, the header files of the Mode and ModeList classes... By the way, I suspect a memory management problem.**

#The sketch

    #include "Mode.h"
    #include "ModeList.h"

    const int inputSize=12;
    const int nbModes=4;
    int input;
    int toSet[inputSize];
    int i;

    char manName[3]={'m','a','n'};
    char cutName[3]={'c','u','t'};
    char levName[3]={'l','e','v'};
    char autName[3]={'a','u','t'};

    Mode m=Mode(0,manName);
    Mode c=Mode(1,cutName);
    Mode l=Mode(2,levName);
    Mode a=Mode(3,autName);
    Mode* man=&m;
    Mode* cut=&c;
    Mode* lev=&l;
    Mode* aut=&a;
    ModeList modeList=ModeList();

    void setup() {
      Serial.begin(115200);
      Serial.print("Allo");
      modeList.add(man);
      modeList.add(cut);
      modeList.add(lev);
      modeList.add(aut);
      }

    void loop() {
      for(int j=0;j<inputSize;j++)
      {
        toSet[j]=NULL;
      }
      i=0;
      if(Serial.available()>0)
      {
        while(Serial.available())
        {
          if(i<inputSize)
          {
            input=Serial.read();
            if(input!=' ' && input!='(' && input !=')' && input!=',' && input!='\n')
            {
              toSet[i]=input;
              i++;
            }
          }
        }
      }

      if(serialMode(man)||man->getStatus())
      {
        //Set man on
        modeList.setMode(man);

        if(toSet[3]=='r')
        {
          if(toSet[4]=='+')
          {
            //Set ypr rate
            Serial.println("Set ypr rate +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr rate
            Serial.println("Set ypr rate -");
          }
          else
          {
            //Set ypr rate
            Serial.println("Set ypr rate");
          }
        }
        else if(toSet[3]=='a')
        {
          if(toSet[4]=='+')
          {
            //Set ypr angle
            Serial.println("Set ypr angle +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr angle
            Serial.println("Set ypr angle -");
          }
          else
          {
            //Set ypr angle
            Serial.println("Set ypr angle");
          }
        }
        else if(toSet[3]=='t')
        {
          if(toSet[4]=='+')
          {
            //Set thrust
            Serial.println("Set thrust +");
          }
          else if(toSet[4]=='-')
          {
            //Set thrust
            Serial.println("Set thrust -");
          }
          else
          {
            //Set thrust
            Serial.println("Set thrust");
          }
        }
      }
      if(serialMode(cut)||cut->getStatus())
      {
        //Cut engines
        modeList.setMode(cut);
        if(serialMode(cut))
          Serial.println("Cut");
      }
      if(serialMode(lev)||lev->getStatus())
      {
        //Stabilize axes
        modeList.setMode(lev);
        if(serialMode(lev))
          Serial.println("Level");
      }
      if(serialMode(aut)||aut->getStatus())
      {
        //Set aut on
        modeList.setMode(aut);
        if(serialMode(aut))
          Serial.println("Set aut on");
        if(toSet[3]=='s')
        {
          if(toSet[4]=='+')
          {
            //Set ypr angle
            Serial.println("Set ypr angle +");
          }
          else if(toSet[4]=='-')
          {
            //Set ypr angle
            Serial.println("Set ypr angle -");
          }
          else
          {
            //Set ypr angle
            Serial.println("Set ypr angle");
          }
        }
        else if(toSet[3]=='A')
        {
          if(toSet[4]=='+')
          {
            //Set altitude
            Serial.println("Set altitude +");
          }
          else if(toSet[4]=='-')
          {
            //Set altitude
            Serial.println("Set altitude -");
          }
          else
          {
            //Set altitude
            Serial.println("Set altitude");
          }
        }
      }
      delay(10);
    }

    bool serialMode(Mode* inputMode)
    {
      char* modeName;
      modeName=inputMode->getName();
      Serial.print("ALLO");
      if(toSet[0]==*modeName&&toSet[1]==*(modeName+1)&&toSet[2]==*(modeName+2))
      {
        Serial.print("Set ");
        for(int i=0;i<3;i++)
        {
          Serial.print(*(modeName+i));
        }
        Serial.println(" on");
        return true;
      }
      else
        return false;
    }

#The Mode class header

    #include "Arduino.h"

    class Mode
    {
        public:
            Mode(int id, char* name);
            int getId();
            Mode* getNext();
            void setNext(Mode m);
            void setStatus(bool status);
            bool getStatus();
            char* getName();
        private:
            char *_name;
            int _id;
            Mode* _next;
            bool _status;
    };

#The ModeList class header

    class ModeList
    {
        public:
            void add(Mode* input);
            int get(int pos);
            ModeList();
            void setMode(Mode* inputMode);
        private:
            Mode* start;
            Mode* end;
    };

title: Serial problem after implementing data structures

Answers: 1

body:
>  If I add Serial.print("Allo") anywhere in the sketch, it will print spaces for a while and stop, before I send any serial data.

Classic symptoms of using up all available RAM.

As a workaround I would use the `F()` macro.

eg.

        Serial.println(F("Set ypr rate +"));

Do that in all places where you are printing string literals. That would save you a couple of hundred bytes.


body:
I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller.

The setup is as follows:

Arduino|---UART--------------------------|MCU2

Arduino|---FLOW_CONTROL_PIN---|MCU2

I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).

At this point I log the amount of bytes sent and compare that to the buffer threshold level.  If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay.  I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).

A problem can arise if the Arduino api is providing more latency than the path under test.  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api.  I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.

title: What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?

Answers: 1

body:
<!-- language-all: lang-C++ -->

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.

I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.

I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

> A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.

This is probably what you are experiencing. See HardwareSerial.cpp:

    // Define constants and variables for buffering incoming serial data.  We're
    // using a ring buffer (I think), in which head is the index of the location
    // to which to write the next incoming character and tail is the index of the
    // location from which to read.
    #if (RAMEND < 1000)
      #define SERIAL_BUFFER_SIZE 16
    #else
      #define SERIAL_BUFFER_SIZE 64
    #endif

For this test you might want to edit that file and reduce that number, substantially.

Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

>  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

---

> What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?

However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.

To keep things simple though, what you really need to do here is **not buffer** because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:

    Serial.write ('a');  // or whatever
    Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).


body:
I have a few RTC modules with a batteries. All of them have this same issue with my project.

They work fine when connected via USB. But if I disconnect the power then reconnect they reset to Jan 1 2000.

I've read several posts about similar problems. But, none seem to apply.

Here is my code:

    #include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
    #include <SPI.h>
    #include <SD.h>
    #include "Wire.h"
    #include <RTClib.h>
    RTC_DS1307 RTC;
    #define BUTTON_PIN       0 // Button
    #define LONGPRESS_LEN    25  // Min nr of loops for a long press
    #define DELAY            20  // Delay per loop in ms

    enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

    boolean button_was_pressed; // previous state
    int button_pressed_counter; // press running duration

    byte zero = 0x00; //workaround for issue #527

    char* modes[]={"Walk", "Bike", "Subway", "Train", "Bus", "X-Bus", "Waiting", "Other"};
    byte mode=0;
    int modeRead;

    // Chip Select for SD
    #define chipSelect 10

    //MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);
    MicroOLED oled(9, 8, 5); // SPI declaration

    void setup()
    {
        pinMode(BUTTON_PIN, INPUT);
        digitalWrite(BUTTON_PIN, HIGH); // pull-up
        Serial.begin(9600);
        button_was_pressed = false;
        button_pressed_counter = 0;

        SD.begin(chipSelect);

        Wire.begin();
        RTC.begin();
        //RTC.adjust(DateTime(__DATE__, __TIME__));

        oled.begin();    // Initialize the OLED
        oled.clear(PAGE);     // Clear the screen
        oled.setFontType(1);  // Set font to type 0
        oled.setCursor(0, 0); // Set cursor to top-left
        oled.println(F("co'mute"));
        oled.display();  // Display what's in the buffer
    }

    int handle_button()
    {
        int event;
        int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

        if (!button_now_pressed && button_was_pressed) {
            if (button_pressed_counter < LONGPRESS_LEN)
                event = EV_SHORTPRESS;
            else
                event = EV_LONGPRESS;
        }
        else
            event = EV_NONE;

        if (button_now_pressed)
            ++button_pressed_counter;
        else
            button_pressed_counter = 0;

        button_was_pressed = button_now_pressed;
        return event;
    }

    void printDate ()
    {
        oled.clear(PAGE);     // Clear the screen
        oled.setFontType(0);  // Set font to type 0
        oled.setCursor(0, 0); // Set cursor to top-left

        DateTime now = RTC.now();

        oled.print(now.year(), DEC);
        oled.print('/');
        oled.print(now.month(), DEC);
        oled.print('/');
        oled.print(now.day(), DEC);
        oled.print(' ');
        oled.print(now.hour(), DEC);
        oled.print(':');
        if (now.minute()<10) {
            oled.print("0");
        }
        oled.print(now.minute(), DEC);
        oled.print(':');
        if (now.second()<10) {
            oled.print("0");
        }
        oled.print(now.second(), DEC);
        oled.println();
        oled.setFontType(1);  // Set font to type 0
        oled.println(modes[mode]);
        oled.display();   // Display what's in the buffer (splashscreen)
    }

    void writeFile()
    {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);
        // If the file is available, write to it:
        if (dataFile) {
            DateTime now = RTC.now();
            //print the date EG   3/1/11 23:59:59
            dataFile.print(now.year(), DEC);
            dataFile.print('/');
            dataFile.print(now.month(), DEC);
            dataFile.print('/');
            dataFile.print(now.day(), DEC);

            printDate ();
            oled.print("*SAVED*");
            oled.display();
            delay(3000);
        }
    }

    void loop()          // run over and over again
    {
        // handle button
        boolean event = handle_button();

        // do other things
        switch (event) {
            case EV_NONE:
            oled.print(".");
            break;

            case EV_SHORTPRESS:
            oled.print("S");
            //modeRead = analogRead(0);    // read the value from the sensor
            writeFile();
            break;

            case EV_LONGPRESS:
            oled.print("L");
            break;
        }

        static int counter = 0;
        if ((++counter & 0X016) == 0) {
            printDate ();
        }
        modeRead = analogRead(A0);    // read the value from the sensor
        delay(DELAY);

        int c=1020/(sizeof(modes)/sizeof(modes[0]));
        for (int i = 0; i < c; i++) {
            if (i*c < modeRead && (i+1)*c < modeRead) {
                mode = i;
            }
        }
    }

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

In this diagram the "pressure sensor" is really a OLED that operates via MOSI and MISO.

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

title: RTC resets when power is off

Answers: 1

body:
The RTC board has a battery holder and requires the button battery to be fitted in order to retain the time and date value. As shown in the [Datasheet][1], this battery is for the RTC chip only.

[![DS1307 Circuit][2]][2]

The [Adafruit board][3] requires a CR1220 button battery.

[![Adafruit DS1307 board][4]][4]

The Adafruit webpage mentions the following:

> Note: This product does not come with a CR1220 coin cell battery.

(Providing that it works when the Arduino is powered up) It sounds as if the battery for the RTC is either:

 - not present
 - not connected (not inserted correctly or not making proper connection)
 - inserted upside down
 - a track on the PCB is broken or shorted
 - the battery is flat

The battery should be inserted so that the flat + side is UP. I suggest that you use a DMM to measure the RTC battery voltage at the RTC IC. Place your +ve probe on pin 3 of the IC and the -ve probe on pin 4. It should read slightly above 3.0 Volts.

I also recommend that you disconnect all of the other periferals so that you just have the RCT connected to the Arduino. Then use a known working program such as the one in the [Adafruit tutorial][5] to verify that your RTC is working correctly. You should be able to disconnect the USB and then reconnect it and find that the RTC is still holding the correct time.

[RTC DS1307 Datasheet][1]
[Adafruit RTC Product][3]
[Adafruit RTC Tutorial][5]

  [1]: https://datasheets.maximintegrated.com/en/ds/DS1307.pdf
  [2]: https://i.stack.imgur.com/mx4aF.png
  [3]: https://www.adafruit.com/product/3296
  [4]: https://i.stack.imgur.com/AszFn.png
  [5]: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit?view=all


body:
I'm building a home automation product and want to measure AC current using Arduino (as of now). I've used ACS712 5A Hall Effect Current module but there's a lot of electrical noise and also the accuracy is not good. There's a lot of deflection in value when no current passes through it. I want to pack the whole kit in a box. So how to make sure that there will be no magnetic interference?

Can you suggest some other module to use for the same? Also that can last long enough.

title: Which device to use to measure AC current using Arduino?

Answers: 1

body:
Some sort of Current Transformer usually does the trick.  You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage.  You can find them packaged like [this one][1] with a [web search][2].

  [1]: http://www.dx.com/p/yqj010504-single-phase-ac-current-sensor-module-w-active-output-deep-blue-5a-294209#.Vd20A_lVhBc
  [2]: https://www.google.com/search?q=ac current sensor


body:
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?

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

    float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
    int x = 0,pre_x = 0,t = 0,pre_t = 0;

    long unsigned int t

    void loop()
    {
      x = analogRead(A0);
      t = millis();
      float diff_t = (float)(t - pre_t)/1000.0f;
      area = (0.5 * (pre_x + x) * diff_t) + pre_area;

      Serial.print(area);
      analogWrite(DAC0, area);
      pre_x = x;
      pre_area = area;
      pre_time = t;
    }

title: expected initializer before void arduino

Answers: 3

body: You add the semicolon that is missing at the end of `long unsigned int t`

body:
**Why have you written t = 0 here and declared it again below??**

    int x = 0,pre_x = 0,t = 0,pre_t = 0;

 **Semi Colon Missing**

    long unsigned int t;

 **Where have you declared pre_time??**

      pre_time = t;

body:
<!-- language-all: lang-C++ -->

    long unsigned int t

No semicolon.

---

Plus, make up your mind what type "t" is:

    int x = 0,pre_x = 0,t = 0,pre_t = 0;
    long unsigned int t;

Is it `int` or `long unsigned int`?

---

> How can I get the code to work?

Avoid C++ syntax errors.


body:
According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

[![Arduino Due Pinout][1]][1]

[source][2]

However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.

Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

  [1]: https://i.stack.imgur.com/VuNPu.png
  [2]: http://forum.arduino.cc/index.php?topic=132130.0

title: How to use the additional SPIs on Arduino Due

Answers: 1

body:
I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI

There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).

The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


body:
I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..

        #include <MIDI.h>
    int pot[] = {A0,A1,A2};
    int AnaPinsNum = 3;
    int potIn[] = {0,0,0};
    int analogValue = 0;

    int lastAnalogValue[] = {0,0,0};

     void setup()
     {
      MIDI.begin(4);
      // 115200 hairless MIDI
      Serial.begin(115200);
      int i;
      for (i = 0; i < 3; i++);
     }
     void loop() {

      int i;
      for (i = 0; i < AnaPinsNum; i++)

      potIn[i] = analogRead(pot[i])/8;

      // potentiometer could be too sensitive and
      // give different (+-1) values.
      // send CC only when the difference between last value
      // is more than 1
      if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
        // value changed?
        if (potIn[i] != lastAnalogValue[i]) {
          // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
          // more info: http://arduinomidilib.sourceforge.net/a00001.html
          MIDI.sendControlChange(1, potIn[i], 1);
          lastAnalogValue[i] = potIn[i];
        }
      }

    }

title: Unable to add multiple potentiometer in Midi controller

Answers: 1

body:
<!-- language-all: lang-C++ -->

Your logic is flawed here:

      int i;
      for (i = 0; i < AnaPinsNum; i++)
        potIn[i] = analogRead(pot[i]) / 8;

      // potentiometer could be too sensitive and
      // give different (+-1) values.
      // send CC only when the difference between last value
      // is more than 1
      if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
        // value changed?
        if (potIn[i] != lastAnalogValue[i]) {
          // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
          // more info: http://arduinomidilib.sourceforge.net/a00001.html
          MIDI.sendControlChange(1, potIn[i], 1);
          lastAnalogValue[i] = potIn[i];
          }
        }

The first three lines read all three analog pins:

      int i;
      for (i = 0; i < AnaPinsNum; i++)

        potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of `i` which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.

      int i;
      for (i = 0; i < AnaPinsNum; i++)
        {   // <------------------------------- add this
        potIn[i] = analogRead(pot[i]) / 8;

        // potentiometer could be too sensitive and
        // give different (+-1) values.
        // send CC only when the difference between last value
        // is more than 1
        if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
          {
          // value changed?
          if (potIn[i] != lastAnalogValue[i])
            {
            // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
            // more info: http://arduinomidilib.sourceforge.net/a00001.html
            MIDI.sendControlChange(1, potIn[i], 1);
            lastAnalogValue[i] = potIn[i];
            }  // end of not same as before
          }   // end of value changed
        }   // <----------------- add this

---

> If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:

Change:

    MIDI.sendControlChange(1, potIn[i], 1);

to:

    MIDI.sendControlChange(i, potIn[i], i);


body:
I am currently using the following code
<!-- language-all: lang-cpp -->

    #include <IRremote.h>

    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
     Serial.begin(9600);
     irrecv.enableIRIn(); // Start the receiver
    }

    void loop()
    {
     if (irrecv.decode(&results))
      {
       Serial.println(results.value, HEX);
       irrecv.resume(); // Receive the next value
      }
     }

The Serial Monitor is always returning "FFFFFFFF" no matter which button I press.
So I am unable to replicate the signal.

Seems that the IR library doesn't support my LG remote.

How do I save and replicate the signal in this case?

title: How do I save IR codes from my LG Air Conditioner remote and replay them?

Answers: 0


body:
I am trying to make a program for my Arduino that will run 4 motors with random actions (forward,backward,left,right) and execution is determined by a random number generator. When I compile there is no errors, and The COM port is connected correctly to my Arduino Mega, but when it uploads the log says this:

    Sketch uses 668 bytes (0%) of program storage space. Maximum is 253,952 bytes.

    Global variables use 9 bytes (0%) of dynamic memory, leaving 8,183 bytes for local variables. Maximum is 8,192 bytes.

That means only 677 B is being used, but the Arduino file is *6 KB*. I know that the program gets somewhat smaller when it is compiled, but not ten times smaller.

What's happening here?

**EDIT**

    // Arduino pins for the shift register
    #define MOTORLATCH 12
    #define MOTORCLK 4
    #define MOTORENABLE 7
    #define MOTORDATA 8

    // 8 bit bus

    #define MOTOR1_A 2
    #define MOTOR1_B 3
    #define MOTOR2_A 1
    #define MOTOR2_B 4
    #define MOTOR3_A 5
    #define MOTOR3_B 7
    #define MOTOR4_A 0
    #define MOTOR4_B 6

    // Motor pins:

    #define MOTOR1_PWM 11
    #define MOTOR2_PWM 3
    #define MOTOR3_PWM 6
    #define MOTOR4_PWM 5

    // LED Pins

    #define led_r 22
    #define led_l 23

    // Actions

    #define RIGHT 0
    #define LEFT 1
    #define FORWARD 2
    #define STOP 3

    // Codes for the motor function.
    #define GO 1
    #define REVERSE 2
    #define BRAKE 3
    #define RELEASE 4

    // Probability

    #define rProb 5
    #define lProb 5
    #define fProb 88
    #define stopProb 2

    // other globals

    #define defSpd 255

    void setup() {}

    void execute(int action) {

     if (action == FORWARD) {

      motor(1,FORWARD,defSpd);
      motor(2,FORWARD,defSpd);
      motor(3,FORWARD,defSpd);
      motor(4,FORWARD,defSpd);

      digitalWrite(led_r, LOW);
      digitalWrite(led_l, LOW);
     } else if (action == RIGHT) {

      motor(1,REVERSE,defSpd);
      motor(2,REVERSE,defSpd);
      motor(3,FORWARD,defSpd);
      motor(4,FORWARD,defSpd);

      digitalWrite(led_l, LOW);
      digitalWrite(led_r, HIGH);
      delay(150);

     } else if (action == LEFT) {

      motor(1,FORWARD,defSpd);
      motor(2,FORWARD,defSpd);
      motor(3,REVERSE,defSpd);
      motor(4,REVERSE,defSpd);

      digitalWrite(led_l, HIGH);
      digitalWrite(led_r, LOW);

      delay(150);

     } else if (action == STOP) {

      motor(1,BRAKE,defSpd);
      motor(2,BRAKE,defSpd);
      motor(3,BRAKE,defSpd);
      motor(4,BRAKE,defSpd);

      digitalWrite(led_r, HIGH);
      digitalWrite(led_l, HIGH);

      delay(1000);

     }

    }

    void loop() {
      // put your main code here, to run repeatedly:

      // Random action
      int i = (1, 101);

      if (i > 0 && i <= rProb) {

        execute(RIGHT);

      } else if (i > rProb && i <= rProb + lProb) {

        execute(LEFT);

      } else if (i > rProb + lProb && i <= rProb + lProb + fProb) {

        execute(FORWARD);

      } else if (i > rProb + lProb + fProb && i <= rProb + lProb + fProb + stopProb) {

        execute(STOP);

      }

    }

    void motor(int nMotor, int command, int speed)
    {
      int motorA, motorB;

      if (nMotor >= 1 && nMotor <= 4)
      {
        switch (nMotor)
        {
        case 1:
          motorA   = MOTOR1_A;
          motorB   = MOTOR1_B;
          break;
        case 2:
          motorA   = MOTOR2_A;
          motorB   = MOTOR2_B;
          break;
        case 3:
          motorA   = MOTOR3_A;
          motorB   = MOTOR3_B;
          break;
        case 4:
          motorA   = MOTOR4_A;
          motorB   = MOTOR4_B;
          break;
        default:
          break;
        }

        switch (command)
        {
        case GO:
          motor_output (motorA, HIGH, speed);
          motor_output (motorB, LOW, -1);     // -1: no PWM set
          break;
        case REVERSE:
          motor_output (motorA, LOW, speed);
          motor_output (motorB, HIGH, -1);    // -1: no PWM set
          break;
        case BRAKE:
          // The AdaFruit library didn't implement a brake.
          // The L293D motor driver ic doesn't have a good
          // brake anyway.
          // It uses transistors inside, and not mosfets.
          // Some use a software break, by using a short
          // reverse voltage.
          // This brake will try to brake, by enabling
          // the output and by pulling both outputs to ground.
          // But it isn't a good break.
          motor_output (motorA, LOW, 255); // 255: fully on.
          motor_output (motorB, LOW, -1);  // -1: no PWM set
          break;
        case RELEASE:
          motor_output (motorA, LOW, 0);  // 0: output floating.
          motor_output (motorB, LOW, -1); // -1: no PWM set
          break;
        default:
          break;
        }
      }
    }

    void motor_output (int output, int high_low, int speed)
    {
      int motorPWM;

      switch (output)
      {
      case MOTOR1_A:
      case MOTOR1_B:
        motorPWM = MOTOR1_PWM;
        break;
      case MOTOR2_A:
      case MOTOR2_B:
        motorPWM = MOTOR2_PWM;
        break;
      case MOTOR3_A:
      case MOTOR3_B:
        motorPWM = MOTOR3_PWM;
        break;
      case MOTOR4_A:
      case MOTOR4_B:
        motorPWM = MOTOR4_PWM;
        break;
      default:
        // Use speed as error flag, -3333 = invalid output.
        speed = -3333;
        break;
      }

      if (speed != -3333)
      {
        // Set the direction with the shift register
        // on the MotorShield, even if the speed = -1.
        // In that case the direction will be set, but
        // not the PWM.
        shiftWrite(output, high_low);

        // set PWM only if it is valid
        if (speed >= 0 && speed <= 255)
        {
          analogWrite(motorPWM, speed);
        }
      }
    }

    void shiftWrite(int output, int high_low)
    {
      static int latch_copy;
      static int shift_register_initialized = false;

      // Do the initialization on the fly,
      // at the first time it is used.
      if (!shift_register_initialized)
      {
        // Set pins for shift register to output
        pinMode(MOTORLATCH, OUTPUT);
        pinMode(MOTORENABLE, OUTPUT);
        pinMode(MOTORDATA, OUTPUT);
        pinMode(MOTORCLK, OUTPUT);

        // Set pins for shift register to default value (low);
        digitalWrite(MOTORDATA, LOW);
        digitalWrite(MOTORLATCH, LOW);
        digitalWrite(MOTORCLK, LOW);
        // Enable the shift register, set Enable pin Low.
        digitalWrite(MOTORENABLE, LOW);

        // start with all outputs (of the shift register) low
        latch_copy = 0;

        shift_register_initialized = true;
      }

      // The defines HIGH and LOW are 1 and 0.
      // So this is valid.
      bitWrite(latch_copy, output, high_low);

      // Use the default Arduino 'shiftOut()' function to
      // shift the bits with the MOTORCLK as clock pulse.
      // The 74HC595 shiftregister wants the MSB first.
      // After that, generate a latch pulse with MOTORLATCH.
      shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy);
      delayMicroseconds(5);    // For safety, not really needed.
      digitalWrite(MOTORLATCH, HIGH);
      delayMicroseconds(5);    // For safety, not really needed.
      digitalWrite(MOTORLATCH, LOW);
    }

title: Arduino Program uses less RAM then expected and doesn't run

Answers: 1

body:
What is:

    // Random action
    int i = (1, 101);

supposed to achieve?

    /tmp/untitled1/untitled1.ino: In function 'void loop()':
    /tmp/untitled1/untitled1.ino:110:13: warning: left operand of comma operator has no effect [-Wunused-value]

Ergo, `i` is always going to be 101.  So all the `if` constructs will be false, so they get optimized out (they are all constants).  Because of that the other functions are never getting called, so they are optimized out.

So you are left with next to nothing.

I think you may have missed the word `random` out from there...

* Program size: 2798 bytes
* Memory size: 17 bytes
* Compilation took 0.227 seconds


body:
I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin `HIGH` and reading the input on the other pin and then swapping. With both pins set to `OUTPUT` I can still read in values with `analogRead()` without having to keep switching pin modes.

My question is why is that the case? What is the point of setting a pin to `INPUT` if `OUTPUT` can still read in values? Are there any disadvantages of doing so?

title: Why should a pin be set as an input if it can read input when set as output?

Answers: 4

body: The reason for this is because `analogRead()` has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of *digital* operations - i.e., when using `digitalRead()` and `digitalWrite()`.  When using `analogRead()` the Arduino code switches the pin into analog mode first and then reads from it.

body: Because I/O pins can be used for either digital input or digital output and can be switched to perform in a given direction. Some of the pins also have an analog capability, either A-to-D conversion (input) or PWM (kind of a psuedo-analog output) but only in one direction permanently assigned by the hardware and therefore not switchable from one to the other.

body:
> My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

If you do a `digitalRead` you can read the current latched state of an **output** pin (it doesn't change it to input). In other words, you read what was last written to it.

If you do a `digitalWrite` of HIGH to an **input** pin it sets the internal pull-up. If you write LOW it disables the internal pull-up. If it switched it to output for you, you wouldn't be able to enable or disable the pull-up. (Note: this applies to older versions of the IDE, newer ones have a pinMode setting of INPUT_PULLUP).

>  What is the point of setting a pin to INPUT if OUTPUT can still read in values?

That certainly won't work with `digitalRead` because you are writing a value to the pin in OUTPUT mode, so you will merely read back what you are writing. In other words, you have activated the driver transistors, which will override whatever value you are trying to read.

body: It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.