3-Way Bluetooth Communication? I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?

To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.

I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.

Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.

Thanks a lot!

Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.


How to program a CAN-BUS Arduino shield to control car windows? My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.

Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?

CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039

Arduino Mega: https://www.sparkfun.com/products/11061

What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.


Is there a way to have the LED switch on after 10 readings or say a minute? I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.

I have tried doing various if loop much to my failure, below is the code I am currently using:

#include <RFID.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED_PIN A0

RFID rfid(SS_PIN, RST_PIN);
int serNum[5];
String cardno;
int interval = 15000; // millisec
long now = 0;
long lasttime = millis();
// change Reader ID to your name
String readerID = "Reader_001";

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
  pinMode(A0, OUTPUT);
}

void loop() {
  now = millis();
  if (now > lasttime + interval) {
    lasttime = now;
    Serial.print(readerID);
    Serial.print(":");
    Serial.println("I am alive");
  }
  if (rfid.isCard()) {
    if (rfid.readCardSerial()) {
      lasttime = now;
      cardno = String(rfid.serNum[0]) +
               String(rfid.serNum[1]) +
               String(rfid.serNum[2]) +
               String(rfid.serNum[3]) +
               String(rfid.serNum[4]);

      Serial.print(readerID);
      Serial.print(":");
      Serial.println(cardno);
    }
  }
  rfid.halt();
  delay(10000);
}

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:

Inside your void loop() function you use the millis() coding style (refer to the BlinkWithoutDelay example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:

#define READ_INTERVAL 10000
int read_counter = 0;
unsigned long read_timestamp=0;
String last_identifier="";
void loop(){
    if(millis()-read_timestamp>READ_INTERVAL){
        // Read the chip
        if(card_identifier == last_identifier)
            read_counter++;
        else
            read_counter = 1;
        if(read_counter>=12){
            digitalWrite(LED_PIN, HIGH);
        }
    }
}

Be sure to use unsigned long with the millis() function, to prevent it from overflowing to a negative value.


Reading values from SQL Arduino ethernet I'm about to do this project where I will make some lights flash up depending on some values that are in an SQL database on a server. I have already bought my Arduino and waiting for it to arrive. But I've been stuck at how to read the SQL data from the Arduino, connected to ethernet only.

Is there a library where I can select from the database directly or do I have to make a web service, in which I can make a http request to when needed?

If it's a web service, can I be directed to some examples of this being used with Arduino? I've been looking around the past few days but haven't been able to find a decent example.

Best regards and thanks a lot in advance for your time! :-)

I would make a small http REST API on your SQL server. The Arduino could use the API to get the data.
The API can easily be done in php, ruby or whatever.


Arduino connected keypad printing wrong numbers Going crazy here trying to connect a keypad to my Arduino. I followed this article KeypadTutorial, but my guess is something is wrong/different because my keypad only has 9 pins and the far left (pin 1) and far right (pin 9) pins have no traces back to the keypad. I bought it years ago and just got around to finding a use for it. It looks just like this one Arduino Keypad but different with white keys with black font.

The issue is the wrong key shows up (i.e. press 0 and get 9). I used a multi-meter to test for continuity between pins when pressing each key and got results that are kind of stumping me. I would think there would be some kind of pattern (like the first pin would always be a 1, 2, or a 3), but obviously not (or I just have a bad keypad).

KEY(pin1, pin2)
1(2,3)
2(1,2)
3(2,5)
4(3,7)
5(1,7)
6(5,7)
8(1,6)
9(5,6)
0(1,4)
#(4,5)
*(3,4)


How can I execute a shell command? This page says to run a shell command I need a "proxy code" running on my computer (Linux Ubuntu). What do they mean by this, and how should I make one?

I'm not familiar with the term proxy code, but I'm assuming that it's a piece of code on your computer that acts as a man in the middle.

You cannot directly use Arduino to run a shell command, so you'll need to create a program on your computer that listens to serial and then executes a command.

For the "proxy code" Python would be a good choice because of the pySerial library that plays nicely with Arduino. It seems fairly easy to execute a shell command with Python.

As per the Arduino code, something like this would work good:

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

loop() {
  if(state == true) {
    Serial.print('A');
  }
}


Wifi REST API GET call - how to concatenate and pass URL parameters? I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.

In curl this works:

  curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C

So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.

sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
Serial.println(request);

When I print the request, everything after the & gets truncated.

  char serverName[] = "access.alchemyapi.com";
  if(client.connect(serverName,port) == 1)
  {
    sprintf(outBuf,"GET %s HTTP/1.1",page);
    client.println(outBuf);
    sprintf(outBuf,"Host: %s",serverName);
    client.println(outBuf);
    client.println(F("Connection: close\r\n"));
  }

This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.

Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use client.print() (or equivalent) to output each part of the request in sequence. For example:

client.print("GET ");
client.print(page);
client.print(" HTTP/1.1\r\n");

client.print("Host: ");
client.print(serverName);
client.print("\r\n");

// etc.

That should let you output any combination of HTTP headers you need.


Does the Arduino Uno have two crystals? Take a look at this picture:

I think most of use agree that the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently.

I was bored so I looked at my Arduino Uno, and saw that it has what seems like another crystal (yellow). It looks like the one that is on the Pro Mini. It's also located near the XTAL pins. After I inspected the schematic a second time, it also appears that there are two crystals on the board.

Which one out of those two is actually connected to the XTAL pins and why are there two?

The ceramic resonator in yellow is connected to the main MCU, and the crystal in red is connected to the other MCU. USB requires tighter tolerances than is available from a resonator therefore a crystal must be used instead.


Which Arduino-Board do I need? I want to use a single Arduino board and link it to both the ANALOG CO2 GAS SENSOR (MG-811 SENSOR) and ANALOG PH SENSOR - METER KIT. I was wondering if the Uno Rev 3 had enough pins or do I have to go with the Mega.

Nano board has a bunch of analog and digital pins. It does good and cheap. But for convenience UNO board is preferable for its large size easy handling and easy pin and wiring management.


How to upload code to atmega32u4? I recently created a pcb with the atmega32u4 to use it as a development board. The controller is connected to a micro usb port. Should I install the arduino bootloader instead of the deafult one? Or keep the default boot loader and find another way of flashing hex files? But bottom line what is the process to flash a hex file to the atmega32u4 via usb?

Installing the Arduino bootloader would make it easier to upload you sketch from the Arduino IDE.
Installing the Arduino bootloader via DFU is probably the easiest method. Alternatively use ISP, but you'd need a programmer for that, or use a separate Arduino board with the ArduinoAsISP sketch running on it.


Cannot use radio transmitter after switching to LowPower library My Arduino Mini board has DHT22 temperature sensor and 433MHz radio transmitter modules. I'm using DHT and RCswitch libraries to make use of them. Code looks like this:

void setup() {
  tempSwitch.enableTransmit(RADIO_PIN);
  dht.begin();
}

void loop() {
  float temp = dht.readTemperature();

  unsigned long message = createTemperatureMessage(SENSOR_ID, temp);
  tempSwitch.send(message, 32);

#ifdef MY_DEBUG
  unsigned int sleepCount = 1;
#else
  // 3600s / 2 / 8s == 225
  unsigned int sleepCount = 225;
#endif
  for (; sleepCount > 0; sleepCount--) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

So I'm reading temperature and sending it using RCswitch library. Initially I just had delay(1000); instead of fancy LowPower sleep loop but I wanted to make my "device" more battery-friendly so I switched to low-power sleep.

The problem is that now Arduino is only sending data first time and after sleeping 30 minutes (in "release" mode) it does not send anything anymore. If I reduce 30 minutes to 8 seconds it is capable of sending data as well as if I replace sleep with delay(30*60*1000);.

From beyond it looks like something is not caching up after the sleep. Do I need to "wake" radio module in any special way? How to fix that?

I've never tried this, but if you are putting the Arduino to sleep I would expect it to cut power to the devices (does it?) if it does then after a 30 minute sleep I would expect the devices to come back up in the initial state.  Guessing by your code the initial state of the radio is Tx Disabled, so try moving the

tempSwitch.enableTransmit(RADIO_PIN);

to before the

float temp = dht.readTemperature();

line.

I'd also be concerned that the DHT22 is not in the correct state after you wake up.

Can you try doing a 1 second LowPower sleep in debug mode, I suspect it would work more often.


How to make timed loops after switch / case? I am working on a code, which is running a function once a second:

switch (gearbox1) {
  case 1:
    //manually close
    Serial.println("Closing1");
    digitalWrite(gear1OpenPin, OFF);
    t.setTimer(1000, Close1, 1);

    break;

  case 2:
    //manually open
    Serial.println("Opening1");
    digitalWrite(gear1ClosePin, OFF);
    t.setTimer(1000, Open1, 1);

    break;

This part is working fine. But then i want at case 10: call function autoClose() which would work in 10 second cycles.

Struggle is, as my first function is called once a second, it is starting function autoClose() once a second as well. How can I overcome this please?

At the moment I have current, non working code:

  case 10:
    //automatic close
    Serial.println("A Close1");
    digitalWrite(gear1ClosePin, OFF);
    digitalWrite(gear1OpenPin, OFF);

    t.enable(autoClose);
    autoClose();
    break;

Edit: Added minimal possible code. I want autoOpen() and autoClose() to loop in 10 sec. intervals.

#include <SimpleTimer.h>
SimpleTimer t;
int gearbox1;

#define gear1OpenPin 44
#define gear1ClosePin 46

int OFF = HIGH;  // states for relays
int ON = LOW;

byte gear1Open = 0;
byte gear1Close = 0;

void setup() {

  t.setInterval(1000, Control1);
  int autoOpen = t.setInterval(10000, autoOpen);
  int autoClose = t.setInterval(10000, autoClose);
}

void loop() {

  t.run();
}

void Control1() {
  //*****************************************
  switch (gearbox1) {
    case 1:
      //manually close
      Serial.println("Closing");
      digitalWrite(gear1OpenPin, OFF);
      t.setTimer(1000, Close1, 1);

      break;

    case 2:
      //manually open
      //   Serial.println("Opening");
      digitalWrite(gear1ClosePin, OFF);
      t.setTimer(1000, Open1, 1);

      break;

    case 5:
      //stop
      Serial.println("Stopping");
      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);

      break;

    case 10:
      //automatic close

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      if (t.isEnabled(autoClose)) {
        autoClose();
      } else {
        t.restartTimer(autoClose) ; t.enable(autoClose);
        autoClose();
      }
      break;

    case 20:
      //automatic open

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      t.restartTimer(autoOpen); t.enable(autoOpen);
      autoOpen();
      break;
 }
}

void Open1() {
  digitalWrite(gear1OpenPin, ON);
}
//**********************************************
void Close1() {
  digitalWrite(gear1ClosePin, ON);
}
//**********************************************
void autoOpen() {

  if (gear1Open == ON) {
    gear1Open = OFF;
  } else {
    gear1Open = ON;
  }
  digitalWrite(gear1OpenPin, gear1Open);
}
//**********************************************
void autoClose() {
  if (gear1Close == ON) {
    gear1Close = OFF;
  } else {
    gear1Close = ON;
  }
  digitalWrite(gear1ClosePin, gear1Close);
}

Create a new variable to hold the state of whether or not you are in autoClose mode:

uint8_t inAutoClose=0;

Then, add a line in your switch statement to set that flag when you enter that state, but not call the function if you were already in that state:

case 10:
  //automatic close
  Serial.println("A Close1");
  digitalWrite(gear1ClosePin, OFF);
  digitalWrite(gear1OpenPin, OFF);
  if (!inAutoClose) {
    inAutoClose = 1;
    t.enable(autoClose);
    autoClose();
  }
  break;

Add a line in your other switch branches to clear that flag:

case 1:
  //manually close
  inAutoClose = 0;
  [...]

If you want autoClose() to be called every 10 seconds repeatedly as the "idle" state, then you need to clear inAutoClose (set it to zero) at the end of every 10 second period. How and where you do that depends on other factors you haven't shown, like what autoClose() does, or what the timer you enable does.

Side note: avoid naming your timer name (autoClose) and your function name autoClose() the same! Does your code compile that way? It ought to throw an error.

ANSWER 2 (based on comments)

Your auto-close state is described as

  Turns on for 10 seconds, after that off for 10 seconds.

This can be accomplished with a similar structure to what you have now, with a few changes. (These are my suggestions, but by no means the best or worst way.)

Edit your open and close functions:

void Open1() {
  digitalWrite(gear1OpenPin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Close1); // Sets a timer to call closer in 10s
   }
}

void close1() {
  digitalWrite(gearClosePin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Open1); // Sets a timer to call opener in 10s
  }
}

When you call either Open1() or Close1(), if your auto-open flag is set, then 10s later, the opposite function is called, and this keeps chaining together, every 10s.

Whenever it's time to stop this, you clear the isAutoOpen flag and disable the timers. You may wish to keep track of the timer ID that is created with the setTimeout() function, so you can disable it at any time to avoid the system going through the cycle one more time after you clear the flag.


Send a polymorphic object over serial I am sending a polymorphic object over serial between two Arduinos. The transmission should be fine, indeed if on the receiver side I static_cast the pointer to the Derived class it works properly. On the other hand if I try to call virtual functions on the Base pointer, Arduino resets. What is causing this behaviour?

Some samples of the code follows.

Sender:

RS485_Serial bus;
void loop ()
{
  Random r(1); //targeting device 1 in the bus
  if (r.request(bus)) { blink(r.val); } //make a request for a random number
                                        //blink the led the given number of times

  delay(1000);
}

Receiver:

RS485_Serial bus;
bus.set_address(1);
void loop ()
{
  listen(bus);
}

Selected common parts:

struct Action {
  byte target_address;

  Action(byte addr): target_address(addr) {}
  virtual ~Action() {}

  virtual size_t size() const { return sizeof(*this); }
  virtual int  vrequest(RS485_Serial &) = 0;
  virtual void vrespond(RS485_Serial &) = 0;

  int request(RS485_Serial & bus) {
    bus.write(reinterpret_cast<byte*>(this), size());
    return vrequest(bus);
  }
  void respond(RS485_Serial & bus) {
    vrespond(bus); // <--- This virtual call makes the sender reset
  }
};

struct Random: Action {
  size_t size() const override { return sizeof(*this); }
  int val;
  Random(byte address): Action(address) {}

  int vrequest(RS485_Serial & bus) override {
    return bus.read(val);
  }
  void vrespond(RS485_Serial & bus) override {
    bus.write(static_cast<decltype(val)>(random(2,5)));
  }
};

void listen(RS485_Serial & bus) {
  byte * data = nullptr;
  byte length = 0;
  if ( bus.read(data, length) ){
    Action & a = *(reinterpret_cast<Action*>(data));
    if (a.size() == length) blink(3);
    if (a.target_address == bus.address) {
      a.respond(bus);
      //static_cast<Random*>(&a)->vrespond(); works but it has no point
    }
  }
}

My doubt is that if the vtable is stored in different positions, than the vtable pointer in the object obtained by the receiver will be off, causing the crash.

I think http://stackoverflow.com is the correct forum for your question. Your problem is how to serialize/deserialize correctly an object in C++.

An easy way to do it is simply send the values (not the object) and recreate the object at the other side. So, now your problem is reduced to send and receive a bunch of int's, float's, string's, whatever.

Why you want/need to do that?


Displaying multiple effects in Fast LED I want to implement three effects which display every 5 seconds. I know that using delay() is not a good method so I want to use milis(). Duration times of the effects are different from each other. How can I assure "non-freezing" or displaying 2 or 3 effects at the same time? Should I measure the time of display of every effect and on its base adjust intervals or is there another solution? What do you think?

EDIT:

Here is my code:

void loop() {
   unsigned long currentMillis = millis();

   if(currentMillis - previousMillis >= interval) {
     previousMillis = currentMillis;
     i++;

    switch (i){
      case 1:
        meteorRain(0xff,0xff,0xff,10, 64, true, 30); // efekt spadającej gwiazdy
        Serial.print("meteorrain: ");
        Serial.print(previousMillis);
        Serial.print("\n");
        break;

      case 2:
         colorWipe(0x90,0x90,0x90, 50);
         colorWipe(0x00,0x00,0x00, 50);
         Serial.print("colorwipe: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;

      case 3:
         MyEffect();
         Serial.print("My effect: ");
        Serial.print(previousMillis);
        Serial.print("\n");
         break;
    }
    if (i>3) i=0;
    }
}

I've ommited the code of effects (it doesn't matter, I think).

I'd take a look at Mark Kriegsmans FastLED example "DemoReel100". This example shows how to delegate to multiple functions.

First, I'll explain that example a bit: You set up an array of function pointers plus a variable for the current index.

typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };
uint8_t gCurrentPatternNumber = 0;

All the functions (rainbow, juggle, etc) just need to work on your leds[] array that you gave to FastLED.addLeds() in your setup() -- I assume that your functions already fulfill that requirement. But: All functions must have the same argument list (in this case: they must be defined like void rainbow() { leds[x] = CHSV(a,b,c); }), so you might need to wrap them in another function.

Then, in your loop, you call your effect functions like this while calling nextPattern() every 10 seconds:

void loop()
{
  // Call the current pattern function once, updating the 'leds' array
  gPatterns[gCurrentPatternNumber]();

  // send the 'leds' array out to the actual LED strip
  FastLED.show();
  // insert a delay to keep the framerate modest
  FastLED.delay(1000/FRAMES_PER_SECOND);

  // do some periodic updates
  EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
}

#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
void nextPattern()
{
  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
}

EVERY_N_SECONDS is a macro defined in the FastLED library; it basically does what you did with currentMillis, previousMillis and interval (There's also EVERY_N_MILLISECONDS and some other related macros).

That's the example so far, now we need to work with differing "effect switch times".

The easiest method in code would be to find the greatest common factor of all switch times -- let's say you want the rainbow() effect to last for 10 seconds, the juggle() effect for 15 and the bpm() effect for 5 seconds. All those switch times are a multiple of 5, so we put that as the switch delay: EVERY_N_SECONDS(5). Now, to get higher runtimes, we just put those functions multiple times into the array:

SimplePatternList gPatterns = { rainbow, rainbow, juggle, juggle, juggle, bpm };

There's another way, which gives you the option of setting the effect durations directly. First, we need an array of durations of the same length than our effect function array and a variable to remember where we are in the durations:

SimplePatternList gPatterns = { rainbow, juggle, bpm };
int[] gPatternDurations = { 10, 13, 73 };
int effectDurationLeft = gPatternDurations[0];

Then, we reduce the "effect switch resolution" down to 1 second and put a bit of logic around the nextPattern() call:

  EVERY_N_SECONDS( 1 ) {
    if( effectDurationLeft == 0 ) {
      nextPattern();
      effectDurationLeft = gPatternDurations[gCurrentPatternNumber];
    } else {
      effectDurationLeft -= 1;
    }
  }

Now you could set your pattern durations by editing the gPatternDurations array.

Please be aware that I did not test the code above. Syntax Errors may occur :)


If an I2C connection is lost for a short period of time will it work if the connection is live again? I'm using an ESP8266 with the Arduino library to read from a sensor(MPU9250 specifically). The readings are done via I2C but I'm using a library that abstracts these methods.

The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).

A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.

So to clearly answer your questions:

You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to this site for further information about I2C. It also gives some advice if your bus is blocked.


SoftwareSerial data not available Second time I'm asking the same question with no solution, let me elaborate in other way for clarity.

I wrote an Arduino program which uses two serial ports, one is hardware serial port and other is SoftwareSerial port.

No problem with hardware serial port, the problem is with software serial port.

The software serial port's Tx pin works but Rx pin does not work, i.e. portone.available() is always zero, nothing in the input buffer of the software serial port.

I'm using Arduino IDE 1.6.12 with an Uno board. Previously I used version 1.6.9 but neither works. Here is the piece of code:

#include <SoftwareSerial.h>

String code = "", customer = "";
bool complete = false;
byte c = 0, j = 0;
char customercode[27];
SoftwareSerial portone(10, 11);
void setup() {
  Serial.begin(9600);
  portone.begin(115200);
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  if (Serial) {
    Serial.print("Connecting");
  }
}

void loop() {
  String copy = "";
  char inchar = '0';

  if (Serial.available() > 0) {
    while (Serial.available()) {
      char bytes = (char)Serial.read();
      if (bytes == '1' || bytes == '2' || bytes == '3' || bytes == '4' || bytes == '5' || bytes == '6' || bytes == '7' || bytes == '8' || bytes == '9' || bytes == '0' || bytes == '.' || bytes == '-' && bytes != '#') {
        customercode[c] = bytes;
        c++;
      } else if (bytes == '#') {
        complete = true;
      }
      if (c > 12 && bytes != '#') {
        code += bytes;
      }
    }

    if (c == 13) {
      customer += '+';
      for (byte i = 0; i < 12; i++) {
        customer += customercode[i];
      }
    }
  }
  portone.listen();
  if (portone.available() > 0) {
    portone.println("AT+CMGF=1");
    portone.println("AT+CNMI=2,2,0,0,0");
    portone.flush();

    while (portone.available()) {
      inchar = (char)portone.read();
      copy += inchar;
    }
    delay(1);
    Serial.print(copy);

  } else if (complete == true && customercode != "" && code != "") {
    sending();
  }
  Serial.print(portone.available());
  delay(1000);
}

Don't call portone.listen().  That method is only necessary when you have created multiple SoftwareSerial ports.  It specifies which port you are listening to, because only one of them can receive at a time (you can transmit on any of them at any time).  It also empties the receive buffer so that data from one SoftwareSerial port is not mistakenly returned by another.  In your code, this empties the input buffer before checking portone.available().  Surprise, it's always empty!  ;)

Also, don't set the pin mode of the pins used for the SoftwareSerial object.  The pin modes were set during the constructor of portone, which happens before setup.  You're messing with pins that have been "promised" to that library for its own use and control.

As Edgar suggested, you should consider a more-efficient software serial library.  AltSoftSerial is best, but is only available on certain pins.  My NeoSWSerial library is next best, and works on any two pins, but only at 9600, 19200 and 38400.  Both of those libraries can transmit and receive at the same time, unlike SoftwareSerial.  Here is an answer with all the gory details.

And you really should ditch the String class usage.  You obviously know how to use char arrays (aka "C strings").  We can't see the sending() function, but you can probably just print a few pieces instead of building a complete String and printing it:

    portone.print( '+' ); // leading plus sign
    portone.write( (uint8_t *) customerCode, 13 ); // array of bytes, length

It would be better to terminate the character arrays with a zero byte (NUL-termination) in loop so they can be used as a standard C string instead of a byte array:

    customerCode[14] = '\0'; // NUL-terminate the C string

Then you can use the standard C string print in sending:

    portone.print( '+' ); // leading plus sign
    portone.print( customerCode );

Printing the pieces is always more efficient than building a big buffer with all the pieces.  This avoids copying the pieces and needing twice as much RAM.     :P


Can't read PWM signal from 2-pin fan header I'm trying to get PWM values from a 2-pin fan header on DuetWifi board (it is a 3D Printer Controller Board). Here is some info about the fan connection on that board.
From their forum, I got to know that fan output is open-drain and can operate with frequency up to 65535 Hz (frequency for each fan is configurable).
First of all, I connected Duet FAN- to Arduino D7 and tried that code:
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT_PULLUP);
}

void loop() {
  duration = pulseIn(pin, HIGH);
  Serial.println(duration);
}

But it shows constant readings between 6-7 in Serial Monitor:
7
6
7
7
7
7
7
6
6
7

Also, any fan speed adjustment in the Duet UI doesn't affect those readings as well.
After that, I have tried a lot of different libraries and codding approaches from Arduino forum to get suitable PWM readings from FAN- pin, but have no luck.

Your picture shows that you have only connected one line to the Arduino.  You do not have a common ground between the Arduino and the fan controller.  You need to connect the grounds together.
Voltage is like height, it requires two points to measure.  If I point at a hill and I say, "How high is that hill?" that seems like a pretty easy question to answer at first.  But it becomes ambiguous quickly.  Do we want to say how high it is compared to the ground around it?  Or how high from sea level?  Or how high from where we are standing?  You simply can't say how high a hill is unless you agree on where to measure from.
It's the same with voltage.  You can't measure a voltage unless you have a potential that you can consider the 0 point to measure from.  That 0 point is the ground wire.  And as you have drawn the circuit the two boards don't agree on where they will consider 0 volts.


Johnny Five LCD: black boxes only I posted this also at Stack Overflow. I have tested the Johnny Five LED example on my Arduino Uno, and it worked fine. Now I need to test Johnny Five LCD. I connected all wires correctly.

The code:

var five = require("johnny-five"), board, lcd;

board = new five.Board();
board.on("ready", function() {
  lcd = new five.LCD({
    // LCD pin name  RS  EN  DB4 DB5 DB6 DB7
    // Arduino pin # 7    8   9   10  11  12
    pins: [7, 8, 9, 10, 11, 12],
    backlight: 6,
    rows: 2,
    cols: 20
    // Options:
    // bitMode: 4 or 8, defaults to 4
    // lines: number of lines, defaults to 2
    // dots: matrix dimensions, defaults to "5x8"
  });

  // Tell the LCD you will use these characters:
  lcd.useChar("check");
  lcd.useChar("heart");
  lcd.useChar("duck");

  // Line 1: Hi rmurphey & hgstrp!
  lcd.clear().print("rmurphey, hgstrp");
  lcd.cursor(1, 0);

  // Line 2: I <3 johnny-five
  // lcd.print("I").write(7).print(" johnny-five");
  // can now be written as:
  lcd.print("I :heart: johnny-five");

  this.wait(3000, function() {
    lcd.clear().cursor(0, 0).print("I :check::heart: 2 :duck: :)");
  });

  this.repl.inject({
    lcd: lcd
  });
});

But it doesn't output as expected. It is showing one row of black boxes only. what have I missed?

Try changing the resistance in your 10k potentiometer. This might be a reason for the black boxes.

P.S: I.m a beginner too.


Is there a better way to combine if statement with an ISR? In my sketch when an interrupt gets triggered, a state variable is toggled from high to low and vice versa. Depending upon the variable state I have an if statement in the main loop that will call alarm_On function if state is high and the else part of the conditional statement will call alarm_Off function if the interrupt is triggered a second time. Thus I want this if condition to run only when the interrupt is triggered. In all other circumstances I want to run other code but if it concerns the same components e.g. the leds, the other code doesn't execute. If it's not a common component then it works fine. How can I overcome this "common component" issue?

 // Analog Input devices
# define humiditySensor A5

// Alarm input
# define alarmButton 2 // Pushbutton

// Output Devices
# define redLed 10
# define yellowLed 11
# define greenLed 12
# define waterPump 9 // LED on relay
# define spk 5

// Variables
volatile byte alarm = LOW;

void setup() {
  pinMode (alarmButton, INPUT);
  pinMode (redLed, OUTPUT);
  pinMode (yellowLed, OUTPUT);
  pinMode (greenLed, OUTPUT);
  pinMode (waterPump, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(alarmButton), ISR_Alarm, RISING);
  Serial.begin(9600);
}

void loop() {
  if (alarm == 1) {
    alarm_On();
  } else if (alarm == 0) {
    alarm_Off();
  }
  int humVal = analogRead(humiditySensor);
  Serial.println(humVal);
  if (humVal >= 500) {
    digitalWrite(redLed, HIGH);
  } else {
    digitalWrite(redLed, LOW);
  }
} // void loop

void ISR_Alarm () {
  alarm = !alarm;  // toggle alarm function if pushed more than once
}

void alarm_On() {
  tone (spk, 100);
  digitalWrite(waterPump, HIGH);
  static byte ledState = LOW;
  static unsigned long oldTime = 0;
  if (millis() - oldTime >= 250) { // loop to blink leds in emergency
    oldTime = millis();
    if (ledState == LOW) {
      digitalWrite(redLed, HIGH);
      digitalWrite(yellowLed, HIGH);
      digitalWrite(greenLed, HIGH);
      ledState = HIGH;
    } else {
      digitalWrite(redLed, LOW);
      digitalWrite(yellowLed, LOW);
      digitalWrite(greenLed, LOW);
      ledState = LOW;
    }
  }
} // end of alarm on function

void alarm_Off () {
  noTone (spk);
  digitalWrite(redLed, LOW);
  digitalWrite(yellowLed, LOW);
  digitalWrite(greenLed, LOW);
  digitalWrite(waterPump, LOW);
} // end of alarm off function

void high_Humidity() {
  digitalWrite(waterPump, HIGH);
}

void low_Humidity() {
  digitalWrite(waterPump, LOW);
}

Your code is not blocked, but ON or OFF are called each loop so your change are to the "common" components are overwritten quite fast.

Do not track the state within the IRQ. You could do something like:

volatile byte alarm = 1;
byte alarm_state = 1;

void ISR_Alarm () {
    alarm = 1;
}

void loop() {
    if (alarm){
        alarm = 0;

        if (alarm_state) {
            alarm_state = 0;
            alarm_Off();
        } else {
            alarm_state = 1;
            alarm_On();
        }
    }

    // other code
}


Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT I upload a blank sketch: pin 13 LED is on. Why?
I connect pin 13 to GND: it turns off until I remove the connection
I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed
I press hard reset: LED blinks a few times, turns off for a second then turns on
I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on
I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V
I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?
I swear it wasn't like this a few days ago.

The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

  Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.

You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.


Accessing multiplexed I2C and UART pins of STM32F103 in arduino IDE I want to access both of the multiplexed I2C and UART pins in the same program. I am programming in Arduino IDE.Can anyone please tell me how to access same pins for different functionalities?

In order to use two different peripherals on the same pins, you have to initialize I2C and de-intialize UART when using I2C and doing the opposite when using UART.

It’s not possible to initialize two different peripherlas on the same pins, concurrently.


Is it possible to overclock the baudrate from the mega to 230400 bps? i have a Arduino Mega 2560 and want send data with 230400bps to my laptop without any framingerror.

I want send the data over USB with serial.print ist that possible or must i use the ethernet?

When that is possible it will be really nice when someone can write what i have to do.

With friendly wishes sniffi

Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).

Simply choosing 250000 bps will remove this error.

Cheers!


Power measurement on Pins as a project I have to build a sensor hub based on Arduino. I need a couple of sensors like gyroscope, barometer, etc. This is no problem so far. The problem arises when it comes to power measurement. We have to measure the power consumption of the Arduino AND all the sensors. Sure, I could use a sensor like the Adafruit INA219 sensor. But this only gives the total consumed power of the Arduino and the sensors.

Is it possible to measure the energy, say, for every pin on the Arduino?

"Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with."

"it possible to measure the energy, say, for every pin on the Arduino?"

You ask if it possible to measure the energy- yes it is-or at least an approximation. The basic solution is as follows. Suppose you want to find the energy consumed by some component at one pin.  Energy is measure in joules. For an electrical circuit we the amount of energy (consumed in 1 second) is given by the formula

joules=current X voltage.
Lets consider the case with one sensor first , lets refer to this as sensor A.
The amount of energy that electrical component consumes in some time duration is by sensor A is:

joules (use by sensor A)=current X voltage X time duration sensor A is on

Now to make this formula applicable to your answer- we can replace voltage by the average voltage, and current by average current, since this is mathemtically equivalent, that the component is on for, and the time duration would be the time the component is on for. So the equivalent formula that can be used is

joules= average current X average voltage of sensor A during time duration X time duration sensor A is on

So for example if the sensor is only ever used for 50 minutes for all time throughout your project- and the sensor is turned on at the arduino pin for 1 second for every minute of that 50 minutes then the energy used by that sensor on that specific pin is equivalent to leaving the pin on for 50 seconds at the average voltage and average current of that sensor. Say the average voltage is 3v then the energy and average current is 20ma. Then the energy used by that sensor is thus
3v*0.02amps*55 seconds=3.3 joules.

Thus to get the total energy (if there were two sensors A and B) you would just need to sum

(joules (use by sensor A)= current of A X voltage of A Xtime duration sensor A is on)+(joules (use by sensor B)=current of B Xvoltage of B Xtime duration sensor B is on.)

Similar formula for more sensors.

To sum up- basically you would need your arduino program to keep track of how long each sensor pin is on (assuming high voltage turn on the sensor and makes it use power, low voltage turns off the sensor or make it use no power)  for each of the time duration in the formula for the duration of the project, you would need an estimate of the average voltage and current (e.g. from data sheet) or another way. Then you would need to use the formula in your code to compute the energy used by each sensor and the total energy.
If you have a way to measure the voltage and current fast enough then you could use them measurement instead of using average value as explained above-but I guess using averages is the easiest way to do it.

.


AT command to put the A6 GSM/GPRS into sleep / power down The general AT command for sleep mode (for the SIMCOM GSM modules) is AT+CSCLK=1 (or AT+CSCLK=2). I have given both a shot but they don't work with the A6 module. Does anyone know of any other command that does the same? The manufacturers claim that it can function at very low current levels when in sleep. But sadly they don't mention the sleep AT command.

A6 module uses a hardware pin (INT/GPIO_1) or (EN) enable on some modules.
There is no AT command as in the SIM900.


Send numbers bigger than 256 by SPI How can i send numbers like 300 or 1024 ?

I'm using the recommendation of the atmel's manual.

void SpiTransmitir(unsigned char data)
{
   SPDR = data;
   while(!(SPSR & (1<<SPIF)));//{Serial.println("While");}
}

I imagined that one bit shift could be the solution, but it still fails.

You need to send two bytes - a high byte and a low byte.

There are two things you need to know with SPI:

You must wait for one byte to finish transmitting before you send the next
The whole transaction needs to be wrapped with a digital chip select signal.

So you have:

Chip Select idles HIGH
You lower Chip Select
You send one byte
You send the other byte
You raise chip select

At the receiver you:

Wait for chip select to go low
Receive one byte
Receive a second byte
Chip Select rises
You combine the two bytes together into one integer.


How to control a DC motor via Arduino Uno as a slave and Mega 2560 as master? Hi I want to control a DC motor using Arduino mega2560 and Arduino Uno as a slave. Mega have to process data from an ultrasonic sensor(measuring distance) and control the motor based on the input. I tried to google but couldn't find a better tutorial or code. I'm using Adafruit motor shield l293d. I have the idea about the wiring part just need a simple code.

Eg:

 if( distance < 20) {
   //send signal to slave to run the motor forward
 }else {
   //send signal to slave to stop the motor
 }

Serial is quite easy to implement and use the SoftSerial.

Example code for serial can be found in the Arduino IDE under the menu:

File | Examples | 04. Communication


esp8266 advertising AP even when flashed with custom firmware I bought several ESP8266 boards from an Amazon seller, and I have flashed them with custom firmware.  This firmware basically sends telemetry to an MQTT server, and has some OTA functionality to self-update from a web server I run.

I flashed them from the Arduino IDE initially, although have also since updated them OTA.

These devices properly connect to the AP I have defined, get an address, and send their mqtt messages.  However, they ALSO advertise an SSID that is FaryLink_XXXXXX where the XXXXXX relates to the MAC.

How is this possible, and how should I wipe their little brains fully?

The Espressif ESP8266 SDK is part of every Arduino sketch for the ESP8266. The SDK handles the WiFi and other basic functions of the chip.

If enabled, the SDK remembers WiFi STA and SoftAP settings and start to connect right after boot. At default it is enabled. In Arduino sketch this is controlled by WiFi.persistent(bool) and of course this setting is stored too.

To clear SoftAP settings, call WiFi.softAPdisconnect(). To only turn off SoftAP, use WiFi.setMode(WIFI_STA).


Communication Protocol Best Practices and Patterns Every time I design a serial protocol to be used between two arduinos, I feel a bit like I'm reinventing a wheel. I wonder if there are any best practices or patterns people follow. This question is less about the actual code, but more about the format of the messages.

For example, if I wanted to tell an arduino to flash it's first LED 3 times I might send:

^L1,F3\n

'^': starts a new command
'L': Defines the command, (L: target this command to an LED)
'1': Target the first LED
',': Command line separator, new value in this message to follow
'F': Flash sub-command
'3': 3 times (Flash the LED three times)
'\n': End the command

Thoughts? How do you usually approach writing a new serial protocol? What about if I wanted to send a query from arduino 1 to arduino 2 and then receive a response?

There are a lot of ways to write a serial protocol depending on what functionality you might want and how much error checking you need.

Some of the common things you see in point to point protocols are:

End of message

The simplest ASCII protocols just have an end of message character sequence, often \r or \n as this is what gets printed when the enter key is hit. Binary protocols might use 0x03 or some other common byte.

Start of message

The problem with just having end of message is that you don't know what other bytes have already been received when you send your message. These bytes would then be prefixed to the message and cause it to be interpreted wrongly. For example, if the Arduino just woke from sleep there might be some garbage in the serial buffer. To get around this you have a start of message sequence. In your example, ^,  in binary protocols often 0x02

Error Checking

If the message can be corrupted we need some error checking. This could be a checksum or a CRC error or something else.

Escape Characters

It could be that the checksum adds to a control character, such as the 'start of message' or 'end of message' byte, or the message contains a value equal to a control character. The solution is to introduce an escape character. The escape character is placed before a modified control character so that the actual control character is not present. E.g. if a start character is 0x02, using the escape character 0x10 we can send the value 0x02 in the message as the byte pair 0x10 0x12 (byte XOR control character)

Packet number

If a message is corrupted we could request a resend with a nack or retry message, but if multiple messages have been sent then only the latest message can be resent. Instead the packet can be given a number that rolls over after a certain number of messages. For example, if this number is 16, the transmitting device can store the last 16 messages send and if any were corrupted the receiving device can request a resend using the packet number.

Length

Often in binary protocols you see a length byte which tells the receiving device how many characters are in the message. This adds another level of error checking as if the correct number of bytes were not received then there was an error.

Arduino specific

When coming up with a protocol for Arduino the first consideration is how reliable is the communications channel. If you are sending over most wireless mediums, XBee, WiFi, etc, there is already built in error checking and retries and thus no point in putting these in your protocol. If you are sending over RS422 for a couple of kilometres then it will be necessary. The things I would include are the start of message and end of message characters, as you have. My typical implementation looks something like:

>messageType,data1,data2,…,dataN\n

Delimiting the data parts with a comma allows for easy parsing, and the message is sent using ASCII. ASCII protocols are great because you can type messages into the serial monitor.

If you want a binary protocol, maybe to shorten the message sizes, you will have to implement escaping if a data byte can be the same as a control byte. Binary control characters are better for systems where the full spectrum of error checking and retries is desired. The payload can still be ASCII if desired.


"SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.
My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.
If I try to compile it for Mega, there are no problems.
I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

Ahhhh, I figured it out.  I had to add #include "Arduino.h" to the .cpp file.


Weak Arduino Output Pins Sorry if this is a newbie question, but I'm really struggling with this and I can't seem to figure it out.
I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.
However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.
Should the basic digital output pins be able to run fairly small drone motors like mine?
Thank you for your help! :)

The Absolute Maximum is 40mA per pin, but you shouldn't go even close to that; max. 20mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200mA.
Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.
Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.


Arduino - "expected primary-expression before '.' token" Error #include "Ultrasonic.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // put your setup code here, to run once:
  lcd.begin();
  Serial.begin(9600);
}
Ultrasonic ultrasonic(11, 12); //Ultrasonic ultrasonic(Trig,Echo);
void loop()
{
  int a = (Ultrasonic.Ranging(CM));
  if (a >= 15 && a < 20)
  { Serial.println("guvenli");
    lcd.print("guvenli");
    delay(500);
    lcd.clear();
    tone(3, 2000, 100);
    delay(500);
    noTone(3);
  }
  if (a >= 10 && a < 15) {
    Serial.println("guvenli dikkat");
    lcd.print("guvenli dikkat");
    delay(500);
    lcd.clear();
    tone(3, 2000, 50);
    delay(250);
    noTone(3);
  }
  if (a < 5)
  {
    Serial.println("vurdun");
    lcd.print("vurdun");
    delay(500);
    lcd.clear();**uıhhf
    tone(3, 2000, 50);
    delay(50);
    noTone(3);
  }
}

In this code i'm getting an error like this:

   C:\Users\*\AppData\Local\Temp\arduino_modified_sketch_113625\sketch_apr29a.ino: In function 'void loop()':

sketch_apr29a:19:22: error: expected primary-expression before '.' token

   int a = (Ultrasonic.Ranging(CM));

                      ^

exit status 1
expected primary-expression before '.' token

Ultrasonic is a class name. Why are you trying to use it before a . in an expression?

Judging by the declaration, you need ultrasonic. That is your object name. ultrasonic, not Ultrasonic.


Is it possible to charge a battery using a water flow sensor? Is it possible to use a water flow sensor to charge a battery? Since the water flow sensor measures water flow using pulses, could I charge a battery using these pulses(instead of using it to read water flow).

Heres an example of the product?
https://netram.co.za/1200-g-12-water-flow-sensor-13mm.html

Thank you

Is it possible to charge a battery using a water flow sensor?

No, it is basically a hall-effect sensor that requires power and generates a low effect pulse.

Look for a generator. Something like this; https://netram.co.za/1199-36v-micro-hydro-generator.html

Cheers!


Assembly for loop repeating 2 times when it's only suppose to do it once I'm programming an Arduino Nano so I belive that this question should be qualified for this SE.

I am trying to dim up an LED using a for loop in AVR assembly.

My problem is that the cycle is repeated twice before ending, while it is suppose to end after the first cycle.

A cycle is when the red_loop is repeated 256 times (to dim the led up). At that point, the value should overflow causing the variable to go back to 0. The code should stop there, but mysteriously, it does another cycle and then it stops.

Does anyone know why?

Here is my code :

.org 0x000

ldi r16, 0b111
out ddrb, r16

ldi r16, 0xff
out portb, r16

ldi r16, 0

; ff00 pin
; ff01 value
; ff02 led

ldi r16, 0b000
sts $ff00, r16

ldi r16, 0
sts $ff01, r16

red:
    ldi r16, 0b001
    sts $ff00, r16

red_loop:
    rcall pwm

    lds r16, $ff01
    inc r16
    sts $ff01, r16
    cpi r16, 0
    brne red_loop

end:
    rjmp end

pwm:
    ldi r24, 190

pwm_pre_loop:
    ldi r17, 0

pwm_loop:
    lds r16, $ff01
    cp r17, r16
    brge off

    cp r17, r16
    brlo on

pwm_loop_check:
    inc r17
    cpi r17, 0
    brne pwm_loop

    inc r24

    cpi r24, 0
    brne pwm_pre_loop

    ret

on:
    lds r16, $ff00

    sbrc r16, 0
    cbi portb, 0

    sbrc r16, 1
    cbi portb, 1

    sbrc r16, 2
    cbi portb, 2

    rjmp pwm_loop_check

off:
    lds r16, $ff00

    sbrc r16, 0
    sbi portb, 0

    sbrc r16, 1
    sbi portb, 1

    sbrc r16, 2
    sbi portb, 2

    rjmp pwm_loop_check

The problem is that the register r17, which you use as a PWM timing
ramp, overflows twice every time you enter pwm_pre_loop:

when you increments it past 127, it overflows to −128
when you increment it past 255, it overflows to 0.

When using a counter the way you are using r17 here, you usually have
it overflow only once per cycle: either you consider it holds a signed
number which overflows from 127 to −128, or you consider it holds an
unsigned number which overflows from 255 to 0. I guess the latter is
more common. Your code is confused about that register's signedness:

The instruction brge (named “Branch if Greater or Equal (Signed)” in
the instruction set datasheet) tests the S (sign flag) bit of the
status register, which is useful for signed comparisons.
The instruction brlo (“Branch if Lower (Unsigned)”) tests the carry
flag, which is used for unsigned comparisons.

You should decide once on the signedness of the counter, and then use it
consistently. Since here unsigned makes more sense, you can just replace
brge by brsh (“Branch if Same or Higher (Unsigned)”).

Or better yet, remove the second test, which is redundant:

pwm_loop:
    lds r16, value
    cp r17, r16
    brsh off  ; if (r17 >= r16) goto off;
    rjmp on   ; else goto on;

Note by the way that you can name your RAM variables. And you can use
some of the other available registers instead of the RAM.


Is there a test framework for Arduinos? I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.

EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.

It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.

Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?

Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.

Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


Circuit works on breadboard but has power problems on protoboard I'm building a simple circuit that takes data from an IMU (using MPU6050), sends it to a microprocessor (Arduino Pro Mini 5V) to apply data smoothing and averaging, and then this data is sent using an HC-08 BLE module for the data to be further processed on a mobile. The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

When I build this circuit on a breadboard, it works well, but the Arduino is power hungry as expected. It runs for over an hour in this setting (I haven't tested it for longer), but I've build this circuit twice using protoboards and it can't stay on. One circuit is able to send data for a while, but the LED on my BLE module dims and eventually turns off after ~5m, and requires me to wait 30+m before I try to power the circuit again. The other circuit has all LEDs shine when power is switched on, but the IMU doesn't send any data (an LED on the Pro Mini blinks whenever I2C data is received).

The shitty thing is that, whenever I power these circuits via USB, they work as intended, just like when I power them using 9V to RAW on the breadboard.

I tested the circuit on the breadboard later and after BLE has connected and is sending data, the whole circuit draws 42.9mA, the BLE module draws 1.5mA, and the IMU draws 5.4mA.

What is the most effective way to fix this problem? Should I focus on finding a different battery, or focus on power-savings within the circuit?

These are my ideas so far:

replace all boards with 3.3V versions
reduce clock speed (might not be viable, I need a lot of IMU data?)
use external voltage regulator, connect Vout from regulator to 5V of pro mini
replace 9V battery with Lithium Ion battery
replace Pro Mini with an ATtiny85

I'd like to take the least time to maximize power savings, so while I could go through all these ideas, I just need the circuit to work at the end of the day.

I have a page about power saving.

To summarize some of the techniques you can use:

Run the processor at a lower frequency
Run the processor at a lower voltage
Turn off unneeded internal modules in software (eg. SPI, I2C, Serial, ADC)
Turn off brownout detection
Turn off the Analog-to-Digital converter (ADC)
Turn off the watchdog timer
Put the processor to sleep
Don't use inefficient voltage regulators - if possible run directly from batteries
Don't use power-hungry displays (eg. indicator LEDs, backlit LCDs)
Arrange to wake the processor from sleep only when needed
Turn off (with a MOSFET) external devices (eg. SD cards, temperature sensors) until needed

I've got a temperature and humidity sensor which has been running for years on 3 x AA batteries.

  The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

That's not a great choice for a start, as the voltage regulator has to turn the 9V into 5V (in the form of wasted heat). You'd be better off with 3 x AA batteries (around 4.5V) and put them straight into the 5V pin.

Those 9V batteries have notoriously low mAh because they are basically 6 coin cells stacked on top of each other.


"Broken Pipe" when uploading to Arduino UNO I just got my Arduino UNO and I'm trying to upload the blink example but the upload fails with

ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMSET"): Broken pipe
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Broken pipe

I have tried both Arduino IDE 1.0.1 (which I installed via my package manager) as well as version 1.0.5 which I downloaded from the arduino.cc website. I'm running Ubuntu Linux 12.10 if that makes a difference.

I'd appreciate any and all help in getting my arduino up and running!

As with any communication error, try these:

Disconnect and reconnect the USB cable.
Use a different USB cable.
Press the reset button on the board.
Restart the Arduino IDE.
Make sure you select the right board in Tools ► Board ►, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
Make sure you selected the right port in Tools ► Serial Port ►. One way to figure out which port it is on is by following these steps:

Disconnect the USB cable.
Go to Tools ► Serial Port ► and see which ports are listed (e.g. COM4 COM5 COM14).
Reconnect the USB cable.
Go back to Tools ► Serial Port ►, and see which port appeared that wasn't there before.

In extreme cases, you may need to burn the bootloader.

Answer adapted from here.


HardwareSerial Indexing Array How should I index HardwareSerial ports into a single array?.

This compiles, but do not work.

HardwareSerial Serials[]={Serial,Serial1,Serial2,Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i].begin(38400);
        while (!Serials[i]);
    }
}

char s;
void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i].available()){
            s=Serials[i].read();
            Serials[i].write(s);
        }
    }
}

your code makes copies of Serials into items in the array of HardwareSerials. To use the original Serial objects, store and use pointers.

HardwareSerial* Serials[]={&Serial,&Serial1,&Serial2,&Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i]->begin(38400);
        while (!*Serials[i]);
    }
}

void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i]->available()){
            char s=Serials[i]->read();
            Serials[i]->write(s);
        }
    }
}


How to control a DRV8266 motor controller with an ESP8266? https://github.com/sparkfun/SparkFun_MiniMoto_Arduino_Library/tree/V_1.1.0

Will this library work on an esp8266?   If not is there any way I can get this driver to work on the ESP?

No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.


How to access the member of union in loop? Trying to get the address of receiving XBee's data in the loop in API mode with escape.
Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.

#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

boolean xbee_rx(struct SENSOR_DATA *ret) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  union XbEE_FRAME{
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
  } xbee;
  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
      xbee.buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(xbee.buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
        *ret = xbee.frame.sensor_data;
        return true;
      }
    }
  }
  return false;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);   // 38400
  Serial.println("overover");
}

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:
 struct SENSOR_DATA data;
  if (xbee_rx(&data)){
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
  }
}

I don't think you can.

The structures are defined within a function so the loop() won't have access to them.

Further the parameter returned from the function xbee_rx() is of type SENSOR_DATA which is a sibling in the frame structure to the data you want to read.


Is it possible to detect host usb device connected to arduino? and how? let's say that I've connected an arduino uno to a pc, or to a mobile phone via usb .. how can I detect the device type and the running operation system if it's possible?

You can't, using stock firmware. And with custom firmware it's still very difficult.

The USB communication chip on the Uno has no out-of-band means of telling the main MCU that it is connected to a host. You might be able to rewrite the communication firmware on the R3 to tell the main MCU over serial that it is connected, but the firmware on the main MCU will need to be written in such a manner that it will anticipate this.

If you want this to work then you should consider using one that has a native USB connection, such as the Leonardo. You will then be able to query the USB facility directly to know whether or not you are connected to a host.


Measure voltage changes with unknown baseline I would like to monitor an audio stream and detect when it is "active" and music is playing or when it is "inactive" and is silent. What is a good way to measure when an audio stream changes state and continues to be "active?"

Each audio stream is amplified with this circuit.

Each audio stream has a different baseline voltage when it is not playing and "silent", but that voltage tends to drift slightly and change. This may be an artifact of my amp. I don't have an OScope and my multimeter is rubbish for low voltage so I can't quite pin down where the drift is coming from.

Currently, I'm using the method shown below, but that isn't as effectivewhen the audio stream is loud (e.g. has a compressed dynamic range).

Also, low volume tracks (e.g. classical music) tends have too low of a dynamic range to measure accurately and I get a lot of false "off" states.

#include <elapsedMillis.h>    //measure elapsed time

const int analogInPin = A0;   //Analog input pin - reads from amplifyer circuit
const int statusLight = 10;   //Digital output pin for indicator light
int sensorValueA = 0;         //Sensor reading now
int sensorValueB = 0;         //Previous sensor reading
int sensorDeltaA = 0;          //Change in sensor reading
int sensorDeltaB = 0;          //Record the last delta - useful for prefenting accidental triggering on start
int sensorThreshold = 50;      //Threshold in delta to trigger action
elapsedMillis turnOverTime;   //Timer for measuring the turnover between changes in sensor reading

void loop() {
  //measure the analog input
  sensorValueA = analogRead(analogInPin);
  sensorDeltaA = abs(sensorValueA - sensorValueB);

 //check if the data is over the threshold and switch on
  if ((sensorDeltaA >= sensorThreshold) and (sensorDeltaB != 0)) {
    turnOverTime = 0;
    powerStateA = true;
  }

  sensorValueB = sensorValueA;

  //check if no sensor data beyond the threshold has been returned within the delay window, switch off
  if (turnOverTime >= delayTime) {
    turnOverTime = 0;
    powerStateA = false;
  }

  //if the powerstate changes act acordingly
  if (powerStateA != powerStateB) {
    digitalWrite(statusLight, powerStateA);
  }
}

An audio signal consists of two main components:

An AC signal
A DC offset

What you are interested in is the AC signal, but not the DC offset.  That DC offset is what is drifting in your current model.

So you need to AC couple the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.

The simplest way is with a capacitor.

But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.

The simplest way is to add a DC offset.

But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an unknown DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.

Here's a very simple circuit:

simulate this circuit – Schematic created using CircuitLab

The capacitor C1 removes the existing DC offset.  R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.

That means that the signal now varies around 2.5V.  Silence is 2.5V, and noise is other values above and below that.

Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512.  Sound will be both above and below that value.

So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.

For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.

int audio = analogRead(A0); // Get a sample
audio = audio - 512; // Remove DC offset
audio = abs(audio); // Remove sign

You can now compare that to a threshold value:

if (audio > 100) {
    // do something
}


Combining code for multiple sensors in a single program I need to operate 3 different sensors (taken 6 sensors of each type) by Arduino Mega2560 :-

DHT11 (temperature-Humidity sensor)
MQ5 (gas sensor) and
Soil Moisture sensor
{taken 6 of each type (total=18).}

I have managed to run each one of them separately and I don't know how to manipulate the code so they could work all together. My background in coding is basic, so it would be great help if someone can help me for combining these codes.

Here are the sketches:

MQ5 Code:

int sensor=7;
int gas_value;
void setup()
{

pinMode(sensor,INPUT);
Serial.begin(9600);

}

void loop()
{

gas_value=digitalRead(sensor);
Serial.println(gas_value);
}

{other digital pins to be used: D6,D5,D4,D3,D2}

DHT11 Code:

#include <dht.h>
#include <dht.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

void setup(){

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

{analog pins for other sensors: A1,A2,A3,A4,A5}

Soil_Moisture Sensor Code:

int sensor_pin = A6;
int output_value ;

void setup() {

   Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");
   delay(2000);

   }

void loop() {

   output_value= analogRead(sensor_pin);
   output_value = map(output_value,550,0,0,100);
   Serial.print("Mositure : ");
   Serial.print(output_value);
   Serial.println("%");
   delay(1000);
   }

{Analog pins for other sensors to be used: A6,A7,A8,A9,A10}

In general:

All #defines and #includes get put from all separate sketches, at the top.

Globals and function definitions (except for setup() and loop()) get mixed together below the #defines and #includes.

All code in the separate setup()s get put in the combined setup().

All code in the separate loop()s get put in the combined loop().

You have to be aware that any loop() from the separate programs that include a delay() will likely have to be refactored to use the same kind of scheduled execution method as the Blink Without Delay example from Arduino. delay() stops the whole program while it twiddles thumbs, which means your other sensors aren't being read or managed during that time.


Problem using an array inside a switch statement I am having a problem when using a switch statement to check for something inside an array. I am using an int as my switch, then I compare the character arrays using strstr. So it reads like this:

void function(char *buffer, uint32_t size){
  char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
  #define TXTCOMPARE1 (char*)"Sample Text 1"
  #define TXTCOMPARE2 (char*)"Sample Text 2"
  #define TXTCOMPARE3 (char*)"Sample Text 3"
  switch(intCompare){
    case COMPARE1 :
      p = strstr(buffer,TXTCOMPARE1); break;
    case COMPARE2 :
      p = strstr(buffer,TXTCOMPARE2); break;
    case COMPARE3 :
      p = strstr(buffer,TXTCOMPARE3); break;
  }
  if(p!=NULL) { Serial.println("Success!"); }
  else { Serial.println("No match"); }
    memset(&p,0,sizeof(p);
}

This method does not work and p is always NULL. However, when I write it out without the switch() it compares just fine:

//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }

Why would the switch statement give me different results for what is basically the same function call?

Edit: Actually it seems to break everywhere when I set more than one call to p = strstr(...). When there is only one strstr it works, when two or more are used, it does not...

One big problem is that you forgot the break statements for those cases.  So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.


How can I read the data stored in EEPROM although is powered OFF based on the simple code I wrote? I need help regarding on EEPROM library. Based on the code below, for every 2 sec, I want to store the int for increase where it will keep increasing by 1. Then, I upload to my Arduino Nano and open Serial Monitor to let it run for about 20 seconds. The serial monitor shows that Increase Count:10.
Then I unplug the Arduino Nano, closed the Serial Monitor, wait for 5 sec, then plug back to computer and turn on the Serial Monitor, then the Serial Monitor start to shows Increase Count:1, which indicated it start to recount again from 1,2,3,4.....
I thought that EEPROM will store the last number it counted which is 10, then when I unplug and plug back it should continue to count from 10, 11, 12, .......
So I would like to ask community whether my execution code and the method is correct or not. If not, can you advice me on how I can execute it correctly. Thank you in advance!
#include <EEPROM.h>

int addr=5;
int storagedata;
int increase;

void setup()
{
  storagedata=EEPROM.read(addr);
  Serial.begin(9600);

  timevalue=millis();
}

void loop()
{
  if (millis()-timevalue>=2000)
  {
    increase=increase+1;

    EEPROM.update(addr,increase);
    storagedata=EEPROM.read(addr);

    Serial.print("Increase Count:");
    Serial.println(storagedata);

    timevalue=millis();
  }
}

increase is a global variable and will implicitly initialized with the value zero. Then you are reading the EEPROM data into the variable storagedata in setup(). And then in loop() you are increasing increase from zero to one and write that to EEPROM. This value then gets read back into storagedata. So now increase and storagedata have the same value: one. So the counting begins on every reset at 1.
It is unclear, why you even have 2 variables for this. One would be enough (unless you want to test the EEPROM for some reason). In setup() read the data into increase. Then the counting starts with the number in EEPROM.


can I design a User Interface to run on the arduino and display it with VGA? I know you can design a user-interface in any language you choose and Link it with a Arduino via serial Port, but I am asking if I can design user-interface to run on the Arduino WITHOUT the need for an external laptop/desktop and display the user interface on a screen (like via VGA) ? and HOW ?

Forget VGA. Arduino is not capable of that.

For display you can use a 16x2 LCD (only chars, not graphics) or an OLED display, which have graphic capabilities. There are in size from 0.96". There BW, but alse color models and touch sensitive ones. For input you use push buttons, or keypad.

Today best option for display is some model with I2C or SPI interfaces (to minimize wiring).

There thousand of projects in Internet. Search "Arduino OLED keypad" and you will find projects like http://www.instructables.com/id/Arduino-OLED-Calculator/:

This hardware impose some limits in the UI (thank god). What you have is a tradicional menu system: you present a menu, user choose an option, Arduino execute it. No help, no dropbox, no autocompletion, nothing, only the most basic "Press 1 for ..."

EDIT:

As Nick Gammon stated, it's possible to drive a VGA display from an Arduino, like this post and this other shows. The resolution are  20 characters wide by 30 characters deep (160 x 480 pixels) for the monochrome version and 120 x 60 pixels for the four colors version.

However, that capabilities doesn't match any of the standard VGA capabilities:

  The VGA supports both All Points Addressable graphics modes, and
  alphanumeric text modes. Standard graphics modes are:

640×480 in 16 colors or monochrome[2] (the latter matching IBM's lesser Multi-Color Graphics Array standard)
640×350 or 640×200 in 16 colors or monochrome (EGA compatibility mode)
320×200 in 4 or 16 colors
320×200 in 256 colors (Mode 13h)

The proposed alternatives achieves less resolution than a 1981 Sinclair ZX-81 (24 lines of 32 chars), takes two timers and half of Arduino RAM minimum (the color example left you with 200 bytes RAM and takes a third timer with it).

So, in practical terms, VGA is not an option.


SD card shield not working on 3.3v My SD shield works nicely on 5v supply, but does not detect SD card on 3.3v. Could someone explain the possible reason behind this? Could you also provide a solution for this?

I've worked with it on Arduino Uno. Now I want to use SD card directly with ESP-12E to read its contents using SPI by doing something like this. Since ESP8266 operates olny on 3.3v, I need SD card to work on this voltage.

I've used two separate SD card shields without any luck! Photos of the two shields and micro-SD card are attached.

I could not find any info on the full size SD card adaptor, but the microSD adaptor has a 3.3V (LM1117 or equivalent) regulator on it. It, therefore, needs a minimum of 4.5V to operate.

To run the adaptor from 3.3V, you would have to remove the regulator and solder in a piece of wire in its place.


Execute Code sent over Serial I was wondering if its possible to send code to the Arduino, and then have it execute this code.

What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library.  I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.

Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,

-Will

No, it's not possible as you describe it.

The Arduino's main chip, the ATMega328p, is what is known as Harvard Architecture.  This means that the Flash memory and RAM both occupy completely separate memory address spaces.  The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the Instruction Bus) and not the memory space the RAM is connected to (the Data Bus).  This means it can only run instructions that are in Flash and not RAM.

It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.

There are other options though.

Use an interpreted language.  I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.
Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno.  Firmata might be of use here.


Any resources you know with regards to remotely reading data from arduino? I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.

Please let me know if you can't understand my question.

You can use the Bluetooth on the board, a Bluetooth dongle for your laptop if the laptop does not have bluetooth or you can buy a wifi shield.

The 101 has Bluetooth LE on the board.

You will find there is a Bluetooth -> Serial USB software, so the application on the laptop can still work the same way as when using the usb.

Here are the Bluetooth examples for the 101 on arduino.cc

https://www.arduino.cc/en/Reference/CurieBLE

and the user guide for the 101

https://www.arduino.cc/en/Guide/Arduino101


7-Segment Display with WS2312B and FastLED I thought of the idea of using the WS2312B LED strip to drive a custom 7-Segment display. The project will require a large number of these displays, and driving them with a single Arduino (I'm thinking of an Arduino MEGA). For driving the LEDs I am using the FastLED library.

I wrote some code that drives a single display, It works, but I think It's possible to make it simpler, the code I wrote stores the digits in arrays, and uses these arrays in functions customized to each digit. here is an example:

//Digit Arrays:
byte digit0[]     = {0,1,2,3,4,5};
byte digit1[]     = {1,2};
byte digit2[]     = {0,1,3,4,6};
byte digit3[]     = {0,1,2,3,6};
byte digit4[]     = {1,2,5,6};
byte digit5[]     = {0,2,3,5,6};
byte digit6[]     = {0,2,3,4,5,6};
byte digit7[]     = {0,1,2};
byte digit8[]     = {0,1,2,3,4,5,6};
byte digit9[]     = {0,1,2,3,5,6};

The functions are something like this:

void AllOff(){
//Switch off All the LEDs in the segment. Should be off for 1 second
  for(int i=0; i<7; i++){
    leds[i] = CRGB::Black;
    FastLED.show();
  }
  //delay(1000);
}
void AllOn(CRGB myColor){
  //Switch on All the LEDs in the segment (should display 8)
  //The color of choice is #1E78A0
  for(int i=0; i<7; i++){
    leds[i] = CRGB (30,120,160);
    FastLED.show();
  }
  delay(1000);
}
void Print0(CRGB myColor){
  //Prints the digit 0:
  AllOff();
  ArraySize = sizeof(digit0);     //get the size of the array
  for(int i=0; i<ArraySize; i++){
    LED_Number  = digit0[i];      //get the LED number from the array
    leds[LED_Number]    = CRGB (myColor);  //Switch the LED on
    FastLED.show();
  }
}

When I call it in the code, I simply do something like this:

Print0(CRGB::Purple);
delay(500);

I have tried for the best part of the past two days to find a better way to go about this, but I couldn't. What I'm thinking is perhaps to create a function that would store all the digits instead of storing every one as an array, and then call it maybe within a for loop? something like

for(int i=0; i<10; i++){
    displaydigit[i];
    FastLED.show();
  }

Do you know of any library that has something similar, or perhaps any idea on how to achieve this?

Your assistance, as always, is greatly appreciated.

Thank You.

First, for all the digits I'd use an 7 value array, indicating for every segment if it's ON or OFF. So for 0 your get byte digit0[] = {1,1,1,1,1,1,0}, where 1 indicates the segment is ON, and 0 indicates it's OFF. Your code then becomes:

void Print0(CRGB myColor){
  //Prints the digit 0:
  for(int i=0; i<7; i++){
    if( digit0[i] )
      leds[i] = CRGB (myColor);  //Switch the LED on
    else
      leds[i] = CRGB::Black; // Switch the LED off
  }
  FastLED.show();
}

The next step would be to create a two dimensional array containing which segments are on for which digits.

byte digits[10][7] = {
     {1,1,1,1,1,1,0} //0
    ,{0,1,1,0,0,0,0} //1
    ,{1,1,0,1,1,0,1} //2
    ,{1,1,1,1,0,0,1} //3
    ,{0,1,1,0,0,1,1} //4
    ,{1,0,1,1,0,1,1} //5
    ,{1,0,1,1,1,1,1} //6
    ,{1,1,1,0,0,0,0} //7
    ,{1,1,1,1,1,1,1} //8
    ,{1,1,1,1,0,1,1} //9
   }

Now you can generalize you Print0 function to accept any number:

void PrintNumber(byte number, CRGB myColor){
  if( number>9 )
    return;
  for(int i=0; i<7; i++){
    if( digit[number][i] )
      leds[i] = CRGB (myColor);  //Switch the LED on
    else
      leds[i] = CRGB::Black; // Switch the LED off
  }
  FastLED.show();
}

Call the new function in your loop; for example PrintNumber(3, CRGB:White);

If you want to put multiple 7-segment displays in series, you could add and offset argument to the PrintNumber function, and use leds[i+offset] instead. Then call the PrintNumber with offset 0 for the first digit/display, 7 for the second, 14 for the third, and so on.


Question regarding Servo including Serial monitor display I tried to make code following your instruction about mills,
and it looks like this. Unfortunately, it is not working. Is there problem with my code?

Here is my code:

#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}

So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?

I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then m=(millis() + 60000). Then you will need to nest another if statement in here to say if it detects ONLY three bar, then m = 0.
Your third if the statement is if it detects the four green bars AND m == millis() then the servo will activate.

This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.


Using an Arduino as the processor for a computer-mouse-like speed detector I'm looking at making a pretty cheap and easy odometer, eventually for an electric car or similar vehicle.

My idea is to implement a big computer mouse, and track the speed with that: a computer mouse takes photos of the surface it is on, and finds the difference between sequential images in both the X and Y directions.

What I am wanting to do is to attach a downwards-facing camera; something like this, to the bottom of the vehicle, and use an Arduino Nano to do the image processing to achieve a result similar to a computer mouse.

I was wondering whether anyone knows of an libraries/documentation on anything similar, or if anyone has any pointers on reasons why this would not work, or ways it would work.

Thanks all.

Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.

If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.

Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to wikipedia, a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.

But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.

Voila; speed! :-)

This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.

Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.