Arduino YUN Rev. 2 power supply I want to connect my YUN Rev. 2 to 7.4V.
I read that the older version only provides exactly 5 V at the Vin Pin. Is the Rev. 2 similar to it? I read that the power supply should be improved, but what does that mean?
I just tried to connect the Vin to regulated 5 V by a power supply board, but it didn't work. If I connect it to the 5V Pin the board is working, but I think this isn't recommended.
So has anybody experience with that board?
Thanks for your answers.

For version 1 VIN is connected, through a Schottky diode, to the 5V rail.  That means you can only provide, at absolute most, 5V plus a little bit for the diode drop into VIN.  The 5V pin can only source power on the Yun, since it is also connected to the 5V rail through a Schottky diode.

In effect the two pins form the "In" and "Out" of the 5V power.

However in version 2 the 5V pin's diode has been removed, and the VIN's diode has been reversed.  VIN is now known as "5V_OUT".

So the 5V pin can be used for both in and out, and what was VIN can only be used for power out.

To provide more than 5V to the Yun you will have to first pass the voltage through a regulator of some form.  Since you want to use 7.4V it sounds like you are using 2S Li-Ion (or similar) batteries.  Because of that I'd recommend a switching regulator, rather than a linear one.  I commonly use 5V UBEC modules from my favourite RC model supplier.

For version 1 you will provide it to VIN.  For version 2 you will provide it to 5V.  Quite why they'd change something quite so fundamental as the power pin arrangement from one version to another is beyond me.  It would cause havoc with compatibility between versions with certain shields.


ESP8266 NodeMCU v3 basic questions Can somebody please tell me what is the operating voltage of ESP8266?

What is the A0 voltage range?

I am powering it up from USB (5v) and have a sensor that comes back with Analog value, to calculate it correctly I am asked to provide "Logical Voltage" value that is either 3300 or 5000 (3.3v or 5v). Sensor is connected to 3.3V port as there is no 5v port on the board.

What do I choose here 3300 or 5000 for NodeMCU V3?

Thank you.

The subtle clue is in the voltage that is available. That is, the only voltage provided on the board is 3.3v. That's a slight hint that the board might run at 3.3v. And you would be right in that assumption.

The ESP8266 chips, as are most modern MCUs more powerful than 8-bit, 3.3v devices.

So you would choose 3300 as your "Logical Voltage" value.  Or better still, measure the 3.3V and find exactly what it is and use that value x 1000 (for example 3317 or 3295).


How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables? I am using NeoPixel strips, and I want to be able to declare a pointer to them, but not initialize them until the setup function (because they will initialize with certain variables only made available in setup).

For simpler data types, I am just doing:

int totalNumColors = 4; //number of colors user can cycle through`
uint32_t* colorArray = new uint32_t[totalNumColors];
void setup() {
  for (int i=0;i<totalNumColors;i++){
    colorArray[i] = totalColorArray[i];
  }
}

How do I do this for NeoPixel strip intializers? I tried:

Adafruit_NeoPixel* pixels = new Adafruit_Neopixel;`

but I get the error:

expected type-specifier before 'adafruit neopixel'

You can assign the pointer to NULL, and in the setup function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).

#include "Adafruit_NeoPixel.h"

Adafruit_NeoPixel* pixels = NULL;

void setup()
{
  pixels = new Adafruit_NeoPixel();
}


Arduino Leonardo is not recognized by usb cable in Windows 8 My Arduino Leonardo was working properly but for the last two hours when I connect it to a PC via a USB cable, it is reporting something like USB is not recognized and even in device manager it is not showing. However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears. What do I have to do? I tried to restart the PC, changed USB cable but the same issue occurs. I checked the USB by connecting another device - it works fine but the Arduino is not recognised.
I tried other PCs also but the same problem continued. What do I have to do?

It is highly likely that the sketch you loaded is causing this.

  However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears.

For a few seconds after reset the bootloader will configure the board as a USB serial device, awaiting upload of a new sketch. Once that times out it runs the existing code. If the existing code does not configure the USB port (eg. by doing Serial.begin) then it will cease to enumerate as a USB device. This is perfectly normal.

The "fix" is to upload a sketch that uses the USB interface. For example, open a serial port, open the keyboard (Keyboard.begin()) or similar.


SIM800L module just repeating data sent via serial I've got a Teensy 2.0 with simple AltSoftSerial as displayed on image:

As you can see, when I send a command (or any other input via serial) the SIM800L module sends me the same input. I tried to switch the TX and RX wires on the module (in case I misconnected them), but then it returns nothing. When I connect the TX and RX wires directly to each other I've got the exact same result as if they are connected to the module.

The whole thing is connected in this way - computer is connected via USB to teensy, the SIM800L and Teensy are connected via software serial (RX to TX and TX to RX), the SIM800L module is powered from an external battery (it requires specific voltage between 3v4 and 4v4).

Is the module bad, or is it a wrong wiring? Why is the module not communicating and just returning what I sent to it?

EDIT 1:

I'm not particularly looking for mistakes in code, the code is most likely correct. I think the problem is probably somewhere around the SIM800L module.

The module shouldn't just repeat what it got, but it should replay with something like OK, or other answers.

You are asking it to repeat the data you sent. It working AS you wanted it to work in your program.

You asked it to see if there is anything sent and if there was, then print it. That's whats it's doing.


What are the parameters of the browseUrl() callback in the Ethercard library? I'm reading a code that uses Arduino as a webclient and when he tries to catch the info from the site, he uses a callback with the following parameters:

static void response_callback (byte status, word off, word len)

Can anyone explain me how does each one of this parameters work exactly?

PS.: The example I got it from:

#include <EtherCard.h>

#define HTTP_HEADER_OFFSET 0
static byte mymac[] = {0x12,0x34,0x56,0x78,0x90,0xAB};
char website[] PROGMEM = "www.yourwebsite.com";

byte Ethernet::buffer[700];
static uint32_t timer = 0;

static void response_callback (byte status, word off, word len) {
  Serial.print((const char*) Ethernet::buffer + off + HTTP_HEADER_OFFSET);
}

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

  if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
  {
    Serial.println("Failed to access Ethernet controller");
    while(1);
  }
  else
    Serial.println("Ethernet controller initialized");
  Serial.println();

  if (!ether.dhcpSetup())
  {
    Serial.println("Failed to get configuration from DHCP");
    while(1);
  }
  else
    Serial.println("DHCP configuration done");

  if (!ether.dnsLookup(website))
  {
    Serial.println("DNS failed");
    while(1);
  }
  else
    Serial.println("DNS resolution done");

  ether.printIp("SRV IP:\t", ether.hisip);
  Serial.println();
}

void loop() {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl("/", "yourpage.php", website, response_callback);
  }
}

Apparently, the callback is executed on every packet which arrives by the browseUrl call.

"off" and "len" are pointers to the Ethernet buffer holding the data. "Off" are the initial value (offset) and "len" (length) is the amount of data received.

"byte status", I am not sure what it means, but it's very likely will be some kind of error code. It's not being used in any sample I am seeing, so I am really wondering what it means...

Check this link for a fully working sample

Callback here are called browseUrlCallback1 and browseUrlCallback2.

Can't figure out a link with the detailed documentation. If someone has it, please post it.


How can I analyse large packets on an Arduino? I'm trying to send a large packet to an Arduino with an ethernet shield on it. I'm using the built-in RX buffer of the W5100 controller to store the data, but I need more memory (at least 16K of buffer space, the W5100 only has 8K of RX buffer space). I have control over the server side of things as I'm writing the server process myself, so I can take solutions on that side.

Is there some hack I can use in the TCP protocol to have the packet broken up?

Edit: I'm using the SFML 2.1 network API on the server side.

All you need to do is analyse the packet on-the-fly using a state machine.

http://www.gammon.com.au/statemachine

You certainly don't need to hold the entire packet at once, however you do need room for the information the packet contains.

Say, for example, that the packet, although wordy, contains 4 x 32-bit numbers of interest. All you need memory for is those 4 numbers, plus a minor extra amount for the current data you are processing (eg. the current state, and the current number being assembled).

Conceptually it is like streaming a movie to your PC. The PC doesn't need to hold the whole movie, it just needs to hold the current frame, and a few seconds in advance, just to keep things running smoothly.


Accelerometer (I2C) and Fona Shield (software serial) won't work together I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.

My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:

fonaSerial->begin(4800);

fona.begin(*fonaSerial);

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona.
http://pasteboard.co/A16708fo3.png

My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.

My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?

This is quite urgent so a quick responses are greatly appreciated!

My Code:

#include <Adafruit_FONA.h>
#include <Adafruit_Sensor.h>
#include <My2_Adafruit_LSM303_U.h>
#include <Wire.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4

#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

volatile byte accelMagnitude;

Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

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

    accel.begin();

    Serial.begin(115200);

    fonaSerial->begin(4800);
    fona.begin(*fonaSerial);

}

void ReadAccel(){

//Get a new accelerometer sensor event
  sensors_event_t event;
 // Serial.println(F("Accel---------"));
  accel.getEvent(&event);

  accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

}

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

    ReadAccel();

    if (accelMagnitude > 20){

        while (accelMagnitude > 20){

            Serial.println("waiting");
            ReadAccel();
        }

        Serial.println("Over 20");

    }
}

As Gerben suggests, it would not be a good practice to just add a delay and call it a day.

1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and

2) FONA has getNetworkStatus(); make a small control loop and query it until you get status 1 or 5, depending on what network are you on.
From FONA's example:

if (n == 0) Serial.println(F("Not registered"));
if (n == 1) Serial.println(F("Registered (home)"));
if (n == 2) Serial.println(F("Not registered (searching)"));
if (n == 3) Serial.println(F("Denied"));
if (n == 4) Serial.println(F("Unknown"));
if (n == 5) Serial.println(F("Registered roaming"));

And then proceed with the rest of your code. You can make additional checks for signal quality with getRSSI();


Can I use micros() to analyze TX23 anemometer signal? I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...

I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:

void loop() {
  collectData();
}

int collectData(void){
   if (bitLength < 0){
      bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
   }
  // init sequence
  pinMode(dataPin, OUTPUT);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  Serial.print("Send HIGH\n");
  digitalWrite(dataPin, HIGH);
  delay(100);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  delay(500);

  Serial.print("Begin input mode\n");
  pinMode(dataPin, INPUT);

  int state = 0;
  int oldstate = 0;
  unsigned long oldmicros = micros();
  for (int i = 1; i<5250 ; i++) {
    state = (digitalRead(dataPin) == LOW)? 0:1;
    if (i%10 != 0) {
      Serial.print("-");
    } else {
      Serial.print("+");
    }

    delayMicroseconds(10);
    if (state != oldstate) {
      oldstate = state;
      i = 1;
      Serial.print(oldstate);
      Serial.print(" @");
      Serial.print(micros() - oldmicros);
      oldmicros = micros();
      Serial.print("\n");
    }
  }
  Serial.print(state);
  Serial.println(micros()-oldmicros);
}

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

You should really make use of pulseIn() to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.

Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):

while (digitalRead(dataPin) == HIGH); // Wait for TX start
uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.

Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.

// Wait for the middle of the first bit
delayMicroseconds(pulseWidth / 2);

uint32_t highBlock = 0;
uint32_t lowBlock = 0;
for (int i = 0; i < 45; i++) {
    // Shift the high 32-bits left one bit
    highBlock <<= 1;
    // Place in the highest bit of the low block as the lowest
    // bit of the high block
    highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
    // Shift the low 32-bits left one bit
    lowBlock <<= 1;
    // Add in the value of the bit from the data pin
    lowBlock |= digitalRead(dataPin);
    // Wait for the next bit
    delayMicroseconds(pulseWidth);
}

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.

A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.


Arduino: Put Data in Other File The below code starts off with lots of data in the beginning, distracting the reader from the actual code.  What is the best practice to clean this up:

#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
int8_t frame = 0;

void setup() {
  /* Important Setup Routine */
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };

void loop() {
  /* Important Main Loop Routine */
}

One way to clean that up is to create a "Globals.inc" file and cut and paste all of your globals into there.  After that's done, simply include the globals file from your main .ino file with #include "Globals.inc"

(Main.ino)

#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

#include "Globals.inc"

void setup() {
  /* Important Setup Routine */
}

void loop() {
  /* Important Main Loop Routine */
}

(Globals.inc)

Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
// 0-255
uint8_t frame = 0;

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };


How to convert array of chars to array of ints? I have a rather newbie question but I can't figure it out.

Lets say I have this char array:

char array[] = "10,11,12,1,0,1,0";

How can I convert it to an array of int like this?

int arrayINT[] = {10,11,12,1,0,1,0};

If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the strtok() function to split it into individual strings.  Then you can use atoi() to convert those individual strings into integers:

char array[] = "10,11,12,1,0,1,0";
int intArray[7]; // or more if you want some extra room?

int ipos = 0;
// Get the first token from the string
char *tok = strtok(array, ",");
// Keep going until we run out of tokens
while (tok) {
    // Don't overflow your target array
    if (ipos < 7) {
        // Convert to integer and store it
        intArray[ipos++] = atoi(tok);
    }
    // Get the next token from the string - note the use of NULL
    // instead of the string in this case - that tells it to carry
    // on from where it left off.
    tok = strtok(NULL, ",");
}

Note that strtok() is a destructive function. It will decimate your existing string with NULL characters as it slices it up.


Spilt string and convert to float to compare I'm transmitting: Temperature: 28.22C

and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?

TX end hardware: (Arduino Uno board with Xbee S1)  to computer
RX end hardware: (Arduino Uno board with Xbee S2)  to computer

Okk very simple approach :-

Suppose this is your string variable inStr = "Temperature: 28.22C"

String inStr = "Temperature: 28.22C";
int indexOfSpace = inStr.indexOf(' ');
//this stores the address of the space character in the string.
int indexOfC = inStr.indexOf('C');

String Temp = inStr.substring(indexOfScace+1,indexOfC);
//as the parameter for the function is supposed to be the starting point of the string to
 be extracted and one more than its ending point.

//Now to convert to float

float TempFlo = Temp.toFloat();


How to burn the bootloader onto a bare chip without using an Arduino board How do I burn the UNO bootloader onto ATMEGA328P-PU without using an Arduino Uno board. That is burn directly from my PC or Android device??

I've tried nothing, I don't know a thing about microcontrollers ☺

The short answer is, you need a AVR programmer

It is a tutorial on the Arduino website:

https://www.arduino.cc/en/Main/Standalone

And the section Bootloading your chips OPTIONAL will answer the question.


How does Arduino IDE for OSX work without drivers? My Arduino IDE works right out of the box without me having to install any USB to UART drivers. I know the Atmega16U2 on the UNO is acting as UART bridge, but this means that OSX recognizes it on a hardware level, which doesn't make sense since no drivers were installed - unless there is some sort of standard here that the Atmega16U2 implements?

The reason why I ask this is that I have a project where I want to connect an ATMega328p to a client mac which may not have access to 3rd party drivers, so having serial work natively with screen would be ideal. If the Arduino IDE can implement serial monitor without any additional drivers then it means I can too.

Does anyone know how this is implemented?

Thanks!

Windows 8.1 is the last version of any common desktop system that requires CDC/ACM (that is what the Arduino's USB port is) drivers.

OS X is based on BSD which, like Linux, has had CDC/ACM drivers built in since (pretty much) the dawn of time. It is only really Windows that has had the concept of drivers for anything that isn't vendor specific and/or complex (such as video cards, or devices that don't adhere to published standards).

Even Windows 10 now has the drivers for CDC/ACM built in (it's only taken Microsoft 20 years or so to catch up with the rest of the OS world).


Is it possible for ThingSpeak to show a simple table of all data collected? I just recently found the ThingSpeak platform for the IoT. I have been playing around with its features a bit, but I have not found a way for it to show a simple table of all the data collected. For example, the table might have humidity, temperature, and timestamp columns, and then every time data is written to ThingSpeak, a new row would be added with the latest readings. I would be surprised if this is not possible with all of its complex graphing tools. Has anybody found a feature like this?

Since ThingSpeak has an extensive API, you can build a tool to read in data and display it as a table. I have created a GitHub repo called, "IoT Debugger" that allows you to see data as a table as the it comes into a ThingSpeak Channel.

To use the demo, enter your channel number and the read API key.

If you want to modify the project, fork the project on GitHub.


Interface pressure Sensor Hello folks,
              I am using G1/4 Pressure Transmitter Sensor 0-1.2 MPa sensor can you guide for programming part.The conversion from bar to pascal  or bar to Mpa or pascal to psi.Though I am new to it. Plz guide me .

I'm assuming you mean that you want to pull a voltage number off of an input pin and convert it to a meaningful number.

To do this find the range of the incoming voltage.

Find the range of the sensor.

After that you need to split the voltage up to show what parts of the range convert to how much psi.

Here is an example of a temperature gauge that has the same principle.

Temp sensor


Read nested array item from PROGMEM I have a 2D array of uint16_t arrays (IR Remote Codes). Due to the size of this data in RAM I'm having all kinds of trouble when my array is larger than one code. Thus, I have been trying to move this whole structure into PROGMEM. Following various tutorials and this solution, I have come up with the code below for reading a single element out of the array and into a variable that I can feed to the IRLIB2 IRSendRaw function.

The variable that holds the code that is read out of PROGMEM is still huge and causing some problems. Is there a more direct way like a python list comprehension to access an arbitrary element and send it directly to the IRSender?

This PROGMEM_readAnything library looks promising, but I don't have enough C++ fu to make the mental leap to implement it in my code.

#include <IRLibSendBase.h>    //We need the base code
#include <IRLib_HashRaw.h>    //Only use raw sender

#define RAW_DATA_LEN 68
const uint16_t sources[3][RAW_DATA_LEN] PROGMEM =
  {{8550, 4306, 530, 1606, 530, 566, 502, 1610, //power on/off
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000},

  {8546, 4310, 558, 1578, 562, 538, 498, 1638,  //source CD
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000},

  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //source CDR
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000}};

//Create a sender
IRsendRaw mySender;

//Read out one code into a variable and send to the IR transmitter
uint16_t myCode[RAW_DATA_LEN];
for (int i = 0; i < RAW_DATA_LEN; i++) {
   myCode[i] = pgm_read_word_near(sources[0] + i);
}
mySender.send(myCode,RAW_DATA_LEN,36);

The library, as it stands, doesn't support direct sending from PROGMEM.  However it's not too hard to get around that - if your C++ is up to it.

The IRsendRaw class is a child class that extends the IRsendBase with a single function.  You just need to do the same thing to create a new class that implements the functions in a way that can read from PROGMEM.

This is the original:

class IRsendRaw: public virtual IRsendBase {
  public:
    void send(uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(buf[i]);
        }
        else {
          mark(buf[i]);
        }
      }
      space(0); // Just to be sure
    }
};

You just need to make your own one of those in your sketch, called something different, and which uses the progmem functions instead of accessing buf[i]:

class IRsendRawPGM: public virtual IRsendBase {
  public:
    void send(const uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(pgm_read_word_near(buf + i));
        }
        else {
          mark(pgm_read_word_near(buf + i));
        }
      }
      space(0); // Just to be sure
    }
};

Now you can define your sender object as:

IRsendRawPGM mySender;

And send the data directly:

mySender.send(sources[0], RAW_DATA_LEN, 36);

(Note: this code is untested).


How to Create a reference to an External Print object Right now I have an object:

class Dog
{
  public:
    Dog(uint8_t I2c, Stream& feedback);
    void Speak();
  private:
    uint8_t _I2c;
    Stream& _output;
};

Dog::Dog(uint8_t I2c, Stream& feedback):_output(feedback),_I2c(I2c){}

Dog::Speak(){
_output.println("Hi There.");
}

That is currently constructed in my sketch via:

Dog Dug([I2cPort], Serial);

How can I modify my class so that to be compatible with taking either a Serial object or an LCD display (using Adafruit's RGB LCD library )?

Eg:

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
Dog Dug([I2cPort], Serial);
Dog Sam([I2cPort], lcd);

Additional info:

The LCD in question is mostly used as a UI display in its own library this library refreshes the display every 1.5 sec. As information from speak(); and the UI have similar priority, it is acceptable if one instantly overwrites the other.

I am open to solutions that involve modifying the construction of Dog the only requirement is that I need to be able to indicate print("[something]"); in the Dog.cpp

I'm interested in asking this question on the Arduino SE as I believe there are differences in how you would approach this if the problem was on a traditional computer.

If your class is only writing to the stream you probably want to have your class take a Print object instead of a Stream object.

The Adafruit library inherits from Print.


Why won't my hall counter count? I want to use a hall effect sensor with a timer (millis). The count should reset after 1 second and print out the given count.

const int Hallsensor=3;
int HallValue;
int LastHallValue;
int Hcount =0;
unsigned long timer = 0;
unsigned long start_time = 0;

void setup() {
  pinMode(Hallsensor, INPUT);
  Serial.begin(9600);
  counting = true;
  start_time = millis();
}

void loop() {
  LastHallValue = HallValue;
  timer = millis();
  if((timer - start_time) >= 1000) {
    HallValue = digitalRead(Hallsensor);
    if (HallValue == LOW and LastHallValue == HIGH) {
      Hcount++;
      Serial.println(Hcount);
    } else {
      if(counting == true) {
        Serial.print("Count is");
        Serial.println(Hcount);
        counting = false;
      }
    }
  }
}

const int Hallsensor=3;
int HallValue;
int LastHallValue;
int Hcount =0;

unsigned long timer = 0;
unsigned long lastChangeTime = 0;

void setup()
{

  pinMode(Hallsensor, INPUT);
  Serial.begin(9600);
   counting = true;
    start_time = millis();

}

void loop()
{

    LastHallValue = HallValue;
    HallValue = digitalRead(Hallsensor);
    if (HallValue == LOW and LastHallValue == HIGH){
        Hcount++;
        lastChangeTime = millis();
        Serial.println(Hcount);
    }
    else{
        if(counting == true){
            Serial.print("Count is");
            Serial.println(Hcount);
            counting = false;
            // Serial.println(LastHallValue);
        }
    }

    if( (Hcount>0) && (millis() - lastChangeTime) >= 1000){
        Hcount = 0;// reset count when it hasn't increased in the last second.
    }

}


How to converte EPOCH time into time and date on Arduino? I have a question on how to convert EPOCH timestamps, which I receive as char*, into DD.MM.YYYY and HH:MM:SS format seperately?

Here are more information to my Arduino project: The Arduino is receiving through an ESP8266 module three different EPOCH timestamps from the OpenWeatherMap API for sunrise,sunset and the current date. I want these 3 informations to be displayed on an 1,3" OLED display, the date in DD.MM.YYYY and the other two timestamps in HH:MM format.

I was looking in several time libraries like TimeLib and RTC for a solution, but I wasn't able to find one.

That's my code fragment on receiving the timestamps:

DynamicJsonBuffer jsonBuffer(4096);
JsonObject& root = jsonBuffer.parseObject(client);

const char* date = root["dt"];
const char* sunrise = root["sys"]["sunrise"];
const char* sunset = root["sys"]["sunset"];

How to convert those timestamps?

Epoch are seconds from 1970-01-01. Get it from JSON as unsigned long. They are a number in the returned JSON (no ")

from https://openweathermap.org/ doc:

"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},

to convert it to string with TimeLib.h:

#include <TimeLib.h>
#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);

  const char* json = "{\"country\":\"JP\",\"sunrise\":1369769524,\"sunset\":1369821049}";

  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(json);

  unsigned long t = root["sunrise"];

  char buff[32];
  sprintf(buff, "%02d.%02d.%02d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t));

  Serial.println(buff);
}

void loop() {
}


Is there any way to use the serial port as an interruption source? I have and sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.

By checking out the reference on attachInterrupt(), I found only the ways to declare interrupt pins, but nothing related to serial. What you can say about it?

Thanks in advance.

Use millis() for the timing of the temperature reading, then you can read from the serial in between time and won't need to use any interrupts.

unsigned long last_measure = 0;

const byte buffer_size = 16;
char buffer[buffer_size] = "";
byte buffer_i = 0;

// setup() and other stuff

void loop() {
    if (millis() - last_measure > 10000) { // read the temperature like in the "blink without delay" example
        last_measure = millis();
        int value = readSensor();
        Serial.println(value);
    }
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') { // end of line, which means we got the whole string
            if (strcmp(buffer, "magic") == 0) { // compare if it matches the magic word
                int value = readSensor(); // read and print the temperature
                Serial.println(value);
            }
            buffer_i = 0; // reset the index
            buffer[buffer_i] = 0;
        }
        else if (buffer_i < buffer_size-1) { // if the buffer is not full
            buffer[buffer_i++] = c; // add char to buffer
            buffer[buffer_i] = 0; // and null terminate the string
        }
    }
}


How to connnect Arduino to Wemos D1 (send data)? I made a project with an Arduino Uno, a 16x2 LCD display and a DS18B20 temperature sensor. It shows the temperature in the display:

I want to connect it to Internet so I got a Wemos D1 Mini. It works great: it send data through my router.

But I need to connect my project with the Wemos D1 Mini:

I think that I just need to send the data (temperatures grades) from my project to Wemos so then Wemos resolve it.

How can I do it?

A) Throw out the Arduino, and just connect your display and sensor to the WeMos directly.
B) Connect the Arduino to the WeMos using UART, SPI or I²C and send the temperature value to the WeMos. Keep in mind that the Arduino UNO is a 5V device, and the maximum voltage for the ESP8266 is 3.3V, so you'll need a level shifter.
You can send the temperature as a binary value (beware of framing errors), but the easiest way is to use a text-based protocol. Since you just have to send a single value, you can just use a single delimiter (e.g. new line). That makes it very easy to parse.


RF 433 Module with VirtualWire: transmit and receive using the same Arduino board I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?

Here is the schematics I tried:

1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module

2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

Here is the source code I wrote:

#include <VirtualWire.h>

#define BTN_PIN A0    // pushbutton que aciona a transmissao
#define LED_PIN 13    // LED aceso ao receber o sinal
#define TX_PIN   4    // ligado ao pino DATA do transmissor RF
#define RX_PIN   7    // ligado ao pino DATA do receptor RF

#define SPEED  5000   // velocidade de comunicacao (bits por segundo)

int estado = 0;

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  vw_set_tx_pin(TX_PIN);  // transmissor
  vw_set_rx_pin(RX_PIN);  // receptor
  vw_setup(SPEED);
  vw_rx_start();

  Serial.begin(9600);
}

void loop() {
  int pressionado = !digitalRead(BTN_PIN);
  char msg[4];

  if (pressionado) {
    estado = !estado;
    itoa(estado, msg, 10);

    vw_send((uint8_t *) msg, strlen(msg));
    vw_wait_tx();

    Serial.print("Mensagem enviada: [");
    Serial.print(msg);
    Serial.println("]");

    delay(500);
  }

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  int recebido = 0;

  memset(msg, 0, 4);
  if (vw_get_message(buf, &buflen)) {

    for (int i = 0; i < buflen; i++)
      msg[i] = char(buf[i]);
    msg[buflen] = '\0';

    Serial.print("Mensagem recebida: [");
    Serial.print(msg);
    Serial.println("]");

    recebido = atoi(msg);

    Serial.print("recebido = ");
    Serial.println(recebido);

    digitalWrite(LED_PIN, recebido);
  }
}

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.

Does anyone have an idea of what could be wrong?

These lines in the ISR in VirtualWire.cpp

    if (vw_rx_enabled && !vw_tx_enabled)
        vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;

and

    if (vw_rx_enabled && !vw_tx_enabled)
        vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.

It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.

You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.


Is it possible for ESP8266WiFi client to request the number of clients currently connected to Access Point? My system consists of several ESP8266 based 'stations', which are synchronised in a way that all of them go into deep sleep and wake up on the same schedule. All stations are WiFi clients. All stations run on batteries and energy saving is critical.

One of the stations is a Master. It contains a modem/router that serves as AP to all stations.   The AP is switched OFF during the sleep phase. When a Master wakes up it switches on the AP and thus starts a communication session available to all stations. When all stations have their data sessions completed and disconnect from AP, the Master switches off the modem/router and goes to sleep.

My question is about the Master being informed that there are no other clients actively connected to the AP. My current solution is WAN based - each station reports to the Web Service on the start and end of their connection. Is it possible to achieve the same result locally - by a request from the WiFi client to the Access Point?

Use WiFi.softAPgetStationNum() to return the number of clients connected to an ESP8266 AP.


How to transmit more than 1 byte continually? In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8.

I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!

Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.

EDIT: Let me show you my data.
So, I'm constantly transmitting the values; 123,124,125,126.

1111011
1111100
1111101
1111110

The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.

11110101
11111001
11101101
11110001

It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit.

As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit.

Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!

I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.

With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be some difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.

Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.

You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.

So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

  However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced?  I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.

Really, to ensure syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.

Imagine you have an incoming stream of bits on the receiver:

011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: 111111111) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.

In other words, with 8-bit bytes, data will always be 0xxxxxxxx1 and thus a gap of 1111111111 must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).


SIM808 module GSM working fine, GPS not working (No GPS ready message on power on) I powered on my SIM808 module. It showed me following output:

RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

It supposed to show GPS ready also.

I sent AT command and return ok.
However AT+CGPSPWR=? returns error. All GPS command showed error.

I think GPS is not initialized at all as i didn't see GPS message when module powered on.

Why is the GPS not working?

You have a version2 module. Use AT+CGNSxxx instead of AT+CGPSxxx


How can I have the user instantiate an object? So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.

A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.

The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()

I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...

Is there a way I could only instantiate the selected program and still call its playNext() method easily?

Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.

Max

You seem like you are almost there. Allocate the objects using new and free with delete.

// Abstract parent
class Playlist {
    public:
    virtual void playNext() = 0;
    // etc.
};
// Derived classes
class Something : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
class SomethingElse : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
// More derived classes......

// A pointer of the current program
Playlist *play_list = nullptr;

// A factory function to create a Playlist while also freeing previous
Playlist * create_playlist(int which_program) {
    // Important - delete old
    delete play_list;
    play_list = nullptr;
    // There are only 16 types, use a switch or if
    switch (which_program) {
        case 1:
            // Create a new one and save in global ptr
            play_list = new Something;
            break;
        case 2:
            play_list = new SomethingElse;
            break;
        // More cases here.....
    }
    return play_list;
}

[edit]--------------------------

Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in setup. But I think it's close to what you want:

class Playlist;  //Forward declaration

// Each class will have a function to create itself
typedef Playlist * (*CreateFunc)();

// The parent class. It also holds a list of all child classes
// Could probably refactor into 2 separate classes
class Playlist{
  public:
  // Need virtual dtor
  virtual ~Playlist() {
    delete last_created;
  }

  // Put all the overridable function declarations here
  virtual void playNext() = 0;

  // This has to be called for each child. (See macro below)
  static void register_class(int id, CreateFunc f) {
    all_maps[num_maps].id = id;
    all_maps[num_maps++].f = f;
  }

  // Factory method to instantiate an object
  static Playlist * create_playlist(int id) {
      // Delete old pointer
      if (nullptr != last_created) {
          delete last_created;
          last_created = nullptr;
      }
      for (int i = 0; i < num_maps; i++) {
          // Search the list for name match
          if (id == all_maps[i].id) {
              // Call the creation func
              return all_maps[i].f();
          }
      }
      return nullptr;
  }
  protected:
  // A struct to hold the class name and a pointer to the creation function
  struct Map {
    int id;
    CreateFunc f;
  };
  static Map all_maps[32];
  static int num_maps;
  static Playlist* last_created;
};
// Static declarations
Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
int Playlist::num_maps = 0;
Playlist* Playlist::last_created = nullptr;

// Example child class
class Child1 : public Playlist{
  public:
  void playNext() {Serial.println("Child1");}

  // Must have this function and it must be static
  static Playlist * create() {return new Child1;}
};
// Another example
class Child2 : public Playlist{
  public:
  void playNext() {Serial.println("Child2");}
  static Playlist * create() {return new Child2;}
};

// Helper macro to simplify registering
#define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

  // This must be done for all classes
  REGISTER_PLAYLIST(0, Child1);
  REGISTER_PLAYLIST(1, Child2);

  // Example usage
  Playlist*p = Playlist::create_playlist(0);
  p->playNext();
  p = Playlist::create_playlist(1);
  p->playNext();
}

void loop() {

}

I just whipped this up. Probably room for improvement....


How will I solve my problem : expected primary-expression before '>' token // defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
// defines variables
long duration;
int distance;

#include <moving.h>
#include <Servo.h>

Servo servo;

moving car(6, 2, 3, 5, 4, 7, 11, 8, 9, 10, 12, 13); // setting up a new RC car with pins EN1, IN1, IN2, EN2, IN3, IN4, EN3, IN5, IN6, EN4, IN7, IN8

void setup() {
{
  for (int i=2; i<14; i++)
  {
    pinMode(i, OUTPUT);
  }
  servo.attach(10);
  servo.write(90);
}
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
}

void loop() {
  if (distance) > 10; // this is the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
  if (distance) < 10; // and this
  car.set_speed(0);
  car.forward();
  delay(600);
  car.set_speed(127);
  car.right();
  delay(700);
  car.set_speed(127);
  car.forward();
  delay(700);
}

You need curly brackets around your if block.

if (distance > 10) { // this solves the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
}

etc
Edit: Thanks to the commenter.


Two or More Arduinos Handshaking research would show that there are numerous ways for two arduinos to talk to one another. But i was looking for a 'basic robust protocol' (..it doesn't sound basic ....I know!), to allow for two arduinos to talk to one another. The idea is , Arduino One(slave), is linked to a sensor and it reads data from the sensor and sends the data  to Arduino Two on 'request' of the data by Arduino Two(master). Arduino Two would have to 'request' for the data from Arduino One, before it can read the data, if its available. A popular method on most sites (e.g https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/shaking-hands-part-1) is the use of the method below. I added a comment in search of clarity.

              void establishContact()
                     {  //This while loop does baffle me as it suggests that
                        //while there is nothing in serial, send A???
                        while (Serial.available() <= 0)
                       {
                         Serial.println("A");   // send a capital A
                         delay(300);
                       }
                     }

Now this method was used in handshaking between Arduino and processing. This method was called on the Arduino sketch. On the processing sketch, a method there just checks to see if 'A' was received. If it is, it reads in the data from serial, clears the serial buffer and  writes 'A' back to Serial. I tried using this method on both of my arduinos as i felt it was 'basic' enough, but it didn't work at all. Does anyone has a better idea on how my arduinos could handshake?.

That while loop makes perfect sense.  It' basically nudging the other end repeatedly until it replies with something - anything.

It's like sitting next to someone and poking them in the ribs every 300ms until they respond to you. Once they have responded you can then react to that response - be that to run very fast or tell them your important news.

The idea of handshaking like that is all to do with synchronisation. It ensures that both ends are ready for communication at the same time.  Once synchronised you know, to a high probability, that what you are sending will be interpreted properly, and any replies you get back will be correct.

For basic communication between two Arduinos it's really not necessary.

The simplest call-and-response protocol involves Arduino A sending a single byte as a request and Arduino B replying with a single byte. It is up to you what those bytes represent, but ASCII letters for requests are ideal since they are understandable by a human, and numbers between 0 and 255 or -128 and +127 fit in to one byte (unsigned or signed respectively). Should you want bigger numbers being sent back then the reply will have to be delimited in some way. The simplest way of doing that is to format the response as ASCII data and send it with a CR and/or LF.

Something like:

if (Serial.available()) {
    char command = Serial.read();
    switch (command) {
        case 'T':
            Serial.println(temperature);
            break;
        case 'P':
            Serial.println(pressure);
            break;
    }
}

The master end then sends either 'T' or 'P' to request temperature or pressure. It then reads characters up to a line feed and stores them in a string which it can then convert into the desired numeric data type depending on what temperature and pressure are (integer or floating point).


Newbie needing help with debounce errors in arduino So I found a code I would like to use and not sure how to edit the code properly.

#include <Debounce.h>

void matrix(char matrix[7]) {
  int map[10];
  map[0] = 2;
  map[1] = 3;
  map[2] = 4;
  map[3] = 5;
  map[4] = 6;
  map[5] = 7;
  map[6] = 8;
  map[7] = 9;

  int i=0;
  for(i=0;i<=7; i++) {
   if(matrix[i] == 0x30) { // 0x31=1, 0x30=0
      Serial.println(map[i]);
      digitalWrite(map[i],LOW);
   }
   else digitalWrite(map[i],HIGH);
  }
}

void show(int number) {
  switch(number) {
    case 0:
      matrix("11111100");
      break;
    case 1:
      matrix("01100000");
      break;
    case 2:
      matrix("11011010");
      break;
    case 3:
      matrix("11110010");
      break;
    case 4:
      matrix("01100110");
      break;
    case 5:
      matrix("10110110");
      break;
    case 6:
      matrix("10111110");
      break;
    case 7:
      matrix("11100000");
      break;
    case 8:
      matrix("11111110");
      break;
    case 9:
      matrix("11110110");
      break;
    default:
      matrix("00000010");
      break;
  }
}

#define t1 13
#define t2 12

Debounce debouncert1 = Debounce( 20 , t1 );
Debounce debouncert2 = Debounce( 20 , t2 );

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

  // initialize the digital pin as an output:
  pinMode(13, INPUT);
  pinMode(12, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

int setCountPlus(int count){
  if(count == 9){
    count = 1;
  }
  else{
    count++;
    count %= 10;
  }
  return count;
}

int setCountMinus(int count){
  if(count==1){
    count = 9;
  }
  else{
  count--;
  count %= 10;
  }
  return count;
}

void loop()
{
  int i=-1;
  show(i);
  while(1){
    debouncert1.update();
    debouncert2.update();
    if(debouncert1.read()){
      i=setCountPlus(i);
    }
    if(debouncert2.read()){
      i=setCountMinus(i);
    }
    if(i==10){
      i=1;
    }
    show(i);
    delay(250);
  }
}

as for the errors.

sketch 65: error: 'Debounce' does not name a type
sketch 66: error: 'Debounce' does not name a type
sketch .ino: In function 'void loop()':
sketch 108: error: 'debouncert1' was not declared in this scope
sketch 109: error: 'debouncert2' was not declared in this scope

Any help would be great on fixing the code to stop getting errors.

In the description of Debounce, you'll find the hint that this library is outdated and no longer maintained.

Its successors, Bounce1 and, more recently, Bounce2 are available from a github repository by Thomas Fredericks, Bounce-Arduino-Wiring.

Instead of simply downloading and unzipping the archive to ${HOME}/sketchbook/libraries, you might want to consider that this is the right moment to get familiar with git repositories as an easily updatable source for third-party libraries.

Supposed that you're on a GNU/Linux system with git installed, you would

cd /${HOME}/sketchbook/libraries
git clone https://github.com/thomasfredericks/Bounce-Arduino-Wiring.git

to obtain a clone of the necessary data.

If the name of the directory of the library contains dashes (-), you'll have to change this name: remove the dashes or replace them with underscores (_). Names with dashes aren't valid!

Once in a while, you would change to the directory of the respective library and simply run git pull to update your local copy to the latest version of the repository.


Not able to find right library for MPU9250 I am using an Arduino Uno and learning to use the motion sensor. Currently I was not able to find the library which looks simple and would like to get your suggestion. I found this https://github.com/hideakitai/MPU9250 library to be simple but don't know how to use it.

For example, take this code:-

#include "MPU9250.h"

MPU9250 mpu;

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

    Wire.begin();

    delay(2000);
    mpu.setup();
}

void loop()
{
    static uint32_t prev_ms = millis();
    if ((millis() - prev_ms) > 16)
    {
        mpu.update();
        mpu.print();

        Serial.print("roll  (x-forward (north)) : ");
        Serial.println(mpu.getRoll());
        Serial.print("pitch (y-right (east))    : ");
        Serial.println(mpu.getPitch());
        Serial.print("yaw   (z-down (down))     : ");
        Serial.println(mpu.getYaw());

        prev_ms = millis();
    }
}

Some values are not defined here, like registration code and input pins. I am not used to reading the documentation code so might need help in that.

In the Arduino IDE, click on SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES.

Then, search for 9250, select the SparkFun one, and click INSTALL.

Finally, from the examples, choose the MPU9250BasicAHRS_I2C.


Detecting the down time of a system by subtracting the time when the sytem gives ON signal and when it goes OFF int pin_state = LOW;
struct Channel {
    byte pin;
    byte state;
    byte count;
    unsigned long fell, rose;  // times of fall and rise
};

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

void setup()
{
    for (int i = 2; i <= CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    //Serial.println("pin,fell,rose,low time");
    Serial.println("Minutes, Seconds, Count");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i)
    {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == LOW && new_state == HIGH)   // input rose
        {
            c.rose = millis();
            c.count = c.count + 1;
        }
        else if (c.state == HIGH && new_state == LOW)  // input fell
        {
            c.fell = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

void display_channel(const Channel &c)
{
  int minutes, seconds;
  unsigned long difference;
  difference = c.fell - c.rose;
  seconds = int(difference/1000);
  if (seconds >= 60)
  {
       minutes = seconds / 60;
       seconds = seconds % 60;
  }
    //Serial.print(difference/1000);
    //Serial.print(",");
    Serial.print(minutes);
    Serial.print(",");
    Serial.print(seconds/1000);
    Serial.print(",");
    Serial.println(c.count-1);
    //Serial.print(",");
  }

In this code, I tried to measure the time taken between the two events (when the ON signal comes and when the signal goes OFF) in two different channels simultaneously. But the code doesn't give any output and the serial monitor is empty except for the statement in the main function.

It would be useful if anyone could find where exact;y the problem is and a valid solution to it would be helpful.

edit : I made the following changes but still output is never displayed. Any error is still ON the program?

You have the same state being tested twice:

if (c.state == LOW && new_state == HIGH)   // input rose

and:

else if (c.state == LOW && new_state == HIGH)  // input fell

If "A", else if "A". It makes no sense. I think you wanted the second one to be the opposite:

else if (c.state == HIGH && new_state == LOW)  // input fell

Also, this calculation in display_channel doesn't work:

if (seconds >= 60)
{
  seconds = seconds % 60;
  minutes = minutes + 1;
}

For example, if seconds is 378, then seconds ends up as 18, and minutes as some undefined number plus 1.

That whole block should be replaced with:

minutes = seconds / 60;
seconds = seconds % 60;

In your code:

minutes starts off undefined
You add only 1 to minutes regardless of how many minutes have passed.


Arduino Uno keeps looping on setup() everytime I press a specific button on the remote I'm trying to decode my Panasonic television remote using the IR_RECEIVE sketch below.

When I press the remote's buttons it works fine and Iget the values, except from when I press the power button - the setup() function executes.

This is the code:

/* Raw IR decoder sketch!

This sketch/program uses the Arduno and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected

Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

#define IRpin_PIN      PIND
#define IRpin          2
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
    Serial.begin(9600);
    Serial.println("Ready to decode IR!");
}

void loop(void) {
    uint16_t highpulse, lowpulse;  // temporary storage timing
    highpulse = lowpulse = 0; // start out with no pulse length

    while (IRpin_PIN & (1 << IRpin)) {
        highpulse++;
        delayMicroseconds(RESOLUTION);

        if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][0] = highpulse;

    while (!(IRpin_PIN & _BV(IRpin))) {
        lowpulse++;
        delayMicroseconds(RESOLUTION);
        if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][1] = lowpulse;

    currentpulse++;
}

void printpulses(void) {
    Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
    for (uint8_t i = 0; i < currentpulse; i++) {
        Serial.print("delayMicroseconds(");
        Serial.print(pulses[i][0] * RESOLUTION, DEC);
        Serial.println(");");

        Serial.print("pulseIR(");
        Serial.print(pulses[i][1] * RESOLUTION, DEC);
        Serial.println(");");
    }
}

This is the output:

  Ready to decode IR!

  Received:

  OFF   ON
  delayMicroseconds(34724);
  pulseIR(3600);
  delayMicroseconds(1800);
  ......
  delayMicroseconds(1340);
  pulseIR(460);
  delayMicroseconds(1360);
  pulseIR(460);
  Ready to decode IR!
  Ready to decode IR!

The last 2 rows appeared when I pressed the power button (twice).
The rows above appears when I press any other button.

I played around with the Arduino and the remote, I might have done something to cause this. The first time I tried it - it worked fine.

I tried resetting and re-uploading.

Sorry if the post is too long or not informative enough - I'm new to this and not really sure what kind of information to provide.

How high can currentpulse get before it is reset to zero? It is used an array index and if it gets larger than the (number of array elements-1), your code will write outside of the array.

Can the array be so far over-written that it grows into the stack area? That could definitely cause a reset, or reset-like behavior.


Understanding the relationship of Pulse and Stepper RPM This may be a better question for the Physics StackExchange so tell me if I should move the question.

I have a pretty simple script that I'm using to control the RPM of my stepper motor:

void loop(){
  digitalWrite(PIN, HIGH);
  delayMicroseconds(wait);
  digitalWrite(PIN, LOW);
}

as you can see it's just producing a pretty standard pulse, I have my Arduino connected to a driver that manages the motor. The wait variable comes from a second order equation I derived from measuring the RPM with a Tachometer and tweaking the value.

// From data RPM = 31729/x + 17.327 thus x = 31729/(RPM-17.527)
wait = M/(RPM-C);

It works pretty well, I get readings consistently within only 1 - 2 rotations off. But the slope and intercept seem completely arbitrary to me. Is there a chance it has to do with the clock speed of the Arduino? I'm using an Uno and from playing around with the numbers I can't seem to find a relationship. From what I can tell, the driver looks hardwired so I don't think it has much to do with the equation.

Any idea what these values, the slope/intercept mean?

Equation: RPM=31729/wait + 17.327 M:31729 and C:17.327

The real answer to this question requires understanding exactly what hardware you have. The formula, assuming one step per pulse, is that the delay should be:

wait = (MicroSecondsPerMinute)(1/RPM)(1/PulsesPerRevolution) - overhead

where overhead is the extra time it takes to run digitalWrite twice and loop. It is small, but if it were zero your code would not work because the amount of time your signal is LOW would be zero as well.

Your numbers suggest Pulses Per Revolution is around 1891. This will be the product of how many steps per revolution the motor is wired for and how many bits of microstepping the driver is doing. A 225 step motor with 3 bit microstepping (8 fractional steps per "true" step) would have PPR of 1800 for example. Your number does not precisely match any common setups, but is exactly in the range expected, with 1600 and 2000 being normal for small steppers.

Because of the "overhead" term, RPM as a function of wait should not be linear. Your constant value should be a function of RPM; in fact, when RPM gets much larger than the number of Microseconds per minute it should converge to being equal to RPM. In this case your RPM is so low that approximating it to 17 is probably valid and all error too small to notice. It could be causing some of the oddness of your PPR value though.


How to use a Pololu 5v AVR ISP Programmer to program an AVR at 3.3v I have a Pololu 5v AVR ISP which I have successfully used to program several Arduinos (a Mega, an Uno and a Pro Mini 5v). I now have a new Arduino compatible clone which is basically a clone of the pro mini 3.3V.

I am wondering if anyone else has used this programmer to program a 3.3V board without issues. I've seen a forum post on pololu's forum which discusses modifications required - but I don't really understand what is necessary.

I've also found the software tool mentioned in the above forum post here and I have downloaded it and built it.

When I run the aforementioned tool I get these options:

PgmCmd: Configuration and status utility for the Pololu USB AVR Programmer.
Version: 1.0.1.0
Options:
 -l, --list             list available devices
 -d, --device SERIALNUM (optional) select device with given serial number
 -s, --status           display complete device status
     --freq NUM         sets the ISP frequency (in units of kHz)
     --linea ID
       or --lineb ID    set serial control signal associated with line A or B.
                        Valid IDs are: none, cd, dsr, ri, dtr, rts.
                        Warning: dtr and rts are outputs: -f option is required
     --swminor HEXNUM   AVR ISP software version minor (in hex, e.g. A)
     --swmajor HEXNUM   AVR ISP software version major (in hex)
     --hw HEXNUM        AVR ISP software hardware version (in hex)
     --vddmin NUM       set minimum allowed target vdd (units of mV)
     --vddmaxrange NUM  set maximum allowed target vdd range (units of mV)
     --restoredefaults  restore factory settings
     --bootloader       put device in to bootloader (firmware upgrade) mode

I then ran the --status option with the serial number of my programmer and got this:

Serial number:                  00048632
Firmware version:               1.07
Settings:
  ISP Frequency:                200 kHz
  Line A Identity:              None
  Line B Identity:              None
  AVR ISP hardware version:     F
  AVR ISP software version:     2.A
  Target VDD allowed minimum:   4384 mV
  Target VDD allowed max range: 512 mV
Last programming:
  Error: None
  Measured Target VDD Minimum:  N/A
  Measured Target VDD Range:    N/A
SLO-scope:
  State:                        Off
  Line A output:                Off
  Line B output:                Off

From this I deduced that my programmer is currently set at between about 4.38V and 4.89V which I presume corresponds to the 5V approximate voltage of the normal Arduino chips.

Given that the utility program allows me to set both the target minimum Vdd and the target Vdd max range should I therefore set it to something like a minimum of 2704 with a max range of 512 which should put the signal voltages at up to ~3.2V.

Is that all I have to do to get this to work?

Since AVR ISP is simply a modified form of SPI, the most universal way to handle this is to use a 3/1 level translator such as the MAX3392E. Once you provide it with 5V on VCC and 3V3 on VL it will translate the MOSI, SCK, and nRESET signals to 3V3 and the MISO signal to 5V.


How to assign an interrupt to a button press with an ATtiny? (interrupt not fired with my code) (Here is finally a solution).

I'm using the following code on a ATtiny45 to assign an interrupt to a button press (pin #7, PB2, INT0). However the LED doesn't blink when the button is pressed, as if the interrupt is not working. Why?

Note: I'd like to use the least power when no interrupt happens, to have a current in the order of magnitude of ~ 1 µA, to run from batteries for years.

#include <avr/sleep.h>

void setup()
{
  pinMode(4, OUTPUT);  // LED
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);      // pin #7 = PB2
  digitalWrite(4, HIGH); delay(100); digitalWrite(4, LOW);  // LED blink, working here
}

void wake()
{
  sleep_disable();
  detachInterrupt(0);
  digitalWrite(4, HIGH);  // LED not working here when pressing the button
}

void loop()
{
  sleep_enable();
  ADCSRA = 0;
  attachInterrupt(0, wake, CHANGE);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}

Note:

I'm using Arduino IDE with damellis' attiny, I also tried with Spence Konde's ATtinyCore but it's the same
In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually I'd like to have interrupts for all these three pins.
I've read https://gammon.com.au/forum/?id=11497 but using noInterrupts() / interrupts() did not change anything in my case.
I've tried "Sketch J" from https://gammon.com.au/forum/?id=11497 but EIFR = bit (INTF0); gives an error: 'EIFR' was not declared in this scope (I'm compiling from Arduino IDE); probably this works on an ATmega but not ATtiny.

Edit: Here is a working code of deep sleep, with an interrupt when the pin #5 (PB0) changes...

#include <avr/interrupt.h>
#include <avr/sleep.h>

ISR(PCINT0_vect) {
  if (digitalRead(0) == LOW)
    digitalWrite(4, HIGH);
  else
    digitalWrite(4, LOW);
}

void setup() {
  pinMode(4,OUTPUT); // LED
  pinMode(0,INPUT_PULLUP);
  pinMode(1,INPUT_PULLUP);
  pinMode(2,INPUT_PULLUP);
  ADCSRA = 0; // ADC disabled
  GIMSK = 0b00100000;  // General Interrupt Mask Register, / Bit 5 – PCIE: Pin Change Interrupt Enable / When the PCIE bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt is enabled. Any change on any enabled PCINT[5:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt Vector. PCINT[5:0] pins are enabled individually by the PCMSK0 Register. / see https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
  PCMSK = 0b00000111;  // Pin-change interrupt for PB0, PB1, PB2
}

void loop() {
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}

...but for an unknown reason, if I add this code:

ISR(PCINT1_vect) {
  if (digitalRead(1) == LOW)
    digitalWrite(4, HIGH);
  else
    digitalWrite(4, LOW);
}

the pin-change interrupt for PB0 still works (PCINT0), but not the interrupt for PB1 (PCINT1). Why?

Look at the datasheet of the ATtiny45. In the section “Sleep Modes”,
there is a table that lists the wake-up sources available for each sleep
mode. For the mode “power-down”, INT0 is listed as a possible wake-up
source, but there is a small footnote:

  For INT0, only level interrupt.

This means that the CHANGE mode you are trying to use will not wake-up
the MCU out of power-down. You have to instead

attachInterrupt(0, wake, LOW);

  In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually
  I'd like to have interrupts for all these three pins.

You may then have to look into the “pin-change” interrupt. This is
something different from the INT0 you are using here, and is not
generally supported by the Arduino core. You will have to either get
some pin-change-interrupt library, or work with no library using the
information from the datasheet (not that hard). Pin-change interrupt is
also a wake-up source for power-down.

Edit: Answering extra questions from comments.

  How did you know that "only level interrupt" means only "LOW"?

The Arduino documentation states that the mode
parameter of attachInterrupt() can be either LOW, CHANGE, RISING
or FALLING. A few boards also support HIGH, but the ATtinies are not
among them. A “level” can be either LOW or HIGH, whereas CHANGE,
RISING and FALLING are “edges”.

This is corroborated by the ATtiny45 datasheet: “The INT0
interrupts can be triggered by a falling or rising edge or a low level.”

  Is pin-change interrupt PCINT?

Yes.

  why do you think it isn't supported by the Arduino core?

The attachInterrupt() API only really makes sense for INT0, INT1,
etc... not for PCINT. You can also look at the source code.

  Isn't it standard to interrupt when a pin changes states?

If you wish, you can configure INT0 to interrupt on a rising edge, a
falling edge, or any logical change. But this uses an edge-detection
logic which relies on the main clock, and thus does not work in
power-down mode.

For more details on INT0 vs. PCINT, their differences, and how to use
them, please refer to the datasheet, specifically to the “External
Interrupts” section I linked to above.

Addendum: Extra question:

  why it doesn't work [with ISR(PCINT1_vect) {...}]?

Gcc tells me “warning: ‘PCINT1_vect’ appears to be a misspelled
signal handler”. And indeed, there is no such interrupt vector on the
ATtiny45: there is only PCINT0_vect, and this interrupt is shared by
all the pins that can generate a pin change interrupt. If you want to
know which pin triggered the interrupt, you will have to figure that out
within the interrupt handler itself.

This is the single point that makes the PCINTs trickier to work with
than INT0 and co.: each PCINT interrupt is shared by a group of pins. On
the ATtiny45, there is only one such group, and PCINT0_vect is the
only interrupt handler. Larger AVRs have more groups (3 on the
Uno/ATmega328P), and PCINT1_vect makes sense on them.

Also beware of the somewhat confusing naming scheme. Avr-libc defines
some macros PCINTn, where n is a number. These macros expand to bit
numbers, and are meant to be used in code like this:

PCMSK = _BV(PCINT0)   // sense changes in pin PCINT0 = PB0...
      | _BV(PCINT1)   // and PCINT1 = PB1...
      | _BV(PCINT2);  // and PCINT2 = PB2

In these macros, the number n identifies an individual pin. Avr-libc
also defines the macros PCINTm_vect for defining interrupt handlers.
In these macros, the number m identifies a pin group.


How do I erase the memory of the Arduino Uno? I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."

So, what's the normal way people call it a day with these things?  Do you usually load up the bare-bones do nothing sketch or just unplug everything?

When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.

When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.

Or have a loop program with a sleep command.

If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.


Arduino IRremote stops working I'm using a standard 38kHz receiver with Arduino-IRremote library and it works fine for a while but then it stops working. The loop function is running time after time as expected but at some point the library decode function starts returning false until I reset the board.

This example code works for me with any arduino nano or bare atmega328p at 8Mhz but for both of them it freezes after some receptions.

The code is the library example itself:

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

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

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

Some times this happens fast and other times it is after 20 or more receptions.
I only added a led blink later to test if the board is frozen or is only the infrared that stops receiving and it was the second case.

I was having similar problem (but not the same )
And it was due to software serial pins which keep on filling the buffers of MCU.

Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .

To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.


Sum values, store them and print the last value I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.

For instance, I can see on my monitor this:

0 L/hour

0 L/hour

And if I have some water running through,

10 L/hour

20 L/hour

20 L/hour

Then when I stop the flow it goes back to 0.

0 L/hour

Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?

Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.

Paul

What you want to do is integrate the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, 0.002778 L/s * 10 s = 0.02778 L of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:

#define INTERVAL 1000  // sampling interval in millisec
#define HR_TO_SEC 2.778E-4  // number of hours in a second

int curr_rate = 0;  // current flow rate in L/hr
unsigned long lastRead = 0;  // the last time the rate was sampled
float totalVolume = 0;

void loop(){
  if (millis() - lastRead >= INTERVAL){
    lastRead += INTERVAL;
    curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
    totalVolume += curr_rate * HR_TO_SEC;  // update the volume
    Serial.println(totalVolume, 4);
  }
}

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.


Stop Buzzer after some seconds/time? This is a "water level alarm/display" sketch using and Arduino and ultrasonic sensor.
The buzzer gets on when the water level hits 100% or more.
But most of the time the water level will stay @ 100%, and I dont want the buzzer to run for long time.
How can I set the buzzer to make sound only for 15 seconds ?
It should turn off after 15 seconds, even if the water level is @ 100%

#define trigPin 8
#define echoPin 9
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int BUZZER = 10 ;

void setup(){
      int duration,distance,percentage,heightTank;
      Serial.begin (9600);
      pinMode(trigPin,OUTPUT);
      pinMode(echoPin,INPUT);
      lcd.begin(16,2);
      lcd.print("HELLO");
        pinMode(BUZZER,OUTPUT);
}

void loop(){
      int duration,distance,percentage,heightTank,deviation;
      //You'll probably want to change the next 2 lines.
      // The first one is the max. level of the water.
      // The next one is how high the sensor is above that max. level.
      heightTank=65;
      deviation=4;

      digitalWrite(trigPin,HIGH);
      delayMicroseconds(1000);
      digitalWrite(trigPin,LOW);
      duration=pulseIn(echoPin,HIGH);
      distance=(duration/2)/29.1;
      percentage=100-(((distance-deviation)*100)/heightTank);
      Serial.println(distance);
      Serial.println(percentage);
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Current tank");
      //lcd.print(distance);
      //lcd.print(" cm");
      lcd.setCursor(0,1);
      lcd.print("level: ");
      lcd.print(percentage);
      lcd.print(" %");
      delay(1000);

      digitalWrite(BUZZER,HIGH);
  if (percentage > 99) {digitalWrite(BUZZER,HIGH); delay(100); digitalWrite(BUZZER,LOW); delay(100);}
  else  {digitalWrite(BUZZER,LOW);}
  }

For this you will have to implement a finite state machine. This is a
very common paradigm in the embedded world. I recommend you start by
studying this tutorial: The Finite State Machine, by Majenko.

Four your particular problem, I would implement a machine with three
states: IDLE, ARMED and ALARM, the ALARM state being the only one in
which the buzzer is on. The transitions would be:

ARMED → ALARM when the level hits 100%
ALARM → IDLE after 15 seconds spent in the ALARM state
IDLE → ARMED when the level gets below 90%

Note that the only difference between IDLE and ARMED is that the IDLE
state will not go into ALARM when the level reads 100%, as you have to
go through the ARMED state before. The threshold at 90% percent is meant
to add some hysteresis. You can tweak the threshold value to your
taste.

I leave the implementation to you. It should be easy one you have
studied Majenko's tutorial.

Edit: Just to illustrate the generality of the concept, I would like
to point out that the code in Look Alterno's answer can be thought of as
a finite state machine where the state is implicitly encoded into the
variables lastBuzzer and percentage. The implicit state is:

ARMED when lastBuzzer == 0
ALARM when percentage > 99 && millis() - lastBuzzer < 15000L
IDLE when  percentage > 99 && millis() - lastBuzzer >= 15000L

The line lastBuzzer = 0 establishes the ARMED state as soon as
percentage ≤ 99. Note that this lacks hysteresis: if the reading
fluctuates between 99% and 100%, the alarm will sound again and again.

I personally prefer using an explicit state variable, as it makes the
code clearer to me. But then, the best approach is whichever makes the
code clearer to you.


Comparators for digital input mode I've asked another question in electronics about what to use to compare 2 input voltages, the answer was to use comparators.

Digging around a bit, turns out most of the comparators outputs are pull-up, which makes it quite difficult to translate (probably due lack of general electronics knowledge, self-learned) and I'm not able to distinguish from maker's PDFs which comparators have pull-up or pull-down outputs.
I've figured PD comparators illustrate in PDF a resistor right after the output... but many illustrations I've seen doesn't clarify PD / PU, or I'm just missig that.

But my question is, are there any PD comparators (well known) where it's output can be connected to the digital pins or arduino (while those are defined as INPUT mode)?

I appreciate any guidance on this topic.

Just a side note, I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V...

You can't put 12 volts into a Uno input pin in any case.

You could run it into a voltage divider and divide it down to somewhere on the range 0 to 5 V, and then do an analogRead to see exactly (or almost exactly) what the resulting voltage is.

I don't really see where comparators come into it in this particular case. I mean, you could use a comparator to turn the LED on, but then where does the Arduino come into it?

  I've actually tried with voltage divider, I went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly.

You need a voltage divider like this:

Those values give you 4 V on the Arduino pin if there is 12 V on the input.

Vout = (R2 / (R1 + R2) ) * Vin

So:

(1000 / 3000) * 12V = 4V


Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.

When I try to transfer a sketch to the device it fails with error message
avrdude: stk500_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11  and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.

Solved:
The issue was due to an USB Hub which I have at my desktop.
After I connecting the arduino directly to an USB port at my desktop everything was fine.
Unfortunately there is no hint about this in the arduino troubleshooting guide. A hub is only mentioned in conjunction with a MAC.


Arduino development vs nRF51 development Originally I had an idea to develop an Arduino-compatible project using an ATmega328P, some sensors and the nRF51822 as the BLE radio. As I progressed, I realized that if I relaxed the Arduino-compatible requirement, I could actually do away with the ATmega328P and write the application directly on the nRF51822 as it is a more capable MCU (32-bit, more memory, faster, has SPI, I2C and TTL serial, etc.) I'm not familiar with writing native applications for the nRF51822 but it seems much more complicated.

For someone that has experience in both platforms, can you please list some of the tradeoffs of developing using an ATmega328P for application + nRF51822 for radio and using the nRF51822 for both application and radio?

First, there are various ports of the Arduino environment to the NRF51822, but I'll leave that aside for the moment and address using Nordic's codebase or the mbed one.

Generally speaking, one of these paths will put you more in the current "real world" of professional level embedded development, in which the ARM cortex parts play a leading role.  You will have conventional multiple source file projects tied together by more ordinary means such as a Makefile or explicit IDE configuration, rather than the rather oddball way the Arduino IDE has evolved to do things.  The basic lower level APIs you will be writing against will be much more conventional - ie, your code will start in main() rather than setup() and loop(), you will generate debug messages with printf() or similarly styled member function on mbed, rather than Arduino type print()/println() (though of course you can use printf() on an Arduino with some setup).  This tends to make it a lot easier to port or share code between this and other embedded systems, or even between an embedded system and a phone or desktop communicating with or simulating it.  Of course you can treat an Arduino as a plain ATmega and do this with that as well, up to the limits of the CPU and its memories.

People tend to think of the mbed option as being an online "toy" for certain boards, but you can generally use others just by setting it for a board using the same MCU in a similar way.  And in most cases you can download a zipfile of a project with a Makefile in it that will drive arm-gcc or a few other compiler choices.  The NRF51822 does come in varieties with different onboard storage sizes, and this can sometimes require care and attention to the linker script - in a few cases a project that fits in the online build (apparently with the Keil compilation engine as its backed) will not build in the downloaded GCC configuration unless you adjust the linker script to reduce the stack size, or perhaps change compiler optimization levels.

Countering reasons you might end up keeping the ATmega would be if you need some of its I/O peripherals or its 5v I/O capability.  For example, the NRF51822 has limited hardware PWM capability compared to an ATmega so that must generally be done in software.

If you are really at home with "The Arduino Way" switching to anything more traditional may take some adjustment of thinking and habits.  On the other had, if you look at the benefits of Arduino being the variety of works-out-of-the-box, easily modified examples you can use to explore the possibility of a project, but often find yourself annoyed by the legacy of its countless quirks and atypical approaches in the longer run, then you'll probably find the adaptation to using the NRF51822 directly to have been worthwhile.


NRF24L01+ changing configuration after startListening I have been trying to get two Arduino UNO talk to each other via NRF24L01's with TMRH20's NRF24 library. I tried many tutorials and examples and none of them worked. Most of them prints some error messages that's due to radio.write returning false.

After some troubleshooting I saw something weird. I set up the configuration (e.g. data rate) and when I call startListening it seems to be changed back.

This code:

void setup() {

    Serial.begin(9600);
    printf_begin();

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.printDetails();
    Serial.println();

    radio.startListening();
    radio.printDetails();
}

Outputs:

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0x4141417852
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x27
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x02
RF_SETUP     = 0x0f
CONFIG       = 0x08
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 2MBPS
Model        = nRF24L01+
CRC Length   = 8 bits
PA Power     = PA_MAX

You can see that the address was set up correctly before startListening (0x4141417852) but after it reverted back to what I assume is the default value (0xc2c2c2c2c2). Data rate has also changed.

Is this normal?

The other Arduino UNO doesn't have startListening or stopListening, but if I print the configuration after openWritingPipe I see the correct configuration.

The first thing that comes to my mind is that you are powering the nrf24L01 directly from the 3V3 pin of your Arduino Uno. DO NOT do this.

The 3V3 pin does not provide enough current for the nrf24L01. This renders the module completely unstable. You can:

Use a decent capacitor across the VCC and GND on the module. (But I do not recommend going for that solution)
Use a separate 3V3 power source that is capable of handling the current spikes of the nrf24L01. But don't forget to connect its ground to the Ardino Uno aswell.
Use a power module that powers the nrf24L01 from Arduino Unos 5V rail.


Arduino: Sending SD CSV file online at specific time of the day I intend to perform data logging from sensors and store it on SD card as CSV format. The data is related to weather and I would like to send it at the end of the day/
Any available codes how to deploy the SD files from Arduino to the cloud/online at specific time of the day?
Thank you in advance.

Well for CSV, you might as well do dataFile.print(",");. It will log a comma and thus separating your values with a comma.

For logging your data at the end of the day, you have multiple ways.

1- Use a delay (worst idea EVER! Don't do this!). This will require you putting delay(86400000);. Yes that is indeed a 24h delay!

2- Use the millis() function. This function returns the number of milliseconds since the programmed started running. There is an example code called blinkWithOutDelay(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see here.

3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.

Now to send the data. You have may options for this too.

1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.

2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.

Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.


Camera switch with ov7670 to output standard A/V signal - composite I've got 3 OV7670 cameras and would like to create a switch that outputs one of the cameras video as standard A/V out (I'm not sure the correct naming).

I found docs explaining how to use the cameras on the Arduino platform but I'm not sure how to output video signal - composite.

An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see here the signal specification.

Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

you will need a very fast DAC (a flash one)
you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...