What should I use Arduino-Mega or Rasbeery pi? I am doing a project on Vehicle tracking and security. In my project Micro controller will sense input from sensors and at the same time it has to sense signal from user for tracking purpose and continuously checking the speed limit and boundary. so, there will be 3-4 tasks that would be executing parallel. Can anyone suggest which one is perfect for this kind of project... Arduino-Mega or Rasberry Pi?

A RaspberryPi is essentially a small, low-spec computer. It is mostly an overkill for many small projects. Imagine using a super high-spec computer to play Minecraft. It's just nonsensical.

I'm assuming you'll be connecting to the car battery? Take note of the power requirements of your project. The RaspberryPi has a power requirement of 2.1A at 5V (which is a lot!), whilst an Arduino has a minimum requirement of 250mA.

Also remember: the RaspberryPi is running an operating system in the background in order to run your code. It will be working on numerous other operations and programs, not just yours. The Arduino will only run your program.

I had a similar project to what it sounds like you're doing. I used an Arduino Mega and had Bluetooth, GPS, and SD card all connected to it. The project worked absolutely fine, and I had lots of spare program space left over should I wish to expand on it. For reference, feel free to explore.


Initialize a class (HX711) within a class with constructor and parameters I am far from being an Arduino specialist, so please bear with me if some of my code below is far from correct.

I am writing a sketch in which I need to use 3 instances of the HX711 library, as I am using 3 different weight sensors.

In order to try to clean up the code, I want to put basically all the code using HX711 in my own class.

Here is what my ScaleMeasure.h looks like:

// ScaleMeasure.h
#ifndef _SCALEMEASURE_h
#define _SCALEMEASURE_h

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

#include <CmdMessenger.h>
#include "HX711.h"

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale = HX711(_dout_pin, _clk_pin);
};

and .cpp

#include "ScaleMeasure.h"

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

void ScaleMeasure::Setup()
{
    _scale.power_up();
    _scale.set_scale();
    _scale.set_scale(_calibration_factor);
    _scale.tare();
    _scale.read();
}

float ScaleMeasure::Measure()
{
    return _scale.get_units(5);
}

but there is obviously something wrong, as a call to the constructor lock the rest of the program. I believe that my instantiation, of HX711 in ScaleMeasure.h  HX711 _scale = HX711(_dout_pin, _clk_pin); is not correct, or not in the right place. The code compile fine, though.

Thanks for your help.

Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:

HX711() {} // default constructor, empty

Add member function to do the init job (done by original constructor), also in the header file

    void Init(byte dout, byte pd_sck, byte gain = 128) {
    PD_SCK  = pd_sck;
    DOUT    = dout;

    pinMode(PD_SCK, OUTPUT);
    pinMode(DOUT, INPUT);

    set_gain(gain);
}

Now your ScaleMeasure class will be like (header):

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

and cpp

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;

    _scale.Init(_dout_pin, _clk_pin);

    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}


How to update a text file dynamically I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.

Now, I have a text file in my server which updates dynamically for every 5 min - 10 min. I am trying to read that text file contents.

I want my server to be always connected, So It must be in setup() function.
I want update only to my text file which dynamically changes, so it must be loop() function.

How to implement this ? Any Suggestion ?

It's difficult to answer without details of how your server works.

If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data.  The arduino would only need to serialWrite() data for the server to parse and store.

If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:

http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.

The arduino could also beam data back to your server via IR, or bluetooth, etc.

There's lots of ways to do this.


Is Arduino Ethernet shield compatible with arduino due? Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can tolerate connection to a 5v Arduino.

Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.

However, you should review the the full schematics and make your own determination that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.

It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.


Play sound on top of background music using arduino uno tmrpcm library We designed a big piano with 15 buttons on it. Every button has a proximity sensor. Whenever users interact with the sensor a specific sound plays for that button. My code is working fine for this purpose but now I want to add background music. Our piano button sound should play on top of that background music. I am using tmrpcm library, and I already added a bg music but when I interact with the sensor, bg music stops and starts from the beginning right after the piano button sound stops. Is there a way to play a sound without interrupting a bg music. Any help will be appreciated.

Assuming you are using an Arduino Uno, You didn't say. As there are many Arduino platforms these days.
As the tmrpcm library is using the PWM  (Pulse Width Modulator) HW (Hard Ware) to recreate the sound waves from the WAV file on the SDCard, the PWM is not available for creating the sounds from your piano application (you didn't say what piano application you were using).  That said, it is not impossible to re-write both applications to SUM the two wave forms together mathematically before resampling the SUM and writing that sample value to the PWM HW to simulate the SUM of the two wave forms.  However, this is likely not trivial and it is also likely the Arduino Uno processor (an Atmel ATmega328P) will not be powerful enough (perform the math fast enough) to keep up with normal sound playback.
It would likely be much simpler to use 2 Arduino Uno boards and sum the sound from the sound file application and the piano application using analog techniques external from the Arduno Uno boards.


How to connect Arduino Nano with ESP8266 and BMP180? I have an issue with my application.

Hardware used:

ESP8266 Serial Wi-Fi Wireless Transceiver Module for IOT
Robodyn Micro USB Compatible for Arduino Nano V3.0 ATmega168 CH340G
SENSOR: BMP180

Connections:

Arduino Nano to ESP8266
CH-PD to Vcc
GPIO0 to GND
Rx to Rx
Tx to Tx
3.3v to 3.3v
Reset to GND
GND to GND

Arduino Nano to BMP180

3.3v to VIN
GND to GND
A5 to SCL
A4 to SDA

Sketch used (uploaded in Generic ESP8266 Board):

#include <DHT.h> //  DHT.h library
#include <ESP8266WiFi.h> // ESP8266WiFi.h library
#include <SFE_BMP180.h>
#include <Wire.h>

SFE_BMP180 pressure;

const char* ssid     = "GOPI-LAPTOP";
const char* password = "kcejava123";
const char* host = "api.thingspeak.com";
const char* writeAPIKey = "CQSHDFP4EZFCDWKO";

void setup() {
  // Initialize sensor
  Serial.begin(9600);
  delay(1000);
  if (pressure.begin())
    Serial.println("BMP180 init success");
  else {
    Serial.println("BMP180 init fail\n\n");
  }
  //  Connect to WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature: ");
      Serial.print(T,2);
      Serial.print(" deg C, ");
      Serial.print((9.0/5.0)*T+32.0,2);
      Serial.println(" deg F");
    } else
      Serial.println("error retrieving pressure measurement\n");
  }
  status = pressure.startPressure(3);
  if (status != 0) {
    delay(status);
    status = pressure.getPressure(P, T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("absolute pressure: ");
      Serial.print(P, 2);
      Serial.print(" mb, ");
      Serial.print(P*0.0295333727, 2);
      Serial.println(" inHg");
      p0 = 1013.25; // we're at 1655 meters (Boulder, CO)
      Serial.print("relative (sea-level) pressure: ");
      Serial.print(p0, 2);
      Serial.print(" mb, ");
      Serial.print(p0*0.0295333727, 2);
      Serial.println(" inHg");
      a = pressure.altitude(P, p0);
      Serial.print("computed altitude: ");
      Serial.print(a, 0);
      Serial.print(" meters, ");
      Serial.print(a*3.28084, 0);
      Serial.println(" feet");
    }
  }
  // make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    return;
  }
  String url = "/update?key=";
  url+=writeAPIKey;
  url+="&field1=";
  url+=String(T);
  url+="&field2=";
  url+=String(P);
  url+="\r\n";
  // Request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  Serial.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  delay(30000);
}

Serial Output:

BMP180 init fail

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

Queries:

• How to enable BMP180 to sense? When I configure BMP180 with Arduino (without ESP8266), I get the output in the serial terminal.

• How to send data to Thingspeak.com from BMP180 using the specified hardware?

Connections:

[...]

Rx to Rx
Tx to Tx

That's not gonna fix your problem with initializing the BMP180, but you have to cross the lines, Rx to Tx and Tx to Rx, if you want to get anything on the serial terminal... Besides, your Nano is 5V, your ESP 3.3V. Connecting directly the Nano's Rx/Tx lines at 5V to the ESP's Rx/Tx 3.3V lines might not be very safe.

As for the BMP180, is it rated for 3.3V, or only 5V? If it is 5V only, it might not work on the ESP. Hence the init fail.


How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  Arduino IDE, Underlying Code and Libraries  Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.

Thanks,

Dave

The simplest way is to look at the source on Github:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.


Interfacing unusual 4 digits 7 segments display There is a common anode and common cathode of 7 segments display. But I got an unusual one.
There are 7 pins controlling 4 digits 7 segments.

I find the pinout by a multimeter. Basically, each pin can be anode or cathode.

My questions:

What is the exact name of this 7 segments display?
How to drive this display by Arduino, any website/sample code?
If I am using the 5V tolerant board, which resistor I need to use? And how is the schematic?

This display seems to have 32 addressable LEDs controlled by only
7 pins. Judging from this fact, and from the provided pinout table, it
looks like a Charlieplexed matrix.
A typical way to drive this kind of matrix is by looping over the
cathodes. You pull one cathode pin LOW, and then pull HIGH all the
anodes of the LEDs you want to shine which are connected to this
particular cathode. Wait a few milliseconds, then move to the next
cathode. It is important that all pins that are not involved in lighting
an LED remain in INPUT mode.
For example, let's say you want to light all the segments of the first
digit (display an “8”) while keeping everything else off. You first pull
pin 1 LOW (first cathode) and pull HIGH pins 2–5 (segments F, G, C
and D). Let that shine for a few milliseconds, then put everything to
high impedance (pins to INPUT) and move to the next cathode: pin 2
goes LOW and pin 1 (segment A) goes HIGH. And so on until you have
done all the cathodes.
For the coding part, I would suggest using a 7×7 matrix of booleans
telling whether a particular segment is meant to be lit. The indices of
the array would be row = cathode number and column = anode number. The
array would have the same structure as the pinout table you posted,
except for the fact that the lines and columns would have indices
ranging 0–6 instead of 1–7. This should make it easy to handle
refreshing the display.
Drawing the digits is a bit trickier than with traditional 7-segment
displays, as for each segment you will have to find its coordinates in
the matrix (cathode number and anode number). For this, I would use a
“mapping matrix” that stores the mapping (digit number, segment number)
→ (cathode number, anode number).
Below is a tentative, and untested, implementation of these strategies.
Note that I did not write a function to output a digit, but that should
be easy to implement on top of the set_segment() function defined
here. Besides, the question of how to draw a digit once you know how to
control individual segments is the standard 7-segment problem, for which
you should be able to find many tutorials.
Note that this code assumes you drive the display directly, using no
iterface other than current-limiting resistors. This carries the risk of
either overloading the cathode outputs or having the display be too dim,
depending on the current-limiting resistors. You may want to use
transistors for the cathodes, in which case you would have a set of
cathode pins different from the set of anode pins.
// Arduino pins connected to the display.
const uint8_t display_pins[7] = {2, 3, 4, 5, 6, 7, 8};

// Which segments are lit. Each segment is located in this matrix at
// the coordinates [cathode][anode].
bool segment_lit[7][7];

// Coordinates in the matrix above where a segment can be found.
struct SegmentCoordinates {
    uint8_t cathode;
    uint8_t anode;
};

// segments[digit][segment] gives the coordinates of
// any segment (0 = A) of any digit (0 = 1st digit).
const SegmentCoordinates segments[4][7] = {
// seg: A      B        C       D      E        F       G
    {{1, 0}, {2, 0}, {0, 3}, {0, 4}, {3, 0}, {0, 1}, {0, 2}},
    {{2, 1}, {3, 1}, {1, 4}, {5, 1}, {4, 1}, {1, 2}, {1, 3}},
    {{3, 4}, {4, 2}, {4, 3}, {0, 5}, {2, 5}, {2, 3}, {2, 4}},
    {{5, 6}, {6, 5}, {5, 4}, {3, 5}, {5, 3}, {4, 5}, {6, 4}}
};

// Turn a segment OFF (lit = false) or ON (lit = true).
void set_segment(uint8_t digit, uint8_t segment, bool lit) {
    SegmentCoordinates coordinates = segments[digit][segment];
    segment_lit[coordinates.cathode][coordinates.anode] = lit;
}

void setup(){}

void loop() {
    static uint8_t cathode;  // currently used cathode

    // Set the current cathode to OUTPUT LOW.
    digitalWrite(display_pins[cathode], LOW);
    pinMode(display_pins[cathode], OUTPUT);

    // Set the relevant anodes to OUTPUT HIGH.
    for (int anode = 0; anode < 7; anode++) {
        if (segment_lit[cathode][anode]) {
            digitalWrite(display_pins[anode], HIGH);
            pinMode(display_pins[anode], OUTPUT);
        }
    }

    // Let that shine for a while.
    delay(10);

    // Turn off everything.
    for (int pin = 0; pin < 7; pin++) {
        pinMode(display_pins[pin], INPUT);
    }

    // Move to the next cathode.
    if (++cathode >= 7) cathode = 0;
}

I used delay() here for simplicity. In production code you would
handdle the timings with millis() in a non-blocking fashion, in the
spirit of the “Blink without delay” tutorial.


Connect bluetooth module when no pins free I need do communicate atmega88 with a smartphone via bluetooth using a bluetooth HC-05 module. The problem is that all my atmega pins are being used. Rxd and txd pins are being used by a keypad (Keypad at PORTD). My project is almost done, at this stage i don't want to change the micro. Is there any alternative to solve this problem? Thanks

The code you're using for the atmega88 should be almost directly compatible with an ATmega328P, I suggest you pick one of those up.

Also you can try to:

Multiplex pins:

http://users.ece.gatech.edu/~sudha/academic/class/ece2030/Lectures/blocks/examples-5.gif

OR

Use shift registers/IO expanders:

http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/


how to change increase pwm frequency by changing resolution? As told in this post:

http://forum.arduino.cc/index.php/topic,16612.0.html#

The arduino can achive up to 62.5khz with 8 bits resolution

adding this line in the setup:

TCCR0B = TCCR0B & 0b11111000 | 0x01

sets the divisor of the timer to 1

int output = 5;
void setup() {
  // put your setup code here, to run once:
  TCCR0B = TCCR0B & 0b11111000 | 0x01;

}

void loop() {
  analogWrite(output,127);

}

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.

Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:

void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output.  The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.

If you check the registers for your chip, this should also adapt to the other timers.  Here, I used timer1 to avoid confusing delay() and millis().


ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K? Recently hit the dreaded 0x7000 / 28k~ AVRDUDE+LUFA limit.  It states everywhere this is because the bootloader uses 4KB, thus reducing the 32KB to 28KB.  Makes sense, except...

Blank sketches on the 32U4 take nearly 4KB from the get go, which I thought was attributed to the bootloader?  So now I'm confused.  If I'm losing 4KB off the top, and 4KB off the bottom - is the bootloader 8KB?

EDIT:  In case the above is unclear, it appears my sketches only have ~24k of the 32k available to them.  Is this expected behavior?

The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.


Component with controllable resistance from Arduino? I'm new to Arduino and building circuits, and was wondering if there is a type of component, or some other way to do the following task:

I want to control the resistance of a circuit from my computer linked to my Arduino, presumably using an output analog PIN.

Basically what I have is an LED whose brightness I want to control from my computer. I want to be able to control the resistance of the circuit to limit the electricity going to the LED, and I want to be able to do this from my computer (not physically, with a potentiometer) (unless a potentiometer's resistance can also be controlled from a PIN?).

How can I do this?

The easiest way to drive an LED with variable brightness is to use one of the pulse width modulation (PWM) output pins on an Arduino.

A PWM pin takes an input value from 0 to 255 (or is it 0/1023? I don't remember.) and converts it to a ratio of on-time to off-time. At the highest value, the output pin is in the on state, 100% of the time. At the halfway point, the output pin is HIGH 50% of the time, and LOW 50% of the time.

Our eyes average out the flashes and see a variable brightness. It works very well.

If you absolutely must have a variable resistance controlled by a digital value, there are devices known as digital potentiometers. These are variable resistors controlled by digital inputs. For an Arduino, you should think about an I2C or SPI potentiometer, which is controlled by serial port commands. You tell it the resistance you want, and it sets itself to that resistance.

As CrossRoads points out in their comment below, you still need a current limiting resistor to drive an LED from a logic pin, to protect both the LED and the output driver on the Arduino. You want to limit the current to the max current for your LED, and then use PWM to lower the brightness from the absolute max set by the current limiting resistor. CrossRoads explains how to calculate the resistor value.


I2C seems to stop working when I attach an AF motor shield I have a cheap MPU 6050 chip that communicates over 3.3V I2C. I can talk to it just fine on my Leonardo. If I add an additional Adafruit Motor shield (the old one), my MPU 6050 demo sketch hangs somewhere, and I get nothing back.

As far as I see, the pins I use for the I2C communication are not used at all by the motor shield.

What could be wrong here?

I have the MPU6050 connected to SCL, SDA, GND and 3.3V, the motor shield uses almost all other pins.

Additional Info:
I am using this sketch currently: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

Update:
Lots of "Serial.println"s later, I've narrowed it down a bit. The example sketch above hangs on the statement "Wire.endTransmission();" on line 279 of the I2CDev library.

Update:
Connecting the motor shield to external power seems to fix my problem. Weird =) I am still interested in the reason for this behavior.

Motors draw large amounts of current, and will either cause your power supply voltage to sag if you draw more current than your power supply can support, or cause blips in the power supply that will cause you all sorts of problems.

You need to take steps to isolate the power from the motor shield from the power for the Arduino.

How are you powering the motor shield? How are you powering the Arduino?

If your power supply has enough current to support both your Arduino and your motors then you can probably solve the problem by adding an isolation capacitor between the Vin port on your Arduino and ground.

What that does is to filter out temporary variations in the input voltage that's being fed to the Arduino. Without it, the Vin voltage to the Arduino is probably dropping as your motor draws large pulses of current, and that causes the output from the voltage regulator to droop as well.

I don't know how to pick the rating of the cap. A trip to the Electrical Engineering stack exchange is probably in order.


Short circuiting GND and power pins I have created an arduino shield and i want to measure the voltage between the GND pin and 5V pins, to see if i see a voltage difference between the two points, in order to test if my pcb is fine.
My concern is since these are right next to each other and my multimeter probes are thick.
If the multimeter probe that 5V pin touches the GND pin, in other words, if i short circuit the 5V and GND pins, then will my arduino be safe?
I am afraid of damaging the arduino.

It all depends on how you are powering the board.
If you're running it from USB then the computer should shut off the power to the USB port. If it doesn't then the Arduino has a small self-resetting fuse on the USB power which should shut the power off for you.
However if you're powering through the barrel jack there's no protection. Worst case scenario: it will blow the voltage regulator, which then "fails short", meaning it passes the whole of the input voltage through to the microcontroller, which then kills it.
So yes, it's possible to damage the Arduino with a short circuit.
Most multimeters have a better way of testing the board though: either the "beepy" continuity test, or the resistance mode.  You can use that to test the continuity or resistance between your 5V and GND pins without having to connect the shield to the Arduino at all. 100% safe.


Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins? I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with analogWrite() to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.

P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

No, you can't.  As it says in the Arduiuno reference page for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."

You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).


To know the state of USB (Serial) connection (connected or not connected) if (Serial.available()) {
        digitalWrite(7, HIGH);
} else {
        digitalWrite(7, LOW);
}

It doesn't seem to be so simple.
My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.

The problem here is twofold.

Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not.  That information simply isn't there. The main chip just receives UART serial data (not USB data) as it arrives and that is that.

Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no proper way to know if the port has been opened or not.  The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really).  The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream.  It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.

To check the status of those lines in your sketch you can examine the boolean operator of the Serial object:

if (Serial) {
  // I am connected
} else {
  // I am not connected
}

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a connection in UART terminology, only data.


Arduino on battery getting unstable if temperature falls i am building an outdoor sensor with a combination of a custom Arduino board and a battery (+solar charging). I experience strange behavior when the temperature falls below a certain value (i can reproduce it by putting it in the freezer), regardless which type of battery i am using. The custom Arduino runs without power-regulation, straight from the 3.7volts the battery can provide.
How can i prevent this to happen? I guess a little heating would be not really a solution as i am trying to consume as less energy as possible.
Would a (step up) regulator possibly help? Any other ideas?

---Update---
Thanks to your comments here i figured out, that the AVR 328p should not be operated below a voltage of 3.7v if run at 16Mhz. As i am running with a 3.7v LiPo Battery that could easily explain my problem i guess. My first try to decrease the processor speed to 8Mhz with a Prescaler worked, but the GSM Fona does not seem to like it. So i would like to try something in between like 10Mhz or 12Mhz. As the prescaler does not support this, my question is: can i just use another crystal or would i have to modify something in the code/bootloader as well?

To answer your modified question:

Running the ATmega328p at 16Mhz with 3.7v is out of spec - see this EESE answer for reference or the ATmega datasheet - so the obvious solution would be to lower its speed to 8Mhz.

But since you also mentioned that there is an additional GSM breakout board involved (Adafruit Fona), which expects UART (in auto-baud mode) Rx/Tx connection, it might not be that trivial. Further exploration of the Fona library's source code reveals that it has several hard-coded delays (see Adafruit_FONA.cpp::begin, for example), but its core seems to be implemented inside the Adafruit_FONA::readline method, which uses an underlying Stream, which in turns comes from a Software/Hardware serial object, as shown in the FONAtest.ino example that comes with the library.

From my experience, Software/Hardware serial should work fine on 8Mhz, except maybe when using high baud rates, which is solvable.
The hard-coded delays doesn't look like they should cause actual damage except for delay, but you could cut them in half just to see if you can make the library work.

Additional aspect that you should consider is the comment from Adafruit's Fona product page, regarding pin Vio:

  This is the pin that you MUST drive with an external voltage from
  3V-5V to set the logic level converter

So, despite that from the datasheet, the Fona seems to have a voltage regulator, you might still want to consider adding a decoupling capacitor between Vcc and Gnd of your battery, to  mitigate transient current draws from any component in your circuit.


Passing variable value in structure object in this code i want to pass value of variable char array 'pass' in object "MyObject". But i am getting this error.

    Arduino: 1.6.11 (Windows 8.1), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\XXX\Desktop\EEPROM_put\EEPROM_put.ino: In function 'void setup()':

EEPROM_put:17: error: array must be initialized with a brace-enclosed initializer

};

^

exit status 1
array must be initialized with a brace-enclosed initializer

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

when i change pass to *pass, result of EEPROM.get() is 1 and 6, instead of 1, 62345, 7539514682.

#include <EEPROM.h>
struct MyObject {
boolean stat;
char password[6];
char mobile[11];
};

char pass[6]="62345";
void setup() {
Serial.begin(9600);
while (!Serial);
MyObject customVar = {
  1,
  pass,
  "7539514682"
 };
EEPROM.put(1, customVar);
Serial.print("Written custom data type!");
}

void loop() {

}

Use class and constructor

#include <EEPROM.h>
class MyObject {
    boolean stat;
    char password[6];
    char mobile[11];
  public:
    MyObject(bool tempStat, char tempPassword[], char tempMobile[])
    {
      stat = tempStat;
      strcpy(password, tempPassword);//As suggested by mikael
      strcpy(mobile, tempMobile);
    }
};

char pass[6] = "62345";
void setup() {
  Serial.begin(9600);
  while (!Serial);
  MyObject customVar(true, pass, "7539514682");
  EEPROM.put(1, customVar);
  Serial.print("Written custom data type!");
}


Instead of 1 and 0, make display say On or Off So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial.  But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup(){
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("System Activated");
    //
    lcd.setCursor(0, 1);
    lcd.print("Ready...");

    pinMode(inPin, INPUT);
    pinMode(outPin, OUTPUT);

    Serial.begin(9600);
    Serial.println("System Activated");
    Serial.println("Made by Mateo Holguin");
    Serial.println("0 = Light is Off | 1 = Light is On");
    Serial.println("=======================================");
}

void loop(){
    reading = digitalRead(inPin);

    if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        Serial.println("Button Switch State Change:");
        if (state == HIGH)
            state = LOW;
        else
            state = HIGH;

        Serial.println(state);
        Serial.println("");
        lcd.clear();
        lcd.print("State: ");
        lcd.print(state);

        time = millis();
    }

    digitalWrite(outPin, state);

    previous = reading;
}

Put the strings to display in an array, and output them instead.

char const * const stateDisplay[] = {"Off", "On"};

 ...

lcd.print(stateDisplay[state]);


Pro Micro ATMEGA32U4 unable to upload I have a simple flashing led program that I want to upload on my pro micro (see image) but it doesnt work (see image: no port available, Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.)

I have successfully uploaded this program on my arduino uno.

Ive followed this guide for the drivers and more.
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows

Thanks for help

Your board will only present a serial port if the sketch that is running on it is programmed to present a serial port. The board does not have an actual serial port for communication with the PC - only what the sketch provides.

If the sketch doesn't provide one, or if the sketch isn't running (for example if it was compiled for the wrong board by accident) then you will never see a serial port.

Since the "normal" way of resetting the board to enter the bootloader (which does present its own serial port) is to open the serial port at 1200 baud, since you don't have one to open it's kind of hard to get to the bootloader. However, depending on what bootloader you have installed there are a number of options that can help you:

Briefly connecting RST to GND just before uploading may activate the bootloader for a few seconds.
Doing the above twice in rapid succession may activate the bootloader for longer (depending on the bootloader version)

Erasing the chip and reinstalling the bootloader is the only real way that is guaranteed to work, though. But that said, I have seen boards come out of China without any bootloader at all - so reinstalling the bootloader is always a good first option with cheap boards.  You can use your Arduino UNO as an ISP programmer (using the ArduinoISP sketch and treating it like you're making a breadboard Arduino).


How does Arduino UNO deal with bit shifting? Explanatory comment: I'm a beginner. I'm examining the feasibly of bit shifting to the right 6 places to divide up the range of the Arduino ADC (has a range of 0 to 1023) to something much smaller. Such that any number in the ADC registers, between 0 and 63 produces a value of 0, a number between 64 and 127 a 1, between 128 and 191 a 2, between 192 and 255 a 3, etc. There is a change every 64 increase in the initial number.

I think this is possible to do. But some doubt has been expressed I think.

As far as I have determined, after right shifting 6 places to the right the following values of numbers are resident in the ADC registers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.

I wish you to consider, is there anything in the way Arduino's IDE works, or with the nature of the initial number in the register (signed/unsigned) that makes the results I have indicated false.  I think, that the initial number will be unsigned, just guessing.

There are two types of right-shift in C - logical and arithmetic.

GCC (which is the compiler the Arduino IDE uses) selects which one to use depending on whether the type you are shifting is signed or not:

If it's signed then use an arithmetic shift
If it's unsigned then use a logical shift

In a logical shift, the value is literally shifted to the right padding the left side with zeros. An arithmetic shift, however, shifts and extends the sign. I.e., it performs an arithmetical "divide by 2".  That means if you right shift a negative value to still have a negative value (Note: this behaviour is implementation specific, so is only applicable to GCC. For other compilers in other situations you will have to check the documentation of that compiler).

So if you store the results of analogRead() in an unsigned integer variable >> N will right shift the value N times. If you store it in a signed integer it will divide the value by 2 N times.

For a positive value, which the results of analogRead() will be, the end result is the same - divide by 2 N times.

So if you right-shift 6 times you reduce a 10-bit value down to (10-6) 4 bits. 24 is 16, so you get 16 possible values.  24-1 is 15, so you get values 0-15 in your final value.


Cannot include .h files back one directory I am working on a project with multiple arduinos. I want my folder structure to be as follows:

/
  libs/
    someSharedFile.h
  arduino1/
    arduino1.ino
  arduino2/
    arduino2.ino

When I include someSharedFile.h in one of my .ino files like this #include "../libs/someSharedFile.h", I get this error No such file or directory.

However, when I move libs/ to arduino1 and include the shared file like this #include "libs/someSharedFile.h" everything works fine.

I am using IDE 1.6.7 on windows 10.

Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in [your home folder]/arduino/libraries


GY91 IMU module, Interrupt? Are there interrupt Pin in the GY91 Module?
If not, are there good alternative for periodic sensor reading?
(apart from mcu schedule/external timer)

No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.

The only way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.

If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


What Arduino boards would be compatible? I am considering using an arduino over the raspberry pi for a new project. However, I am not sure what arduino I should buy so that it is compatible with the below add-on.

Are all Arduinos compatible?

TIA.

Edit:

Link to product- https://www.adafruit.com/product/3387

My goal is to use an arduino with the above product to move a 3D model in Unity 3D.

As one can see from the pinout description page (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/pinouts):

So this board is literally designed to be powered by 3.3V and 5V and have compatible logic levels for both these voltage ranges, which is what every Arduino known to me and the Raspberry Pi use.

Furthermore, there is also Arduino Code (https://github.com/adafruit/Adafruit_LSM9DS1)  which is compatible with pretty much every Arduino Core and Raspberry Pi Python code (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/python-circuitpython).

So by means of voltage levels and platforms, this board is highly compatible with everything out there that is either 3.3V or 5V powered and has a SPI or I2C peripheral.


Why are pin 18 and 19 always HIGH? I wired my switch just like in the default button program. I know it works because it works fine on other pins, just not pin 18 or 19. What am I doing wrong?

const int buttonPin = 18;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

The analog pins function as digital pins number 14 - 19, with 14 being A0 and 19 being A5. I had hooked it up backwards.

This time we're gonna get funky
Everybody check your pins
Check check check check your pins
Check check check check your pins


Why is my arduino now working with my LCD 16x2 displays? So I've tried with 3 different lcd screens and each one has given me something different (https://imgur.com/a/EVzFoVv) and here is my code

#include "LiquidCrystal.h"

// initialize the library by providing the nuber of pins to it
// LiquidCrystal lcd(8,9,4,5,6,7);
LiquidCrystal lcd(52, 50, 48, 46, 44, 42);

bool isSetup = false;

int want = 600;
int live = 615;

void setup() {
  lcd.setCursor(0,1);
  lcd.print("   Booting Up");

}
void loop()
{
  if(isSetup == false)
    Set();
}

void setupIs(){
  Clear();
  isSetup = true;
  lcd.setCursor(0,0);
  lcd.print("Want: ");
  lcd.setCursor(0,1);
  lcd.print("Live: ");
}
void Set(){
  lcd.begin(16,2);

// set cursor position to start of first line on the LCD
lcd.setCursor(0,0);
//text to print
lcd.print("WANT: 1500");
// set cusor position to start of next line
lcd.setCursor(0,1);
lcd.print("LIVE: 1800");
}

void Clear(){
  lcd.setCursor(0, 0);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  lcd.print("                ");
}```

Well first when looking at your code what you are essentially doing using the Clear() function is that you are writing something to the memory of your lcd screen again.If you really want to clear the display you could use lcd.clear().Try changing that.
And make sure that your wiring is correct.


Talking to Eurotherm 2416 temperature controller over modbus rs232 I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:

/**
 *  Modbus master example 2:
 *  The purpose of this example is to query several sets of data
 *  from an external Modbus slave device.
 *  The link media can be USB or RS232.
 *
 *  Recommended Modbus slave:
 *  diagslave http://www.modbusdriver.com/diagslave.html
 *
 *  In a Linux box, run
 *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
 *  This is:
 *      serial port /dev/ttyUSB0 at 9600 baud 8N1
 *      RTU mode and address @1
 */

#include <ModbusRtu.h>
#include <SoftwareSerial>

SoftwareSerial mySerial (3,5);

uint16_t au16data[16]; //!< data array for modbus network sharing
uint8_t u8state; //!< machine state
uint8_t u8query; //!< pointer to message query

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram[2];

unsigned long u32wait;

void setup() {
  // telegram 0: read registers
  telegram[0].u8id = 1; // slave address
  telegram[0].u8fct = 3; // function code (this one is registers read)
  telegram[0].u16RegAdd = 1; // start address in slave
  telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
  telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

  // telegram 1: write a single register
  telegram[1].u8id = 1; // slave address
  telegram[1].u8fct = 6; // function code (this one is write a single register)
  telegram[1].u16RegAdd = 2; // start address in slave
  telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
  telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

  Serial.begin(9600);
  master.begin( &mySerial, 9600); // baud-rate at 9600

  master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
  u32wait = millis() + 1000;
  u8state = u8query = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    master.query( telegram[u8query] ); // send query (only once)
    u8state++;
    u8query++;
    if (u8query > 2) u8query = 0;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 1000;
    }
    break;
  }
   Serial.print(au16data[O]);

  au16data[4] = analogRead( 0 );

}

I can read process values with telegram[0] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram[1]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?

Thank you!

You could also take a look at this github project:
https://github.com/ukos-git/arduino-eurotherm2416

It is specifically designed for the purpose you ask for.
It basically includes Module named Temperature and a possibility to set or read it:

Temperature.set(100)
t = Temperature.getTemperature()

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.


How do I upload sketch (and parameters) through a user interface I'm pretty new to Arduino and I'm developing my first real-world project.

I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.

What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:

How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?
When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

1) Why not just

system("avrdude ...");

That's more or less what the Arduino IDE does.

2) If you really want to embed the data in the executable, see
Embedding Blobs in
Binaries.
You would need to re-link and re-upload the program each time you change
that data. You won't need the Arduino IDE, as it's only job is basically
to call avr-g++ and avrdude. You can use the IDE if you find it's CLI
easier than those of the standard tools.

If you put the data in EPPROM instead, the avrdude can upload it without
re-uploading the program.


Can I use the microchip of Arduino Uno as a standalone microcontroller I want use the ATmega328P chip of the Arduino Uno board as a standalone device.

Is that possible?
Which pins are which on the Arduino board and the ATmega328P?
Do I need any external components?

Yes it's possible. To use the ATmega328P to "emulate" an Arduino Uno board (without the USB part) you just need 3 ou 4 additional components: the oscillator, two capacitors and a resistor. Please take a look at: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard for a schematic/breadboard.
The Atmega328P features itself the memory, cpu and flash so those components are already inside the chip. You can find the relation of the pins in this image:


Is the a low memory alternative to SoftwareSerial? I'm running a program on a ATtiny85 and running into problems because of a lack of available RAM. When I ran avr-nm on my ELF file I found that SoftwareSerial was taking up a lot of RAM even though I'm just using it to set the data transfer rate with mySerial.begin(9600); and nowhere else.

So I'm wondering if there is another way of doing this without using so much memory:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

mySerial.begin(9600);

Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace #define _SS_MAX_RX_BUFF 64 on line
42
by something smaller. If your loop() runs fast enough (no delays, no
blocking code) you could probably get away with buffering only a very
few bytes.

Or you could rewrite the library so that, instead of buffering the
incoming bytes, it handles them to you for processing. See for example
this receive-only UART code based on the USI
port for an illustration of the
approach.


Arduino ESP8266 - wifi evt: 3 and wifi evt: 7 meaning? I'm getting these in my serial port, but what does wifi evt 3 and 7 mean?
I am trying to complete this tutorial. https://youtu.be/4Z0gBG8dkqw

The PHP file is on my hosting, and the ESP reads out the temperature and humidity from the sensor so that's fine.

The serial code:

Connecting
wifi evt: 3
Connected
Temperature:
24.10
Humidity:
39.70
[hostByName] request IP for: lucasdebelder.be
[hostByName] Host: lucasdebelder.be IP: 185.182.57.81
connected
HTTP/1.1 200 OK
Date: Fri, 11 May 2018 13:14:17 GMT
Server: Apache/2
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 0
Content-Type: text/html; charset=UTF-8

�
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7

The code that I am running in Arduino.

#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_email.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

The codes are explained in this forum thread. The wifi event types are  described here (and also duplicated here, which are ultimately coming from the Espressif Non-RTOS SDK, chapter 6.2.4):

typedef enum WiFiEvent
{
    WIFI_EVENT_STAMODE_CONNECTED = 0,
    WIFI_EVENT_STAMODE_DISCONNECTED,
    WIFI_EVENT_STAMODE_AUTHMODE_CHANGE,
    WIFI_EVENT_STAMODE_GOT_IP,
    WIFI_EVENT_STAMODE_DHCP_TIMEOUT,
    WIFI_EVENT_SOFTAPMODE_STACONNECTED,
    WIFI_EVENT_SOFTAPMODE_STADISCONNECTED,
    WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED,
    WIFI_EVENT_MAX,
    WIFI_EVENT_ANY = WIFI_EVENT_MAX,
    WIFI_EVENT_MODE_CHANGE
} WiFiEvent_t;

The enum's values are increasing downwards, meaning that 7 is WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED. Receiving a probe request means that some other device has scanned the surrounding WiFi networks and your ESP answered. This indicates that your ESP is in the Software Access Point (AP) + Station (SoftAP + STA) mode. But you only want to be a station in your own WiFi network, not an access point yourself.

The output is triggered by this function.

This comment on an issue suggests that you add WiFi.mode(WIFI_STA); to your setup, like

void setup() {
  WiFi.mode(WIFI_STA);
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

Subsequently, a WiFi event 3 indicates WIFI_EVENT_STAMODE_GOT_IP. Which also makes sense because you're telling the module to connect to the WiFi, it acquires an IP over DHCP and is then fully connected. This message is harmless since it doesn't indicate an error.

You should investigate on why these debug messages are thrown in the first place. The messages are only printed if two macros are set: DEBUG_ESP_WIFI and DEBUG_ESP_PORT (see here). So something must do #define DEBUG_ESP_WIFI and #define DEBUG_ESP_PORT Serial somewhere.

This is either done in some compiler settings which you are not aware of or because you modified a header file to include this change. Either way, you can try to use the #undef pre-processor macro to remove these definitions again before including the library. Change your first line to the following:

//Try to kill the DEBUG defines
#undef DEBUG_ESP_WIFI
#undef DEBUG_ESP_PORT
#undef DEBUG_WIFI
#include <ESP8266WiFi.h>


DHT11 Sensor Code Fatal Error I recently tried using Hobbyist.co.nz's guide on the DHT11 sensor. I installed the Adafruit_Sensor and DHT11 Sensor libraries,  but it keeps returning with a fatal error.

Here is the code and the error:

#include <dht.h>

#define dht_dpin A0 //no ; here. Set equal to channel sensor is on

dht DHT;

void setup(){
  Serial.begin(9600);
  delay(300);//Let system settle
  Serial.println("Humidity and temperature\n\n");
  delay(700);//Wait rest of 1000ms recommended delay before
  //accessing sensor
}//end "setup()"

void loop(){
  //This is the "heart" of the program.
  DHT.read11(dht_dpin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  delay(800);//Don't try to access too frequently... in theory
  //should be once per two seconds, fastest,
  //but seems to work after 0.8 second.
}// end loop()

C:\Users\XXXXXX\Documents\Arduino\sketch_dec19c\sketch_dec19c.ino:2:17:

  fatal error: dht.h: No such file or directory

#include <dht.h>

The examples I can see from Adafruit say

#include "DHT.h"

or

#include <DHT.h>

But you wrote

#include <dht.h>

They aren't the same.

Further, the examples for the Adafruit library show usage like:

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

But you call DHT.temperature and DHT.humidity.

If you are meaning to use the Adafruit library, you have to write your code according to their documentation.

Also of note, you have defined the type of the object as dht and the name as DHT, but for Adafruit, the type is DHT.

EDIT:

The example on the website you note has a downloadable zip file for the DHT library they use. You cannot assume that all libraries for interfacing a certain sensor will all have the same programming interface.


Parse long CSV file with esp8266 I'm trying to write a code for nodeMCU (esp8266 based board) to continuously calculate distance between GPS location and geographical coordinates written in a CSV file in SD. Originally I thought the best way to do it was to parse the file, save the longitudes and latitudes in two arrays at startup and, then, calculate continuously distances between arrays and coordinates taken from GPS. If distance is less than a value, an output warns me. There is only a "little" problem: the file contains 5500 coordinates and, so, it is impossible to allocate two arrays containing 5500 floats inside ram memory. Now I have thought two alternatives:
1) save the two arrays in flash memory that is, I know, a lot slower but also bigger
2) parse and calculate distance line by line continuously: in a loop I'll take the first line from SD, parse it, calculate distance between it and GPS location and, then do the same thing for second, third,... line. It requires the continuous access to SD and parsing but I don't have to use flash memory.
What is the best option in your opinion? Have you got alternatives or suggestions?
Thank you!!

Instead od the SD card you can use the esp8266 file system SPIFFS. It uses the flash of the esp8266, which is connected at 40MHz as Quad I/O on newer systems.

To use SPIFFS you create a folder named data in your esp8266 sketch folder. You put the files in that folder and then you use the SPIFFS upload plugin.

In runtime use the SPIFFS library. It is similar to SD library.


Uno to Mega and where is the error for the interrupt that isn't delared? I want to read a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R).
A couple questions, I found out that an Uno can only handle 2 interrupt pins and I think I need 3 for the Index.  What do I need to do to the following code to get it to run on a Mega which I believe can handle 3 interrupt pins?

Also I am getting a 'outAChange' was not declared in this scope.
What am I missing here.

I will be using the data from the encoder value to run a NeoPixel 60 for a directional mast/antenna.

Here is the code I am trying to use:

// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup(){  // set encoder pins
pinMode(outA, INPUT_PULLUP);
pinMode(outB, INPUT_PULLUP);
pinMode(outZ, INPUT_PULLUP);  //Index

// attach interrupts to pins
attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);

// initialize serial
Serial.begin(57600);
}

void loop(){

if (encoder_save != encoder)  // only print if new value
encoder_save = encoder;

// If Index(Z) reads low reset encoder to 0
if (digitalRead(outZ) == LOW)
{
  encoder = 0;
}
}

{
Serial.println((encoder * 360)/360);
}
}

// interrupt routines
void outAChange(){
// when outA changes, outA==outB means negative direction
encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;
if (encoder < 0)
{
  encoder = (encoder + 360);
}
}

void outBChange(){
// when outB changes, outA==outB means positive direction
encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;
if (encoder >= 360)
{
  encoder = (encoder - 360);
}
}

Your brackets are all messed up.  If you pass your code through an autoformatter (such as the one included in the IDE) you end up with this:

// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup() { // set encoder pins
    pinMode(outA, INPUT_PULLUP);
    pinMode(outB, INPUT_PULLUP);
    pinMode(outZ, INPUT_PULLUP);  //Index
// attach interrupts to pins
    attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);
// initialize serial
    Serial.begin(57600);
}

void loop() {
    if (encoder_save != encoder) { // only print if new value
        encoder_save = encoder;
    }

// If Index(Z) reads low reset encoder to 0
    if (digitalRead(outZ) == LOW) {
        encoder = 0;
    }
}

{                                                << WHAT
    Serial.println((encoder * 360) / 360);       << IS
}                                                << THIS
}                                                << CODE?

// interrupt routines
void outAChange() {
// when outA changes, outA==outB means negative direction
    encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;

    if (encoder < 0) {
        encoder = (encoder + 360);
    }
}

void outBChange() {
// when outB changes, outA==outB means positive direction
    encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;

    if (encoder >= 360) {
        encoder = (encoder - 360);
    }
}

As you can see, after the end of your loop() function, you have an extraneous block of code with a bunch of random brackets.

You need to decide where in your program that should actually be and move it there, deleting those extra brackets.


Velocity from Sensor Data - Best Approach? I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity.

What is the best approach to get accurate, smooth, and fast data to my control logic?

Would I benefit from combining accelerometer and barometric data? If so, how?

Background:

I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.

Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.

I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.

Thanks!

Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).

The first few things to address are in regard to the barometer:

(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data before passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.

(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there.  (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."

Just one more thing before we get into the filter...

It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.

Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.

One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between [-1, 1]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.

Regardless, here's some insight that may be useful:

The Kalman filter is very much dependent on how you model your system.

To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):

Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.

We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:

The filter works fairly well.

But what if our model happened to be off - that is, it doesn't reflect what's really happening?

In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.

This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.

There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag",  you need to use what is known as an extended Kalman filter - which basically linearizes your data.

Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.

In any case, I hope this helped. Feel free to ask any questions.

(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).


Arduino -> Processing conversion: creating mux channels As the title alludes to, I'm in the process of converting an Arduino sketch to a Processing sketch. So far, mostly pretty straightforward.

I'm running into an issue with creating an array of ints for the channels for two muxers. Below is the code that I currently have working for the Arduino sketch:

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 8; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  analogWrite(SIG_pin, testValue);

  //return the value
  return 0;
}

Below is the slightly varied version that I'm using for my Processing-equivelent sketch.

int readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  arduino.analogWrite(SIG_pin, testValue);

  int val = 0;
  return val;
}

I'm currently getting an error of unexpected token: int error at the following line:

  int muxChannel[20][8]={

And, an error of The type of expression must be an array type but it resolved to int at this line:

digitalWrite(controlPin[i], muxChannel[channel][i]);

Thank you!

When making an array I processing you must use the code

int[] xyz = \*declare variable or new*\ {
    this is some code
}

You used

int xyz[num][num]

You must declare the values of the array only after declaring it.
Also, did you try declaring digitalWrite as a new variable?


Running Python on Arduino I've been using Python for quite long, and I was wondering if it can be used as a programming language for Arduino, rather than C/C++.

When I'm using the Arduino IDE, the sketch is compiled into a hex file that contains the program binary.

Knowing that micro controllers execute only binary, I would like to know if there is a tool to convert Python code into binary, so that I can upload it directly to Arduino using AVR or other programmers.

I read about Micro Python, a lightweight adaptation of Python that can fit in boards, but can only work with PyBoard, which I have never used yet.

I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in IOT.

To my knowledge, there is not a "python to ATMega architecture" compiler out there.

However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.

Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.


Is there a way of turning a computer into a Arduino type board? The Arduino's processing power is not sufficient for some of the tasks I would like it to perform...

I'm thinking of making a Home Automation System and would like some serious processing power at the center of it all.

So I'm wondering if I can just use standard PC parts to essentially put together my own board?!?

Is this possible???

A regular Arduino uses an AVR, more "pimped" Arduino might go to ARM. Some special versions of Arduinos uses other chips, such as the ever iconic ESP8266.

For home automation, an ESP8266 is WAY enough. Using an ARM is quite and overkill for home automation. But I've never seen anybody using a full PC for it. Why? Because it is around 10-20 times more expensive. They require much more components and many other things.

Something close to a full PC that you can get is a Raspberry Pi (any version would do). They act like a small PC, some even use it as a laptop. See PiTop. The Raspberry Pi is stronger, more powerful, and much faster then any Arduinos. The Pi also has ethernet, a graphic interface, and an audio interface built in. That means that you can pretty much connect it to a monitor and it will work as a normal PC running either Windows or Linux. You can then watch a video, with graphics and sound, from the inthernet without external modules like you would need on an Arduino. Their only weakness is that it is harder to program them to read may sensors. That is why the Arduino is popular for covering that.

At the end of the day, it is your choice. I would personnally suggest an ESP8266. This module has many GPIOs, depending on the breakout that you have, and has WiFi built in. This is a great feature for home automation. Most home automation builders use this module.

If you have any questions about the informations I just gave you, comment it, I'll reply.


How to only detect the opening and closing of door sensor once im quite new to Arduino coding. Currently im trying to create an alarm and when the alarm ring, the user will just need to remove the door sensor once to stop the alarm and listen for the next alarm. What i have is Real Time clock module to keep track of the time.

So i have tried to code on my own but failed and here's the outcome:
After the alarm ring, and i remove the door sensor from each other, it stopped buzzing (Which is correct partly) but once i put it back together, it continued to ring for the alarm duration (Which was set as 1 min)

Here's the code i had:

#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
DS3231  rtc(SDA, SCL);
Time  t;
#define buz 11      //This is Buzzer that is plug into pin 11 (Change it accordingly to what you will be putting it in the arduino)
int Hor;            // This is declaring the alarm in Hours
int Min;            // This is declaring the alarm in Minutes
int Sec;            // This is declaring the alarm in Seconds
const int sensor = 10;    // Door sensor connected to Pin 10
int state; // 0 close - 1 open switch

void setup()
{
  Wire.begin();
  rtc.begin();
  Serial.begin(9600);
  pinMode(buz, OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Alarm");
  lcd.setCursor(0,1);
  lcd.print("Test");
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
  delay(2000);
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());

  alarm1();
  alarm2();
  delay(1000);
}

void Buzzer()
{
  digitalWrite(buz,HIGH);
  delay(500);
  digitalWrite(buz, LOW);
  delay(500);
}

void alarm1() //E.g. This is the first alarm for the medicine
{
  state = digitalRead(sensor);
  if( Hor == 20 && (Min == 11 || Min == 12) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else if ( Hor == 20 && (Min == 11 || Min == 12) && state == 1)
  {
    noTone(buz);
  }
  delay(200);
}

void alarm2()
{
  if( Hor == 19 && (Min == 48 || Min == 49) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else
  {         //Once user open the door sensor, the alarm will stop buzzing
    noTone(buz);
    alarm1();
  }
  delay(200);
}

Just to clarify that the variable state i took from

http://www.instructables.com/id/How-to-Use-a-Magnetic-Door-Switch-Sensor-With-Ardu/

So to summarised my problem, i am trying to get the system to read the opening of the door sensor once so that the alarm will stop and listen to the next alarm regardless if i put it back the door sensor or not
Really hope someone can help me thanks for you kind attention

As often, the answer to this question is “Implement a ‘Finite State
Machine.’”. In this instance, you need at least three distinct
states:

ARMED: the buzzer is not active, but it is only a matter of time...
ON: bzzzz... bzzzz... bzzzz...
STOPPED: the user has stopped the alarm.

Each of your alarms should have a start time and a stop time (say, two
minutes after the start time). Then, the possible state transitions are:

ARMED → ON: when we hit the start time of an alarm
ON → STOPPED: when the user stops the alarm
ON → ARMED: when we hit the stop time of the alarm
STOPPED → ARMED: when we hit the stop time of the alarm

Notice that, once the user stops the alarm, the only way for the buzzer
to start buzzing again is by going through the transitions STOPPED →
ARMED → ON. The first transition happens at the alarm's stop time,
whereas the second one happens at the next alarm's start time.

You did use a kind of state variable in your code, but the problem is
you failed to realize that ARMED and STOPPED should be distinct
states. If you fuse these states together then, when the user stops
actively “stopping” the alarm, and if it's still start time, the
system transitions immediately back to the ON state.


Reading 2 numbers from serial I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using Serial.read(). Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).

As turned out, my problem was in another portion of the code and all below code works perfectly as is!

How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.

If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of [0;7] and [1000;2000]. Thanks for any advice. Disclaimer, I read a lot, including this, but most questions go into detail about the packaging format, whereas I am concerned about the reading method.

Code I use at the moment:

// read numbers from the char representation!
// on the serial connection
// each DIGIT is sent separately

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
uint8_t channel; // holding the number of the channel to modify
uint16_t signal; // ppm signal length in us (1000-2000)

void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
  if (stringComplete) {
    channel = uint8_t(inputString[0])-48;
    signal = 0;
    for (uint8_t n=1; n<5; n++) {
      signal = (signal*10) + uint8_t(inputString[n])-48;
    }
    Serial.print(F("ch: ")); Serial.print(channel);
    Serial.print(F(" signal: ")); Serial.print(signal);
    Serial.print(F("\n"));
    //PROCESS Data
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    // if the incoming character is a
    // newline (10) or carriage return (13)
    // set a flag for a complete transmission
    if (inChar == 10 | inChar == 13) {
      stringComplete = true;
    }
  }
}

Another version I tried, without strings is:

// channel and pulse-length
uint16_t numbers[2] = {0, 0}; // channel,value
uint8_t buf[5];

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

void loop() {
  if (serial_input(numbers,buf)) {
    numbers[0] = buf[0]-48;
    numbers[1] = (buf[1]-48)*10+(buf[2]-48);
    Serial.print(F("channel: ")); Serial.println(numbers[0]);
    Serial.print(F(" signal: ")); Serial.println(numbers[1]);
    // Do Stuff
  }
}

uint8_t serial_input(uint16_t* num, uint8_t* buf) {
  uint8_t newData = 0;
  uint8_t k = 0;
  num[0] = 0; num[1] = 0;
  while(Serial.available()) {
    delayMicroseconds(2100);
    char ser = Serial.read();
    if (isDigit(ser)) {
      buf[k] = uint8_t(ser);
      k++;
      newData = 1;
    } else {break;}
  }
  return newData;
}

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:

void serialEvent() {
  if (!newdata) {
    channel = Serial.parseInt();
    signal = Serial.parseInt();
    newdata = true;
  }
}

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...

115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.

serialEvent() is no better than manually looking at things like serialAvailable() in your loop since that is all it does anyway. It just runs after each iteration of your loop.

One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:

// Input text in the form "123 456\n"
char instring[20]; // Room for 19 characters plus terminating null
int spos = 0; // Location in the array
int val1 = 0;
int val2 = 0;

void loop() {
    if (Serial.available()) {
        char *bita, *bitb;
        int c = Serial.read();
        switch (c) {
            case '\r': break; // ignore
            case '\n':
                 spos = 0;
                 bita = strtok(instring, " ");
                 bitb = strtok(NULL, " ");
                 if (bita && bitb) {
                     val1 = atoi(bita);
                     val2 = atoi(bitb);
                 }
                 // You now have two new values in val1 and val2
                 break;
            default:
                if (spos < 18) {
                    instring[spos++] = c;
                    instring[spos] = 0;
                }
        }
    }
}


How to communicate with GPS SIM900a without Serial Monitor I am fairly new to Arduino. I was working on a project where I use a GSM SIM900a modem interfaced with an Arduino. The AT commands are sent via the Arduino to the GSM Modem. The problem, however, is that the commands are only sent when I open the Serial Monitor. I have an IR proximity sensor and I would like the AT commands to be sent when the sensor detects an object. I am putting the code for the GSM modem below (I have not yet put in the code for the IR sensor).I want to know how to send the AT commands when the Arduino is hooked up to a battery and not to a PC

#include <SoftwareSerial.h>
SoftwareSerial myGsm(7,8);
float temp;
int tempPin = 0;
void setup()
{
 myGsm.begin(9600);
 Serial.begin(9600);
 delay(500);

myGsm.println("AT+CIPSHUT");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CIPMUX=0");
 delay(2000);
 printSerialData();

 myGsm.println("AT+CGATT=1");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CSTT=\"bsnlnet\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks
 delay(5000);
 printSerialData();

 myGsm.println();
 myGsm.println("AT+CIICR");
 delay(6000);
 printSerialData();

 myGsm.println("AT+CIFSR"); //init the HTTP request
 delay(2000);
 printSerialData();

 myGsm.println("AT+CIPSTART=\"TCP\",\"122.178.80.228\",\"350\"");
 delay(5000);
 printSerialData();
 delay(5000);

 myGsm.println("AT+CIPSEND");
 delay(2000);
 printSerialData();

sendtemp();
delay(3000);
myGsm.println("AT+CIPCLOSE");
printSerialData();

myGsm.println("AT+CIPSHUT");
delay(1000);
printSerialData();
}

void loop()
{
}

void printSerialData()
{
 while(myGsm.available()!=0)
 Serial.write(myGsm.read());
}

void sendtemp()
{
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
  Serial.print("TEMPERATURE = ");
  Serial.print(temp);
  Serial.print("*C");
  Serial.println();
  delay(5000);
 myGsm.println(temp);
 delay(3000);
 printSerialData();
 myGsm.write(0x1A);
 delay(3000);
   printSerialData();

}

Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)


What happens if I connect an external power supply, plus to GND and minus to VIN? So far, I have connected plus to VIN and minus to GND, but I am curious what would happen if I do it the other way around. And I am not going to try in case I break someting.

So, what will happen?

Some systems have protection against people connecting things in reverse.
Some don't.

On unprotected systems you MAY destroy the powered system and/or you MAY destroy the power supply - both these depend on happenstance, system design and luck.

Possibly worse - you may damage the target system in an inobvious way so that it subsequently behaves incorrectly or damages other equipment.

Systems which are designed to be protected may not be protected in all cases. eg if you have a "shield" connected that accesses the Vin pin outside the protection diode the reverse polarity voltage may damage the shield AND current may travel via the shield circuitry back into the Arduino via other connections.

Advice on You tube may just sometimes very very occasionally be wrong. Or more often.

If this "Reference Schematic"  is correct (as you'd hope it was) then Vin is connected to the "inside" of protection diode D1 - so D1 does not protect against reversed polarity. See lines and boxes in red.
Larger version of diagram here

D1 does protect against reversed polarity on "PWRIN".
How PWRIN relates to shield feeding I know not.


Arduino IDE not compile .S program to board After answering my previous question correctly I'm getting all sorts of errors when trying to compile the following program:

I'm completely new to both assembly and the arduino IDE so I apologise in advance for any basic errors.

sketch.ino:

#include "blink.S"
extern void blink();
void setup() {
  // put your setup code here, to run once:
blink();
}

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

}

blink.S file:

#define __SFR_OFFSET 0
#include <avr/io.h>

  .section .text

  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

  mov r16, r18    ; copy mask 00100000 also to r16

loop: out PORTB, r16    ; switch on or off the pins of port B
        ; according to bit pattern in r16

  ldi r17, 82   ; 1000ms delay, see below

outer_delay:
  clr r1
middle_delay:
  clr r2
inner_delay:
  dec r2      ; 1 clock tick
  brne inner_delay  ; 2 clock ticks when z!=0, 1 tick when z=0.

  dec r1      ; when this line is reached, about
        ; 256*3 = 768 ticks have been consumed since inner_delay.
  brne middle_delay ;

  dec r17                 ; when this line is reached, about
        ; 256*256*3 = 196608 ticks have been
        ; consumed since middle delay.
  brne outer_delay

  eor r16,r18   ; invert bit 5 in r16 using exclusive or.
  rjmp loop   ; jump back to loop.

There's four things I can see wrong (one of which is my fault, actually - I should have mentioned it in the previous question - nevermind).

Firstly you cannot include a .S file in a .INO file. A .S file is assembly, a .INO file is C++. You can't mix the two in one file (and including a file does just that - includes the file verbatim at that point). So remove that #include. Otherwise it would be like opening a book written in English only to find the preface is written in Klingon.

Secondly you need to give your function a name. It doesn't have one at the moment. Naming the file is not naming the function.

So you need to provide a label at the entry point:

  .section .text

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

Third you need to export that name as a global symbol:

  .section .text
  .global blink ; << This exports the function name

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

And finally you have the problem of linkage name munging.  You're linking a C++ file with (ostensibly) a C file - and C++ munges names. So you have to tell your C++ file that the function is not a C++ function, but a C function (which is what I should have mentioned previously):

extern "C" void blink(); // << Add the "C" to tell it not to munge the name

void setup() {
  // put your setup code here, to run once:
  blink();
}

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


Signal pin of buzzer is connected with which Arduino uno pin I bought a 3 pin buzzer. It has positive, negative and signal pin.

I don't understand how this signal pin should be connected with the Arduino.

Here is reported the description page of the buzzer.

As I have read in the page you have linked, I think you should program the Arduino to provide an impulse to the signal (s) pin.

Therefore, to answer your question you can use any digital pin of the Arduino. And I guess that as long as the impulse last as long as the buzzer will produce a sound.

Here an example of code:

int buzzPin =  2;    //Connect Buzzer on Digital Pin3
void setup()
{
 pinMode(buzzPin, OUTPUT);
}
 void loop()
{
 digitalWrite(buzzPin, HIGH);
 delayMicroseconds(50);
 digitalWrite(buzzPin, LOW);
 delayMicroseconds(50);
}


Where is Arduino on Fedora? I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

It depends how you installed it.

If you downloaded the tarball and extracted it then it's wherever you extracted it.

If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.

If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in ~/.arduino15