Can I use an IR distance sensor in rain? I am planning on using 'SHARP IR Distance Sensor - GP2Y0A710K0F' in an outdoor environment. Assuming the casing I design for the sensor is waterproof, can I use this IR sensor without any trouble? If the water is interfering, what can I do to reduce that noise?

The sensor is fixed above the ground and aimed towards the ground like this.

According to the data sheet for this device, located at Adafruit's web site, the frequency used is 870nm. If you required specific attenuation figures, that might be useful information.

Another web site suggests that thermal IR camera imaging systems (which use a different frequency IR) are attenuated by rain. Some of the IR energy is lost by absorption and some by reflection. I was hesitant to suggest that as the answer due to the different frequencies involved.

Digikey has a document covering wide use of IR sensing. Listed in the document:

The disadvantages of IR technology are:

Line of sight: transmitters and receivers must be almost directly
aligned
Blocked by common materials: people, walls, plants, and other objects can block transmission
Short range: performance drops off with longer distances
Light and weather sensitive: direct sunlight, rain, fog, dust, and pollution can affect transmission
Speed: data rate transmission is lower than typical wired and RF transmission

Even though data transmission is not your objective, the considerations apply. A wet surface over which your sensor passes will have the signal attenuated and may also be slightly diffracted.

I found no direct reference to the magnitude of the attenuation. If your sensor is protected from water intrusion and the surface is only slightly wet, you may have minimal problems reading the distance. If the rainfall is at the level of a frog-strangler, there could be sufficient water to eliminate useful readings.

Another search resulted in a similar question on the physics stack exhange, which led to a more comprehensive answer:

There is another image on the same page, but both show that at the 870nm frequency, there is lower attenuation than much of the IR spectrum, particularly above 3000nm. The above linked document suggests that the affect of rain (water) is low at near-infrared (970-1940nm) but that's still higher than the device's 870nm figure.

For your objective, shielding the surface from rain (umbrella) or clearing the surface of standing water seems to be the best options. If those are impractical, one would have to experiment to determine how much water flow can be tolerated before the signal is lost or attenuated beyond reception limits.


I2C pull up resistors and an I2C MUX I have a rig with 5 light sensors on an I2C mux and I am wondering if I need only 1 pull-up resister set for the whole bus or one on each branch from the mux?
Or should I remove all the pull-ups from the branches and leave the one on the mux?
My issue is that the Arduino softlocks after 5-60 min of running, and it always softlocks on a read lux call.

From what I can tell, the I2C bus multiplexer itself receives and re-transmits on what amounts to a completely separate bus.  So, each bus would need its own pull-up resistors.  That said, the board you've linked that breaks out the multiplexer chip has pull-up resistors on each bus that it's providing:

The breakout also has pull-ups on the bus going to the multiplexor itself:

Beyond that, the ambient light sensor breakout seems to provide its own 4.7K pull-ups. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the guts of the wire library.
It seems you should not necessarily need to add any additional pull-up resistors of your own to what is already on the buses.

With regard to the O.P. comment given below concerned about too many pull-up resistors.
At some point probably below (perhaps far below) 500 ohms some devices may have trouble sinking enough current to create a LOW. The AVR wouldn't have a problem with 500 ohms for example.
The ATMega328P datasheet (along with most other AVR datasheets) will tell you that the internal pullup value is between 20K-50K.  If you're concerned about too-many-parallel-resistors/too-many-current-paths/too-little-total-resistence, you can take the 20K figure along with multiplexer breakout's 4.7K figure, to calculate pow(1 / 20e3 + 1 / 4.7e3, -1), for about 3.8K, which should be fine.  If you do the same calculation on the multiplexor's individual bus resistor 4.7k and the ambient light sensor breakout's own 4.7k resistor, you get 2.35 k (half), which is also probably fine.  If anything both of these total figures can be made smaller (by adding yet another parallel resistor) for longer buses and at higher frequencies.  If you're worried about these figures you can lower the I2C clock rate.  You can also examine the edges of your signal with a scope.  Also if you really want to dig into this stuff, you read in the official I2C manual.  But, really I think what you have is probably fine.


Whatever components we connect to the Arduino, their grounds and 5v pin connection must be the same? I am trying to connect different types of sensors & motors to the Arduino should I make their grounds and 5v pins on the same connection.

All the grounds must be connected. They don't have to be the same physical pin - the Arduino has multiple GND pins, but they are all connected internally.
The 5V doesn't matter where you get that from, as long as it's regulated and the associated ground is connected to all the others.


Measure different Vcc using 1.1V bandgap When I power my ATmega328P chip from 5.16V and 3.3V, there doesn't seem to be a single bandgap voltage compensation figure that works for both.

I'm using the following sketch, and I need the following InternalReferenceVoltage values to read the correct voltage from A0:

1255L to correctly output 5.16V.
1358L to correctly output 3.3V.

I have a couple of questions:

Should I be able to use a single InternalReferenceVoltage compensation value whe powering the ATmega328P from different voltages?
Aren't both of these values outside the specced 1.0 to 1.2 range?

The code is from, http://forum.arduino.cc/index.php?topic=56750.msg407897#msg407897, retolefty post @ Mar 28, 2011, 02:27 pm.

#include <SPI.h>

void setup()
{
  delay(5000);

  Serial.begin(115200);
}

void loop(void)
{
  // Determines what actual Vcc is, (X 100), based on known bandgap voltage
  int battVolts = readVcc1();

  Serial.print("Battery Vcc volts =  ");
  Serial.println(battVolts);
  Serial.print("Analog pin 0 voltage = ");
  Serial.println(map(analogRead(0), 0, 1023, 0, battVolts));
  Serial.println();

  delay(1000);
}

// Returns actual value of Vcc (x 100)
int readVcc1()
{
  uint8_t oldADMUX = ADMUX;

  const long InternalReferenceVoltage = 1255L; // Adjust this value to your boards specific internal BG voltage x1000

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // For mega boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
  // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (0 << MUX5) | (1 << MUX4) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#else
  // For 168/328 boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#endif
  delay(50); // Let mux settle a little to get a more stable A/D conversion
  // Start a conversion
  ADCSRA |= _BV(ADSC);
  // Wait for it to complete
  while (((ADCSRA & (1 << ADSC)) != 0));

  // Scale the value
  int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value

  ADMUX = oldADMUX;

  return results;
}

I have read these other references to try and find a solution:

Measure Vcc using 1.1V bandgap
https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/
http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

The internal reference won't change much. That's why it's a reference.

Running this code on my Atmega328P:

void setup ()
{
  ADMUX = bit (REFS0) | bit (REFS1);  // Internal 1.1V reference
}
void loop () { }

That outputs the reference voltage on Aref. I measured it as follows with different values for Vcc:

Vcc     Aref
------------
5.00   1.085
4.00   1.081
3.30   1.080
3.00   1.079

So you can see that it retains, more or less, the same voltage regardless of Vcc. In any case, there is no way of measuring Aref, unless you have another reference voltage around to compare it to.


Clock frequency VS cycle time I am considering switching from Arduino Pro Mini 5V 16MHz to Arduino Pro Mini 3.3V 8Mhz for some project because I would like to run it with a 4.5V input power.

Will the switch from 16 to 8Mhz double the cycle time of my loop() function ?

Edit -- adding precision:
My loop function is simple: it's reading a couple of sensors with analogRead and setting a few pins to HIGH or LOW. It does not use delay().

Thanks.

The execution time of your loop() will be slightly longer when the CPU
runs at 8 MHz v.s. 16 MHz, but I don't expect the difference
to be significant. CPU-bound functions, such as digitalWrite(), will
run at half the speed. These functions, however, are quite fast. In
contrast, analogRead() is slow, as it takes roughly 110 µs to
execute, so this is likely where your loop() spends most of its time.
The execution time of analogRead() does not depend significantly on
the CPU speed. This function spends most of its time waiting from the
analog-to-digital converter to do its conversion. When the CPU is
clocked at either 1, 2, 4, 8 or 16 MHz, the Arduino core sets the
ADC prescaler so that the ADC is clocked at 125 kHz.
This means the conversion time will be the same irrespective of the CPU
frequency.
Note: You may just use your Arduino Pro Mini 5V 16MHz. This board is
based on the ATmega328P microcontroller, which is rated for frequencies
up to 20 MHz when the supply voltage is between 4.5 and 5.5 V.
According to the datasheet (see freq-Vcc graph), it should safely
run at 16 MHz for any supply voltage between 3.78 and 5.5 V.


Read from analog then cast not showing the correct value I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.

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

void loop() {

  // Let's say 1002 is the analogValue
  int analogValue = (int) analogRead(0);

  // get the percentage
  int value = 100 * analogValue / 1023;

  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
  Serial.println(analogValue); // print the analog value 0...1023
  Serial.println(100 * analogValue); // just for test
  Serial.println(value); // The percentage
  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");

  delay(500);
}

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:

~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~

Max value for int is 32,767. But 100 * 1002 = 100,200. You are overflowing the int. Use unsigned long. Or float and cast to int when printing.


Wire.endTransmission() Hangs I have written a code that transmits data over the I2C channel, The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTrasnmission().

I found the issue using Serial debug messages.

Strange thing:

When i disconnect the SCL line (A5 on arduino Pro Mini), the hang disappears and the code starts to function again.

A search brought me to this forum
http://forum.arduino.cc/index.php?topic=66353.0

where a guy talks about the code snippet

if(hang)
unfreeze();

is this possible, if yes where do i place it?

Observation:  The hang goes away if i disconnect the SCL line on either of the arduinos communicating, the sam edoes not happen if i disconnect the SDA.

The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTransmission().

Nothing is transmitted until you call Wire.endTransmission() so that is where it will hang.

You should not try to do Wire transmissions inside an ISR (if you are doing that).

There is an alternative to the Wire library which times-out rather than hanging. It is at: Arduino I2C Master Library.

Make sure you have pull-up resistors on SDA and SCL. Typically 4.7 k from both to +5 V.

If none of that helps, please post your code.


Is there any option to connect XDTouch IrTouchScreen to Arduino? Is there any option to connect XDTouch IrTouchScreen with USB interface or RS232 to Arduino board?

At the cable of this touchscreen i have something like at the photo.
At the top of the photo pins (+, t, r, -) from touchscreen to SP232EEN, and at the bottom of photo pins (+, D-, D+, -) from CY7C63803-SXC module to USB output.

Looks like your touch screen may talk RS-232. It uses the SP232EEN (a MAX232 clone) to interface with an MCU (Cypress CY7C63803) to get USB.

Connect wires to T1 IN and R1 OUT (I assume it's on channel 1) to your Arduino for UART communication. You would most likely need to disconnect those pins from talking to the Cypress chip, or they will interfere. Use the +5V and GND pins of the USB interface to power it direct from the Arduino.

Alternatively cut that board off and use a cheap MAX232 interface board to connect to the Arduino - that may be cheaper.  T and R are TX and RX (though from which PoV is anyone's guess).


ISR definition causing boot loop? I am trying to compile and upload code to an Arduino Uno from the command-line, however I seem to be experiencing an odd issue.

When I compile this code:

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

ISR(TIMER0_OVF_vect) {
}

int main() {
  while (true);
}

With these commands:

$ avr-gcc -mmcu=atmega328p -DF_CPU=16000000 -std=c17 -O3 -Wall -Wextra -c boot_loop.c -o boot_loop.o
$ avr-gcc boot_loop.o boot_loop.elf
$ avr-objcopy -j .text -j .data -O ihex boot_loop.elf boot_loop.hex
$ avrdude -p atmega328p -c arduino -P /dev/ttyUSB0 -U flash:w:boot_loop.hex

My Arduino ends up in a boot loop, flashing the LED 3 times every second or so (similarly to when you press the reset button or the device powers up).

I've tried it without an empty ISR and also with different interrupt vectors (e.g. TIMER0_COMPA_vect) but to no avail. Completely removing the ISR definition stops the boot loop.

Your problem is not with your code. It's with how you're linking your elf file.

You haven't specified the chip to link for.

$ avr-gcc -mmcu=atmega328p boot_loop.o -o boot_loop.elf


On/off button for Arduino Mega for 5V input pin- hardware based auto on/off arduino(PUSHBUTTON NOT AS INTERRUPT) I am working on Arduino Mega project where I want to add a PUSHBUTTON (Any other can be suggested) that will be programmed in my arduino code, such that if I would press the button arduino code should stop working and when I will press the button back the code should resume from the moment where it stopped.
Button will be attached to 5v pin so that will turn off/on the arduino.

Your question is very badly written, and a lot of infos are missing. In any case, from what I understood from your comments, you want a button that works this way:

The arduino is not powered up
You press the button; the arduino turns on, and starts the operations.
You press the button; the arduino shuts down.
You press the button; the arduino turns on, and resumes the operations from where it was.

I'm not sure about the last point, so first of all I'll give you some hints about the first three points.

You can modify the circuit in a way similar to this:

simulate this circuit – Schematic created using CircuitLab

(I named the two arduino pins as A and B because it is not important which pins you use, just two separate pins).

The diodes can be any diode (e.g. 1N4148). The PMOS and NMOS are not critical, provided that they can fully turn on with a 4-5V gate voltage and that the PMOS can bear the current you need.

When the arduino is shut down, the NMOS is off, and so is the PMOS. When you press the button, the voltage on the NMOS gate becomes about 4.5V, so it turns on. the PMOS turns on too, and so the arduino sees some power. At the very first moment, it has to pull pin B to 5V. This way even when the button is not pressed anymore, the board will be powered. When the user presses the button, the arduino can sense it through pin A. This way it can go into shutdown mode. Here is a sort of base for handling this behavior. Please note that I'm using the Bounce2 library, since I particularly like it when dealing with buttons (it automagically handles bounces and also give more info about the edges).

#include <Bounce2.h>

const byte pinA = the pin A number;
const byte pinB = the pin B number;

Bounce pinA_debounced = Bounce();

void shutdown() {
    // Turn off the board
    digitalWrite(pinB, LOW);
    // Farewell, cruel world!
    while(1); // wait for a power off
}

void setup() {
    // Turn on the board
    pinMode(pinB,OUTPUT);
    digitalWrite(pinB, HIGH);

    // Initializate the debounced pin
    pinA_debounced.attach(pinA, INPUT_PULLUP);

    // Other setup instructions
}

void loop() {
    // Update the Bounce instance :
    pinA_debounced.update();

    if (pinA_debounced.rose())
        shutdown();

    // Other loop instructions
}

If you want to save your data in order to resume it, well, this highly depends on your actual code. You will have to identify what is your "current status", then save it to EEPROM.

Here is, for instance, a program which outputs on serial one sequential number (from 0 to 254, then restart from 0) every second. When you shut it down, it will start again from the last one:

#include <Bounce2.h>

const byte pinA = the pin A number;
const byte pinB = the pin B number;

const byte valueAddress = 0x10; // Any value is fine for this
// as long as it is in the available EEPROM

Bounce pinA_debounced = Bounce();
byte value;
unsigned long lastMillis;

void shutdown() {
    // Save status BEFORE turning down the power
    EEPROM.update(valueAddress, value);

    // Turn off the board
    digitalWrite(pinB, LOW);
    // Farewell, cruel world!
    while(1); // wait for a power off
}

void setup() {
    // Turn on the board
    pinMode(pinB,OUTPUT);
    digitalWrite(pinB, HIGH);

    // Initializate the debounced pin
    pinA_debounced.attach(pinA, INPUT_PULLUP);

    // Restore the current value from EEPROM
    value = EEPROM.read(valueAddress);
    Serial.begin(9600);
    lastMillis = millis() - 1000;
}

void loop() {
    // Update the Bounce instance :
    pinA_debounced.update();

    if (pinA_debounced.rose())
        shutdown();

    if ((millis() - lastMillis) >= 1000)
    {
        lastMillis += 1000;
        Serial.println(value);
        value++;
    }
}


Understanding the ESP8266 I've received my ESP8266-01 and playing with it I discovered that with a baudrate of 74880 I can get the boot modes and `hy version, etc:
 ets Jan  8 2013,rst cause:1, boot mode:(3,0)

load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 249
rf[112] : 00
rf[113] : 00
rf[114] : 01

SDK ver: 1.5.4.1(39cb9a32) compiled @ Jul  1 2016 20:04:35
phy ver: 972, pp ver: 10.1

With this baudrate I'm not able to check the AT commands. Then, when I switch to a baudrate of 115200 I am able to communicate with the ESP:

Ai-Thinker Technology Co. Ltd.
ready
AT
OK
AT+CWL
ERROR
AT+CWJAP?
No AP
OK
AT+CWLAP?
ERROR
AT+CWLAP
+CWLAP:(4,"bbox2-7f0d",-88,"00:1 ",1,-46,0)
+CWLAP:(0,"PROXIMUS_FON",-94,"06: ec:6b",1,-47,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-88,"0a: :ec:6b",1,-44,0)
+CWLAP:(3,"WiFi-2.4-BB3D-ext",-51,"00: 9a:38",1,-12,0)
+CWLAP:(3,"NGUYEN",-79,"e0:b ",11,-2,0)
+CWLAP:(0,"PROXIMUS_FON",-81,"42:6 ",11,0,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-79,"42 ",11,0,0)
+CWLAP:(4,"WiFi-2.4-6858",-75,"4 e",11,1,0)
+CWLAP:(0,"PROXIMUS_FON",-89," ",11,-6,0)
OK

How is that possible that it has two different baudrates?

Thanks in advance,

How is that possible that it has two different baudrates?

Very simple. Exactly the same as the Arduino.

If you put:

Serial.begin(9600);

in your program then your sketch runs with the serial port at 9600 baud. However, just before then, the bootloader runs at 115200 baud for a few seconds listening for instructions from the PC.

There's no magic there.

You can even do it yourself:

Serial.begin(9600);
Serial.println("Hello at 9600 baud");
Serial.flush();
Serial.end();
Serial.begin(115200);
Serial.println("Hello at 115200 baud");
Serial.flush();
Serial.end();

The baud rate isn't fixed. It's whatever the firmware that is running at that precise moment deems it to be - whether that is the bootloader, the AT firmware, or your own custom sketch.


W5100 Ethernet shield DHCP fails with a Switch we are using Arduino W5100 Ethernet shield. The code is to try DHCP first and if that fails, then try the static IP. we do the Ethernet Initialization and stop every time.  The library is Arduino Ethernet library.

when we try with a wireless router, everything works and we are able to contact our web server.
Now the wireless router is connected to a switch.
switch <======> router <=====> W5100

if we try to send data using the switch directly, DHCP fails, whereas a laptop using the same cable works.

Question is, even Arduino Library has DHCP functionality, why should a laptop work where the shield is failing? The network and topology and rules should be same for both the laptop and W5100 shield. Anything we can do to debug this issue more?

Edit1 : -  Switch which we are using is L3 in nature.

Below is the code which we are using at present.

    while(1) {

        KDEBUG("wait 10 seconds...\r\n");
        // wait 10 seconds
        for(loop = 10; loop > 0 ; loop--) {
            wait_millis(1000);
        }

        KDEBUG("Try transmitting data on ethernet...\r\n");
        transmit_data();

    }

    return 0 ;

}

void wait_millis(uint16_t num) {

    for(; num > 0 ; num-- ) {
        _delay_ms(1) ;
    }

}

// transmit data using Ethernet
static uint8_t transmit_data() {

    char request[256];
    uint8_t status = 0  ;

    // reset counter
    counter = (counter > 254) ? 0 : counter ;

    memset(&request[0], 0 , sizeof(request));
    memset(&bencode[0], 0 , sizeof(bencode));

    wait_millis(5000);
    // try DHCP
    if (Ethernet.begin(mac_address) == 0) {
        KDEBUG("Failed to configure Ethernet using DHCP \r\n");
        // use static IP. no return code.
        Ethernet.begin(mac_address, ip_address);

    } else {
        KDEBUG(" Got lease from DHCP \r\n");
    }

    // wait for ethernet to initialize:
    wait_millis(5000);

    // we got a connection?
    status = client.connect(server, port) ;
    KDEBUGF("ethernet client  status= %d \r\n", status);
    if(!status) {
        goto quit ;
    }

        KDEBUG("connected \n");
    // create an HTTP request
    strcat(request, "GET /api/gl868.php?data=");
    strcat(request,bencode);
    // 12 chars
    strcat(request," HTTP/1.1 \r\n");
    // 25 chars
    strcat(request,"Host: ");
    strcat(request,server);
    strcat(request," \r\n");

    // send GET request
    client.println(request);
    _delay_ms(1);
    client.println() ;

    wait_millis(1000);
    client.stop();
    wait_millis(1000);

    if(client.connected()) {
        client.stop();
    }

    return 1 ;

quit:

    wait_millis(100);
    if(client.connected()) {
        client.stop();
    }

    return 0 ;

}

A certain way to debug this is to use tcpdump to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for DHCPDISCOVER packet that Arduino should be sending.

A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.


cannot resolve overloaded function... error I started to learn Arduino and I want to get an input from user to blink LEDs. I wrote under the void loop() section input codes. After i compiled it and Arduino IDE gave me this: "Arduino:1.8.5 (Windows 10), Kart:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\Yunus Emre ERYILMAZ\Documents\Arduino\sketch_feb17a\sketch_feb19a\sketch_feb19a.ino: In function 'void loop()':

sketch_feb19a:27: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numBlueBlink=Serial.parseInt;

             ^

sketch_feb19a:31: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numYellowBlink=Serial.parseInt;

               ^

exit status 1
cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

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

What should i do, how can solve this problem? Thanks.

The code that i wrote:

int blueLEDPin=9;  // Declaring blue led's pin is 9.
int yellowLEDPin=10;  //Decllaring yellow led's pin is 10.
int blueOnTime=250;  // Bue led ontime
int blueOffTime=250; // Blue led offtime
int yellowOnTime=250; // Yellow led ontime
int yellowOffTime=250; // Yellow led offtime
int numBlueBlink=0;
int numYellowBlink=5;
String blueMessage="The blue LED is blinking...";
String yellowMessage="The yellow LED is blinking...";

void setup() {
  String wm1 = "Welcome to";
  String wm2 = " My Program";
  String wm3;
  wm3 = wm1+wm2;
  Serial.begin(115200);
  Serial.println (wm3);
  pinMode (blueLEDPin,OUTPUT);
  pinMode (yellowLEDPin, OUTPUT);

}

void loop() {
Serial.println ("How many times do you want the blue LED to blink? ");
while (Serial.available()==0){ }
numBlueBlink=Serial.parseInt;

Serial.println ("How many times do you want the yellow LED to blink? ");
while (Serial.available()==0){ }
numYellowBlink=Serial.parseInt;

Serial.println (blueMessage);
for (int j=1; j<=numBlueBlink; j=j+1) {
  Serial.print ("   You are on Blink #: ");
  Serial.println(j);
  digitalWrite (blueLEDPin,HIGH);  // Turn first led on
  delay (blueOnTime);  // Wait
  digitalWrite (blueLEDPin,LOW); // Turn first led off
  delay (blueOffTime); // Wait
}

Serial.println (" ");

Serial.println (yellowMessage);
for (int k=1; k<=numYellowBlink; k=k+1){
  Serial.print ("   You are on Blink #: ");
  Serial.println (k);
  digitalWrite (yellowLEDPin,HIGH); // Turn second led on
  delay (yellowOnTime); // Wait
  digitalWrite (yellowLEDPin,LOW);  // Turn second led off
  delay (yellowOffTime);  // Wait
}
Serial.println (" ");
}

The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of

 numBlueBlink = Serial.parseInt;

you have to write

 numBlueBlink = Serial.parseInt();

See Serial.parseInt for a reference.


2 instanced of ESP8266Ping I'm using ESP8266Ping lib inside my iot lib which hanldes Wifi connectivity and MQTT messages. Since it create its own instance called Ping when calling #include <ESP8266Ping.h>- it had to be place in iot.cpp.
I writing another library, IPmonitor which checks clients on the network (using pings), I wanted to use ESP8266Ping again.
My sketch file, create an instance of iot and IPmonitor for check/ log errors on monitored clients.
But I get error of using the same library twice.
I guess that since ESP8366Ping.h library is defined it creates an instance of the class ( see mark below ):
class PingClass {
  public:
    PingClass();

    bool ping(IPAddress dest,   byte count = 5);
    bool ping(const char* host, byte count = 5);

    int averageTime();

  protected:
    static void _ping_sent_cb(void *opt, void *pdata);
    static void _ping_recv_cb(void *opt, void *pdata);

    IPAddress _dest;
    ping_option _options;

    static byte _expected_count, _errors, _success;
    static int _avg_time;
};

#include "ESP8266Ping.impl.h"
PingClass Ping;                     // <----- This

#endif

How can it be solved ?

With that library... you can't. All the code is in one big monolithic .h file. As you well know by now that is a big no-no. The author should be given a big slap on the wrists.
The closest you could do without re-writing the whole library is to just copy the class definition from the outer .h file and create an extern to the existing object - maybe make your own copy of the ESP8266Ping.h file without the #include "ESP8266Ping.impl.h" and PingClass Ping; (the latter of which you change to an extern).


Detecting an incoming 7.875 kHz pulse to use as trigger I have written a code that detects an incoming pulse (square) of 7.875 kHz to trigger the output High for the entire duration of pulse, and trigger the output low if the pulse is off or not detected.
CODE
// Define pins
volatile int pulse1 = 2;    //incoming pulse 1 on pin 2

const int ledPin = 13;   //output to trigger LED

void setup() {

  pinMode(pulse1, INPUT);

  pinMode(ledPin, OUTPUT);

  // Timer Setup

  TCCR1A = 0;               // set entire TCCR1A register to 0
  TCCR1B = 0;               // same for TCCR1B
  TCNT1  = 65282;           // initialize counter value
  TCCR1B |= (1<<CS10);      // set prescaler to 8 bit
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

}
ISR(TIMER1_OVF_Vect){
  TCNT1 = 65282;
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV2, FALLING);
  }

void loop() {
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, RISING);

}

// Interrupt routines

void ISR_UV1(){
  digitalWrite(ledPin, HIGH);      // Send high signal
}

void ISR_UV2(){
  digitalWrite(ledPin, LOW);      // Send low signal
}

Is it the correct approach, or am I doing it wrong. One last thing that is bothering me is, every time I connect a wire (not connected to anything) to the input pin 2, it sends a high signal, and keeps the signal high until the Arduino is reset.
The pulse is a square wave 50% duty cycle generated by a device. I dont need to measure it or count it. I am just using it as a trigger to send a HIGH signal when it occurs. So it stays on (occurs) for 25ms & turns off during which its freq. is 7.875MHz & then it is repeated by the device according to the device parameters. I am aware it is a very short pulse but for the purpose of project nothing else can be used as the trigger
Any help will be appreciated.

So i figured out what the problem was, I had to detach interrupts in the interrupt routines not in my main code. So basically these changes:
void loop() {
  digitalWrite(ledPin, LOW);
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, CHANGING);

}

& in the Interrupt routines:
digitalWrite(ledPin, HIGH);      // Send high or Low dpending on the routine
detachInterrupt(digitalPinToInterrupt(pulse1));

& basically this works like a charm, & there are still issues with the timer, but that will be solved in my main code with another sensor.


Using softwareserial with a TFT, how can I use a variable to position cursor? I have tried several different ways to do this, but in the line:

myTFT.println("DS32(32,g,'Hello!',4);");

where g is an int, it simply doesn't print. If I just replace the g with a value of any kind, all is well.

I'm using an Uno (well, an Orion board from Makeblock) and the Makeblock TFT.

All my other print lines work fine but of course, none contain variables.

Just split the print into three parts:

myTFT.print("DS32(32,");
myTFT.print(g);
myTFT.println(",'Hello!',4);");


Parsing Arduino Receiving Strings I'm currently using google geolocation to get location data to one nodemcu and sending it through serial to another Arduino.
The serial command I'm getting right now is,

1.450187T103.824745

I'm using the following code to parse it.

 if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    //if (c == '\n') {  //looks for end of data packet marker
    if (c == '\n') {
     // Serial.println(readString); //prints string to serial port out
      //do stuff
      substring = readString.substring(0,8);
      lati = substring;
      loc = readString.indexOf("T");
      substring = readString.substring(loc+1, loc+11);
     longi = substring;
       readString=""; //clears variable for new input
      substring="";

    }
    else {
      readString += c; //makes the string readString
    }
  }

It works most of the time but sometimes I get 'T' inside the string as well.
like this

lat=1.450146&longi=102464T103

What's wrong in my code?

with readBytesUntil and C string

if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  char* p = strchr(buff,'T'); // returns pointer in string
  if (p != NULL) {
    *p = 0; // write 0 as char at pointer to terminate the first part
    p++; // move the pointer to next char
    Serial.println(buff);
    Serial.println(p);
  } else {
    Serial.println(buff);
  }
}


Copy content of array This may be an easy question, and if so im sorry, but i couldn't find out how to do this. I've programmed in python before and hoped that this would work, but it don't.

int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int newArray[] = myArray2;

I wanted to only have to change one place in my code, which of the first three arrays i want my new array to take values from. Do anyone have any suggestions on how to do this?

Make newArray be a pointer to whichever array you wish to work with.  For example:

int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int *newArray = myArray2;

// ... work with selected array, via newArray[] subscripting

Note, you may need to set an array-length variable at the same time as choosing the array.

For example:

int *newArray = myArray2;
int newSize = sizeof(myArray2)/sizeof myArray2[0];

// ... work with selected array

newArray = myArray3;
newSize = sizeof(myArray3)/sizeof myArray3[0];
// ... work with selected array

Alternately, add an array-end marker at the end of each array (eg, a negative number), or more elegantly, make all the arrays the same length.

If you want to make a new copy of the original array, such that modifying the new array won't change the old, use (eg) memcpy().  For example:

int newArray[7];
...
memcpy(newArray, myArray2, sizeof(myArray2));

Note that memcpy()'s size argument is given in bytes.  Also, if you need to declare memcpy() [I don't recall whether it's automatically declared in the Arduino environment], add #include <string.h> up front.


Output frequency from an SPI DAC (MCP4922) is lower than expected I'm using a 2-channel, 12-bit DAC (MCP4922, datasheet) with an Arduino Uno, using the library written for it here. With the clock divider set to 2, I should have the SPI clock frequency at 8MHz. If each value sent to the DAC takes about 12 of these clock cycles, that leaves me with about 650kHz as my output frequency (when I'm sending a simple on-off signal like below), but the fastest I see is about 25kHz.

  void loop() {   dac.output2(4095, 0);   dac.output2(0, 4095);  }

Am I misunderstanding how the transfer protocol works? How can I make this faster? I'd like to both understand why this is so slow, and also to get an output frequency of at least 50kHz.

Let's do some maths...

16MHz master clock / 2 = 8MHz SPI clock
2 transactions = 16 bits (not 12!)
8,000,000 / 16 = 500,000
2 transitions per cycle
2 channels
2 + 2 = 4
500,000 / 4 = 125,000Hz

So in a perfect world you could expect 125kHz from the DAC. However the world is far from perfect.

Let's look at what it's actually doing when you use output2():

void DAC_MCP49xx::output2(unsigned short data_A, unsigned short data_B) {
  this->_output(data_A, CHANNEL_A);
  this->_output(data_B, CHANNEL_B);

  // Update the output, if desired.
  // The reason this is only in the dual-output version is simple: it's mostly useless
  // for the single-output version, as it would make more sense to tie the \LDAC pin
  // to ground, or do it manually. However, there should be a single-call method
  // to update *both* channels in sync, which wouldn't be possible with multiple
  // separate DACs (for which there is latch()).
  if (automaticallyLatchDual) {
    this->latch();
  }
}

Assuming automaticallyLatchDual is false we can pretty much ignore that section. So it's calling _output() twice - once for each channel. And what does that do?

void DAC_MCP49xx::_output(unsigned short data, Channel chan) {
  // Truncate the unused bits to fit the 8/10/12 bits the DAC accepts
  if (this->bitwidth == 12)
    data &= 0xfff;
  else if (this->bitwidth == 10)
    data &= 0x3ff;
  else if (this->bitwidth == 8)
    data &= 0xff;

  // Drive chip select low
  if (this->port_write)
    PORTB &= 0xfb; // Clear PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, LOW);

  // bit 15: 0 for DAC A, 1 for DAC B. (Always 0 for MCP49x1.)
  // bit 14: buffer VREF?
  // bit 13: gain bit; 0 for 1x gain, 1 for 2x (thus we NOT the variable)
  // bit 12: shutdown bit. 1 for active operation
  // bits 11 through 0: data
  uint16_t out = (chan << 15) | (this->bufferVref << 14) | ((!this->gain2x) << 13) | (1 << 12) | (data << (12 - this->bitwidth));

  // Send the command and data bits
  SPI.transfer((out & 0xff00) >> 8);
  SPI.transfer(out & 0xff);

  // Return chip select to high
  if (this->port_write)
    PORTB |= (1 << 2); // set PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, HIGH);
}

That's quite a lot. All those boolean mathematics operations and decision making slows things down a lot. So does hopping from function to function (yes, the compiler will possibly try and inline some things).

Even the SPI.transfer() isn't that efficient with checks and while loops, etc.

To get anywhere near the kind of speed you are looking for you would need to use non-blocking SPI code so you can be transferring a byte out of the SPI port at the same time as getting the next byte ready to send. You don't need to wait for the current SPI transfer to finish (as the SPI library does), you just need to be sure that the previous one has finished before you start the next one.


is there any real arduino emulators (so I can upload and run machine code on it) I play with Arduino Micro. I write my programs in directly in machine code, in binary editors (yes, I know that there are more easy ways to program an Arduino, I do it for fun and learning). Often my programs work, but if not, then I would like to run them on an emulator to understand what's exactly going on under the hood. Is there any Arduino emulator that accepts hex files with compiled program and can execute it? I already looked at tools mentioned at Can I program for Arduino without having a real board? , but as far as I see, they are simulators rather than emulators and I can't use compiled binary programs in them.

There are many different processors used in making many different types of Arduino boards.  So there is no one way to write Arduino machine code.

There are emulator for simpler processors available for the asking.  But, while they work, it is not believe they claim to be totally accurate.

At one point in processor development history, ICE machines were widely used.  This is where a real processor is modified to allow access to internal controls and registers.  (This actually sounds like the answer to your question.)  However, as processors grew in speed and complexity, this approach grew out of favor.

Currently, most processors are built with extra internal circuitry and interface to break program execution for debugging purposes.  JTAG is one such industry standard / example.

So, while the question has merit, the common practice is likely not to run code on an emulator, but to run it on the processor using the JTAG interface and an IDE running on a host-computer / work-station.


Using PBC library on Arduino I want to know if there is a way to install/use the PBC library on Arduino UNO. I want to implement some cryptographic primitives using PBC library.

Thank you.

You could use the RELIC toolkit. It has PCB and they have scripts to compile for Due and Mega. I'm not sure if you could use this with Uno. But this library targets resource-constrained devices.


When the TX and RX pins for Bluetooth are connected the LCD screen will not update. Why is that? I have connected a Bluetooth shield and LCD screen to an Arduino Uno. I have two active low push buttons to increase or decrease the variable desiredTemp. This value is meant to be displayed on the LCD screen, and on my smartphone over the Bluetooth serial connection.

This works as intended for my smartphone, however, when my transmission and receive pins are connected to the board the LCD screen is frozen until the pins are removed. Additionally, I'm not able to update the desiredTemp variable through the Bluetooth serial connection.

Attached is my code:

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

LiquidCrystal LCD(10,9,3,2,1,0);
double inIRPin = A0;
double inThermPin = A1;

int LED = 4;
char recvChar;

int increaseTemp = 7;
int decreaseTemp = 6;
int increaseTempState = 0;
int decreaseTempState = 0;

#define RxD         13
#define TxD         12
SoftwareSerial BTSerial(RxD,TxD);

double valIR = 0;
double valTherm = 0;
double val = 0;
double temp = 0;
double const tempRatio = 0.125;
double desiredTemp = 40; //Degrees Celcius

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

 pinMode(increaseTemp,INPUT);
 pinMode(decreaseTemp,INPUT);

pinMode(RxD, INPUT);
pinMode(TxD, OUTPUT);
pinMode(LED, OUTPUT);
setupBlueToothConnection();

pinMode(inIRPin, INPUT);
pinMode(inThermPin, INPUT);
LCD.begin(16,2);
LCD.setCursor(0,0);

}

void loop() {
  // put your main code here, to run repeatedly:
   valIR = analogRead(inIRPin); //IR Sensor Output
  valTherm = analogRead(inThermPin);

   increaseTempState = digitalRead(increaseTemp);
   decreaseTempState = digitalRead(decreaseTemp);

   if(increaseTempState == LOW){
    desiredTemp++;
  }
   if(decreaseTempState == LOW){
     desiredTemp--;
   }
   if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
      BTSerial.println(desiredTemp);
      if(increaseTempState == LOW){
         desiredTemp++;
         updateLCD();
       }
       if(decreaseTempState == LOW){
         desiredTemp--;
         updateLCD();
       }
       if(recvChar == '1'){
         BTSerial.println("Increasing Temp");
         desiredTemp++;
       }
       if(recvChar == '0'){
         BTSerial.println("Decreasing Temp");
         desiredTemp--;
       }
   }
    updateLCD();
  }

 void setupBlueToothConnection()
 {
    BTSerial.begin(9600);

    BTSerial.print("AT");
    delay(400);

    BTSerial.print("AT+DEFAULT");             // Restore all setup value to
    factory setup
    delay(2000);

    BTSerial.print("AT+NAMESmartCoaster");    // set the bluetooth name
    delay(400);

    BTSerial.print("AT+PIN0000");             // set the pair code to connect
    delay(400);

    BTSerial.print("AT+AUTH1");             //
    delay(400);

    BTSerial.flush();

  }

 void updateLCD(){
      LCD.setCursor(0,0);
      LCD.print("Current Temp:");
      LCD.println(temp);
      LCD.setCursor(0,1);
      LCD.print("Desired Temp:");
      LCD.println(desiredTemp);
      delay(100);
  }

You connected the LCD module to serial hardware pins 0 (RX) and 1 (TX).

When you receive the data from the Bluetooth module, through the software serial, you send it to the hardware serial.

if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
...

This messes up the communication with the LCD module. Remove Serial.print(recvChar); and it should work.

A more sensible solution would be to use hardware serial for the Bluetooth module and the other pins for the LCD module.

Software serial should only be used, if you really can't use the hardware serial, e.g. you need the hardware serial to communicate with another device (a PC or some other module).


2 digit number to 2x 1 digit Suppose I have a number with 2 digits, 42.
It is an integer, received from my RTC

Now for my 7 segment displays, I will need 2 seperate numbers,
4 on display 1.
2 on display 2.
How do I slice this number in 2?

Numbers retrieved from an rtc are usually returned as a char or integer.

On this basis, you want

ones_column = bytefromrtc % 10;
tens_column = (bytefromrtc / 10) % 10;
hundreds_column = (bytefromrtc / 100) % 10;

the % operator returns the modulus - if you divide 42 by 10, the answer is 4, with a remainder of 2. % returns the remainder, in this example, 2.

To do the tens column, first get rid of the last digit by dividing by 10, then do the modulus as above. Since bytefromrtc is not a float, if you divide it, you lose the remainder - 42 / 10 = 4, not 4.2.

If the output is a word, or integer, or long integer, the method is exactly the same, except for the number of digits you can get out.


How do I create a constant loop with an event that only occurs once? I am currently working in void loop() and have setup a distance meter that constantly checks the distance.

Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?

if (distance <= 150){
    personPresent();
    }

  if(distance > 150){
    personAbsent();
      }

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.

In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

What you want is not to check the distance but to check that the distance condition changed.

static boolean present = false;

Inside loop:

if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}


Reading the DotStar datasheet - power requirements I'm trying to figure out my power requirements for a strand of Adafruit DotStar LEDs - APA102 Cool White, not the RGB. I'm not sure how to interpret the datasheet.

In the middle of the product spec table on page 1, under Power Consumption, it says 0.2W (MAX: 1W).  Which would mean at 5V, MAX would be 0.2A, or 200mA.

Then on page 3 in the electrical characteristics table under the symbol/Parameter "LOL/Sink Current Voltage" it says typ. 24.5mA; max. 26.5mA.

I plan on having the strand on full brightness most of the time.

So which is it?  200mA? or 26.5mA?

You have correctly worked out:

I(A) = P(W) / V(V)

I = 0.2 / 5
I = 0.04A

MAX:
I = 1 / 5
I = 0.2A

From that it seems it will use between 40 - 200mA depending on brightness.

Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

More information on current sinking


Typedef not accepted as a data type in a function? I know I'm in a C++ compiler, but I typically create a typedef from structures, probably a holdover from earlier C programming. So this has my head spinning. I create a Typedef from a structure. After that, I have no trouble declaring a global or local version of that structure anywhere in a function, or outside of all functions (global). But when I try to create a function with this typedef as an arg, or even a function arg with a pointer the such a typedef, the compiler complains (and the complaint doesn't seem to make sense). Example...

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint16_t codeID;

// a few more vars

  uint8_t powerDownSaveFlag;       // lets me know why we're being reset.
  uint8_t future[10];
} Sunstates;

So now, this typedef seems as good as any other. Either of these statements compile fine...

Sunstates sunStates;
Sunstates * pSS = &sunStates;

But if I now try to create a function, with either an instance of this data type or a pointer to it, like so...

void systemDataVerify(Sunstates *pST) {  }

The compiler arduino compiler offers this confusing error message...

  Arduino: 1.8.3 (Windows XP), Board: "Arduino Nano, ATmega328"

  SolarControler_21a:393: error: variable or field 'systemDataVerify'
  declared void

  void systemDataVerify(Sunstates *pSS) { }

                   ^

  SolarControler_21a:393: error: 'Sunstates' was not declared in this
  scope

  SolarControler_21a:393: error: 'pSS' was not declared in this scope

  void systemDataVerify(Sunstates *pSS) { }

  exit status 1 variable or field 'systemDataVerify' declared void

The fact that it doesn't like me declaring a function void is odd, but not as troubling as it calling my function a 'variable or field' and definitely not as strange as it saying my datatype (Sunstates) was NOT"declared in this scope. The data type was defined immediately before the function.. and the fact I could declare both instances of the type AND pointers to it kind of proves it exists within the scope. Can someone help me understand why the compiler is complaining?

Edit... I was asked to include a short sketch that shows the problem...

uint8_t somefunction()
{
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag;       // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates;    // creat an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p)
{
return;
}

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

}

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

Now... I have discovered that if I remove the 'somefunction()' definition before the Structure definition, the problem goes away. And I'm using Arduino 1.8.3 to compile this.

I do not get this error in Arduino IDE 1.8.5 with snippet you provided, but I get it in Sloeber Eclipse plugin. The later attached sketch fails to compile in Arduino IDE 1.8.5 too.

The error is in Arduino build chain ino to cpp conversion for the C++ compilation. Put the typedef declaration into .h file and include it in ino.


nodemcu EEPROM corrupting Platform

Hardware:                 [nodemcu amica ESP8266MOD]
Core Version:         [nodemcu-master-21-modules-2018-03-17-17-09-10]
Development Env:      [Arduino IDE|]
Operating System:     [Windows|]

Settings in IDE

Module:           |Nodemcu]
Flash Mode:           [qio|dio|other]?
Flash Size:       [1MB]
lwip Variant:   [v2 Lower Memory]
Reset Method:     [nodemcu]
Flash Frequency:  [40Mhz]
CPU Frequency:        [80Mhz]
Upload Using:     [SERIAL]
Upload Speed:   [115200] (serial upload only)

Problem Description

hi, in my code i did a simple thing. i get the data from jSon object and write them to the EEPROM. once i write them to eeprom i can read the relevant data from that writing function handleFinishWizard()  (i have put reading functions here n there to find where is the problem) .When i write data and finish it i can read the data.once its over when the program moved to the loop, eeprom data are corrupted and it doesnt display anything. i attached the output in debug message. whats the problem here?

[MCVE] Sketch

code in github CODE LINK

Debug Messages

```
add 1
aid 1
station: c0:ee:fb:ed:3b:0e join, AID = 1
value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM save:

value on EEPROM save:

value on EEPROM save:

```

Look at this code:

void setupCredentials(const char *ssid, const char *password,
                      const char *link) {
  int addr = 0;

  EEPROM.begin(512);
  addr = sizeof(int);
  EEPROM.put(addr, ssid);
  delay(10);
  addr += sizeof(st_ssid);
  EEPROM.put(addr, password);
  delay(10);
  addr += sizeof(st_password);
  EEPROM.put(addr, link);
  delay(10);
  EEPROM.commit();

You are calling EEPROM.put(addr, ssid) with ssid being a const char*. A pointer to some memory location. Notice that you only give it a start address and a pointer, not the length of your data.

Have a look at the implementation of the put function:

  template<typename T>
  const T &put(int const address, const T &t) {
    if (address < 0 || address + sizeof(T) > _size)
      return t;
    if (memcmp(_data + address, (const uint8_t*)&t, sizeof(T)) != 0) {
      _dirty = true;
      memcpy(_data + address, (const uint8_t*)&t, sizeof(T));
    }

    return t;
}

What it essentially does is copy your given object const T &t into its internal _databuffer. The size of the data saved is determined by sizeof(T).

In your example t = ssid, T = const char* and sizeof(T) = sizeof(char*) = 4 and addr= sizeof(int) = 4.

What you are doing here is not to save the string that ssid points to in memory but the pointer value of ssid. After you leave the function the data pointed to by ssid will be de-allocated at some point and the memory will be overwritten by something else.

When you do a print directly in the function you are retrieving the pointer value of ssid 3 times and print that value. At that point the data is still there and everything is okay. Then if you print it again after leaving the function you get garbage because the local data is gone after the function call handleSetup is left.

What you want here is to not use a const char* in your second argument to a  EEPROM.put(address, object) call but a char [20], for example. This way the put will work correctly.

Example:

// Assume EEPROM.begin() was called already
void EEPROM_SaveSSID(const int address, const char* str) {
    char ssid_buf[20];
    strncpy(ssid_buf, sizeof(ssid_buf) - 1, str);
    EEPROM.put<char[20]>(address, ssid_buf[0]); //sizeof(ssid_buf) = 20
    //don't forget to EEPROM.commit(); and EEPROM.end()
}

/* read SSID into a pre-allocated buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    EEPROM.get(address, ssid_buf); //sizeof(ssid_buf) = 20
}

If you do not like the semantics of these C++-templates auto-determining the size of read/write calls, you can always use bytewise read and write calls:

void EEPROM_SaveSSID(const int address, const char* str) {
    for(size_t i = 0; i < strlen(str)) {
        EEPROM.write((int)(address + i), str[i]);
    }
}

/* always read 20 bytes starting from given address into buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    for(size_t i = 0; i < sizeof(ssid_buf); i++) {
        ssid_buf[i] = EEPROM.read((int)(address + i));
    }
}

See "EEPROM" (actually: Flash-emulated EEPROM) implementation code at https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM.


Using SD shield for extra external memory? I am an Arduino beginner and I am planning to make a musical instrument with it. I want to add record and playback functionalities into the instrument.

I figure I will have to store lots of data to meet this feature, but the Arduino I'm using (Uno/Nano) probably won't have enough memory to hold lots of songs.

My question is, is using an SD card with an SD shield a good way to expand memory? If not, what should I use to do so?

Thanks

There are different options:

SD shield: much memory (GB's), however keep in mind that it will take time to retrieve the data from the SD card. Also you can retrieve 512 bytes every time (which also means it costs 512 precious bytes of arduino SRAM).
External SRAM: There are external SRAM ICs, like 23LC1024 or 24K256. These are much faster and offer 128 or 32 KB. There are many others too, these are most 'common'. These are much faster than SD cards, you can get 1, 2 or more bytes per time. But it's not the same as Arduino SRAM, e.g. you cannot really store variables, so you have to copy data to internal SRAM to be used.

So first, check how much you need, and more important: what is the latency you can live with.


Problems with inputting into serial monitor I am currently working on a project where i take a frequency, and i want the code to take that value and use a formula to work out its mmh2O level. I use the Serial Monitor to input the values, but i have a problem. When writing the values e.g. "44.62352548","44.49151522". The value that is sent is wrong and displayed wrong.

I know the code i have written does not support this many signigicant figures from a float. And i have tried a few things to try and solve it but i cannot crack it.
I have tried using dtostrf() command, but i have never used this before and dont understand. Somebody from the arduino Forums had helped me out but it didnt seem to work.
I have also tried formatting aswell, and that did not seem to work.
If anyone has any help and advice it would be much appreciated.
float level;
float myValue;

String msg1 = "Enter Frequency (type 0 to exit): ";
String msg2 = "Your Frequency is: ";

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

void loop()
{
  Serial.print(msg1);

  while (Serial.available() == 0);
  {

  }
  myValue = Serial.parseFloat();
  if (myValue == 0.0)
  {
    Serial.end();
  }
  else
  {
    freqConversion();
  }
}

 void freqConversion()
{
  level = (myValue-44.712)/-0.0285493333;
  Serial.println(myValue);
  Serial.print(msg2);
  Serial.println(level);
}

You have hit a bug in the implementation of parseFloat().
This function reads the number you send as an integer, ignoring
the decimal point, and stores it in a long. It then multiplies it by a
scaling factor (a power of 0.1) in order to get the correct value. The
problem is, if you provide too many significant digits, the integer
overflows, and you get garbage. For example "44.64978683" is interpreted
as
(long) 4464978683 * 0.00000001

but (long) 4464978683 overflows and rolls over to 170011387, hence the
result you get.
Simple workaround: do not provide so many significant digits. They are
irrelevant anyway given the resolution of a float.
Edit: I did not find any bug report for this issue, so I submitted my own to the Arduino dev team.
Update: Per request of a maintainer, I submitted a pull
request with a failing unit test revealing this bug. We then worked
on a fix, which has now been merged to master. It should be published on
the next release of ArduinoCore-API.
Note, however, that the AVR core does not yet use the common API
repository. In the meantime, it may be worth submitting a pull request
to ArduinoCore-avr that cherry-picks the fix from ArduinoCore-API.


exit status 1 'mcpButtonState' cannot be used as a function I keep getting this error and I don't know why.

mcpButtonState is an array, and I would like to change one of its values using a line like this:

mcpButtonState(thisPin) = 0;

(it's inside of a for loop looping trough all my pins).
This is my complete code:

#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h
#include <Wire.h>
#include "Adafruit_MCP23017.h"
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
Adafruit_MCP23017 mcp;

int mcpButtonPins[] = {0,1,2,3,4};
int mcpButtonCount = 5;
int mcpButtonState[5];

int analogButtonPins[] = {0};
int analogButtonCount = 1;
int analogButtonState[1];

int potiPin = A2;
int soundVolume = 15;

void setup() {
  mySoftwareSerial.begin(9600);
  //Serial.begin(115200);
  mcp.begin();
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
    mcp.pinMode(thisPin, INPUT);
    mcp.pullUp(thisPin, HIGH);
    mcpButtonState(thisPin) = 0;
  }
  //ANALOG BUTTON SETUP
}

void loop() {
  int potiValue = analogRead(potiPin);
  int newVolume = (potiValue / 1023 * 30);
  if(newVolume != soundVolume)
  {
    soundVolume = newVolume;
    myDFPlayer.volume(soundVolume);
  }
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
     if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 0)
     {
      mcpButtonState(thisPin) = 1;
      myDFPlayer.play((thisPin + 1));
     }
     else if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 1){}
     else {
      mcpButtonState(thisPin) = 0;
      }
  }
  //ANALOG BUTTON PLAYING
}

Use [] not ():

 if((mcp.digitalRead(thisPin) == 0) && (mcpButtonState[thisPin] == 0))

Note the use of && instead of the word and.


RePaper 2.7" eInk Display with Arduino Due I got a RePaper 2.7' eInk display that unfortunately doesn't support Arduino Mega because of its limited SRAM capacity (8k bytes). I am porting the library to Arduino Due because of its sufficient RAM capacity (96 KB in two banks: 64KB and 32KB).

I am using the thread rePaper - 2.7" Graphic eInk Dev Board Headers  and I've done all the modifications.

Has anyone successfully ported the library to Arduino Due? Also, does anyone have a library for Dynamic Printing for this display?

You're trying to port the library from the Due to the Mega? If the library is large a "port" just isn't going to happen because relatively minor modifications to the code are very unlikely to shrink the size significantly; you'll need a complete rewrite.

My suggestion is to start by studying the data sheet for the device and the code for the existing Due driver to get an idea of how it works. Then sit down and write some sketches for your Mega that make something happen on the display (perhaps just clearing it, turning on and off a few specific pixels, the like) to verify your understanding. Once you've done that, you can start to consider the design of your driver.

Because of the vastly different memory limitations it's likely that your driver will look and work very differently from the Due driver. For example, a 264 x 176 x 1 bit frame buffer would use almost 6K of RAM (most of the RAM in a Mega 2560 and far more than in an Uno), so you're not going to want to have one. I don't know if the Due driver has a frame buffer (I'm just using this as an example of a typical difference you might encounter), but if it does, and that's used for doing certain kinds of things, you'll need to do them in a different way or not do them at all.

This is not a simple project, but it's a great one and will teach you a lot about microcontroller programming!


Why analogue pins affect each other? I have a sensor and it generates an analogue signal.

I am reading all analogue data and sending it to my computer.

uint8_t sensors[] = { A0,A1,A2,A3,A4,A5,A6 };
const int len = sizeof(sensors) / sizeof(sensors[0]);
void loop(void)
{
    for (size_t i = 0; i < len; i++)
    {
        auto sensor = sensors[i];
        int sensorValue = analogRead(sensor);
        // Convert the analogue reading (which goes from 0 - 1023) to a voltage (0 - 5V):
        float voltage = sensorValue * (5.0 / 1023.0);
        char t[100];
        sprintf(t, "%d:%d$\n", sensor, sensorValue);
        uint8_t t1[100];
        //PrintSerial.println(t);
        memcpy(t1, t, 100);
        wifi.send(t1, strlen(t));
    }
    delay(300);
}

I plotted the analogue reading. Why does the graph look like this?

This is to be expected.

The other pins have nothing connected to it, so their voltage is floating.

The Arduino MCU only has a single ADC. To read the different analog pins, it uses a multiplexer to connect the pin you want to read to the single ADC. The ADC inside the MCU have a "sample and hold" capacitor inside it.

To read the voltage at the pin, it will connect the pin, to charge the sample and hold capacitor. It will then disconnect and measure the voltage of the sample and hold capacitor, one bit at a time.

So in your case, by reading the voltage at the connected pin, it will charge the capacitor. It will then read the unconnected pins. But because nothing is connected the sample and hold capacitor will stay at about the same voltage, because the unconnected pin will neither charge, nor discharge it.

Measuring the voltage on the sample and hold capacitor will slightly lower this voltage, so that's why in the graph the lines will be lower than the previous measurement.

PS Also, because all the pins are placed in a breadboard, you'll have some capacitive coupling between the adjacent pins.


How to supply more than 500mA while powered by USB I'm about to build myself a new BrewPi and I have some Arduino power/USB questions.

Something smiliar to a combination of these projects:

https://imgur.com/a/Nval6

https://www.homebrewtalk.com/threads/how-to-brewpi-lcd-add-on.510036/

The device will have a Raspberry Pi Zero W, an Arduino UNO (clone?), a LCD screen with backlight, and some relays and probes. The Pi must be connected to the Arduino via USB. The Arduino will drive the screen and some relays/probes. For simplicity's sake, I would like to power everything from the same regulated 5V power supply, and for ease of wiring I would prefer to power the Pi only and have it power the Arduino via USB, with the Arduino then supplying power to the rest.

My preference:
5V ----> Pi Zero --(USB)--> Arduino --(5V)--> Screen/etc.

However, according to this datasheet the max draw of the screen might exceed 1000mA:
https://www.vishay.com/docs/37314/lcd020n004l.pdf

This obviously exceeds the 500mA limit from the Arduino's 5V pin while being powered via USB. However, a Pi Zero has few safety features and does not limit outgoing current from it's USB port:
https://www.reddit.com/r/raspberry_pi/comments/3zyhuq/pi_zero_usb_power_outputmilliamps/

Given this, is it feasible to short/bypass the Arduino's polyfuse and then draw more than 500ma from the 5V pin of the Arduino without too many problems?

If not, can I 'add' the power supply's 5V to the Arduino's 5V (either from the Pi's 5V pin, or direct from the power supply) at the same time as maintaining the USB connection (which uses the same 5V source)? I'm stretching the limit of my circuit understanding here. If not how should I power the other components?

Would it instead be better to have a 12V supply and power the Arduino directly, then attempt to power everything else from its 5V pin (remembering that there is still a USB connection from the Pi back to the Arduino). What I'd really like to avoid in this situation is having to provide a second 12V->5V conversion.

Any help or advice would be greatly appreciated.

Do not bypass the fuse. Drive your external components directly from the external 5V power supply. Do not pass everything through the Arduino.

You say you have a regulated 5V power supply. Assuming it provides enough current you should use it to drive your external components directly.

You might need to add a filter capacitor near the feed for the Pi/Arduino, to filter out fluctuations in the 5V supply as your high current components switch on and off. You should be able to google "Power supply filter capacitor" to learn more.


Compilling error not highlighting line in code A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.

The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.

See my post about How the IDE organizes things.

The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.

In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.


How do functions outside of void loop work? I am used to Arduino sketches with a void setup() part that runs once, and a void loop() part that keeps looping. What happens when you have void functions outside of the main void loop()? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?

For example in the code below, when will the void receiveData(int byteCount) and the void sendData() functions run?

//I2C_test

//This code demonstrates communication via an I2C bus between a raspberry pi and an arduino.
//When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this
//data to control a motor. After the Arduino has recieved data from the master, it then collects
//data from the external environment via a sensor and sends this data back to the Raspberry pi.

#include <Wire.h>
int number = 0; //Declare variables
int val = 0;

void setup() {
  //Anything between the curly brackets runs once when the arduino is turned on or reset
  pinMode(0, INPUT);
  //Set pin 0 as input and 3 as output
  pinMode(3, OUTPUT);
  Serial.begin(9600);
  //Set the data rate for serial transmission at 9600bps
  Wire.begin(0x04);
  //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address
  Wire.onReceive(receiveData);
  //Define callbacks for i2c communication
  Wire.onRequest(sendData);
}

void loop() {
  //The code between the curly brackets keeps repeating
  delay(100);
}

void receiveData(int byteCount) {
  while(Wire.available()) {
    number = Wire.read();
    //Set the variable "number" to the data sent by the master
    analogWrite(3, number);
    //Write this number to pin 3 (PWM). This controls the motor speed
  }
  val = analogRead(0);
  //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023
}

void sendData() {
  Wire.write(val);
  //Send the data read from the sensor to the master.
}

The setup() and loop() functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.

Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within setup() or loop()), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)

For example, pinMode() is a function just like any other. It only runs when you actually put something like pinMode(3, INPUT) in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).

The example code you've posted is quite interesting. Look at these lines in setup():

Wire.onReceive(receiveData);
Wire.onRequest(sendData);

These lines are telling the Wire object to call receiveData() and sendData() in response to I2C events. It does this by passing function pointers which are stored and used by Wire.

I'd recommend searching for information about C/C++ function pointers online if you want to learn more about this. You may also be interested to explore Arduino's attachInterrupt() function.


Function for converting milliseconds to minutes? I'm playing around with a Neopixel strip and want to be able to enter the amount of minutes I want an LED to do something rather than in milli seconds. So for example,

void loop() {

colorWipe(strip.Color(0, 0, 255), 50);
delay(sConversion(5));

colorWipe(strip.Color(0, 0, 0), 50);
delay(sConversion(5));

In my mind this should then delay the code by 5 minutes instead of doing

void loop() {
colorWipe(strip.Color(0, 0, 255), 50);

delay(300000);

The function I wrote is

sConversion(int minutes) {
    int milli = minutes * 60000;

    return milli
};

When I write this same function in JS it returns the correct value, 300000. But when I run it in the Arduino IDE the blue light never changes.

I have this function outside my void loop() and void setup(). Is that the correct place to put it? I have no errors returned.

Full code sample

void setup() {

strip.begin();
strip.show();

}

int sConversion(int minutes) {
    int milli = minutes * 60000;

return milli;
}

void loop() {

colorWipe(strip.Color(0, 0, 255), 50); // Blue
delay(sConversion(1));

colorWipe(strip.Color(102, 204, 0), 50); // Green
delay(300000);
}

void colorWipe(uint32_t c, uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
    };
};

Is this the reason?

  No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt.

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

Your sConversion returns an int as argument. You need to declare it as unsigned long.

This is what you are lookin for:

unsigned long conv(int x) {
  return x * 600000L;
}


Is new without a delete acceptable? I know it is not a good practice to use the new command to dynamically create data, however, if I would never use the delete, would it result in memory gaps/other problems?

Background

The reason I need to create instances dynamically, is that I want to test my application first on a PC. And I want for several classes to have more properties for the PC version than for the Arduino version (for example, to store names, or information for the PC GUI to display). The PC version classes will be inherited from the Arduino (real) classes, but with added properties.

In some classes I need to build up a list, and I cannot use a type with hardcoded values to fill an array.

Example:

I have a LightSetup class that has a list of Pars (which are LED lights):

class LightSetup
{
protected:
    Par* _pars[NR_OF_PARS];

Par is the Arduino/real version, to fill in these I need:

LightSetup::LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        _pars[n] = new Par(1 + 8 * n);
    }
}

In the PC version, instead of new Par, I use new TestPar.
And in the header I cannot define it without a pointer like this:

    Par _pars[NR_OF_PARS];

Otherwise it cannot contain TestPar instances.

Sure. Using new or malloc to set things up initially is really no different to static allocations. There is nothing inherently bad with using malloc or new, only in using it repeatedly with free or delete.

Allocating a block of heap memory and keeping it allocated for the rest of eternity does not cause heap fragmentation. It's only repeated allocation and deallocation of variable sizes (such as String causes) that start to create problems. Allocating at the start of your program and leaving it allocated, as long as you don't allocate too much, of course, is not a problem.


Can I use an ESP8266 as a replacement for an original Arduino? I want to learn Arduino, but I'd like to use the ESP8266 as it has built in wifi. I understand that I can use the Arduino IDE for this board.

However, what about books and resources out there? Are these two boards so similar that I can follow original Arduino examples? I'm primarily thinking in terms of connectivity to, say, sensors.

I'm a beginner at this and will not be able to figure out how to bridge compatibility gaps.

Yes, No and Maybe is the best answer :)

Assuming that you want to replace a Arduino Uno board with an ESP8266 based board.  Your best choice at the moment would be a Wemos D1.  It has the same form factor as the UNO, but it has less pins, 9 digital and 1 analog.

If you are not bothered about the form factor, you could also try a Node-LUA, or a Wemos D1 Mini.  If you have steady hands you could try just using the heart of these three boards directly, which is usually called an ESP8266-12E, but it has 1mm pitch and no voltage regulation.

There are a lot of sites around that have tutorials on using ESPs.  They are mostly interchangeable with Arduino boards from a software perspective, they have more memory and a faster clock speed.

The biggest difference between an Arduino based board and an ESP board is most Arduino use 5v and most ESP based boards use 3.3v.  Make sure you read the datasheet before you hook up you sensors.

There is an ESP-32 as well.  This is not interchangeable with an Arduino Uno at the moment.


Connecting esp8266 using Arduino I am trying to connect to esp8266 using Arduino UNO. There are various things on the internet having mixed information and hence I am seeking some clarity.

I followed these instructions, but could not get to connect to ESP8266 using AT command. http://cordobo.com/2300-flash-esp8266-01-with-arduino-uno/

I have following questions:

Can I connect ESP8266 directly to Tx/Rx without voltage divider or level shifter? I also suspect that the voltage divider connections are wrong. As per my understanding, the Tx from Arduino should be divided, and the divider output should be connected to ESP8266.
When I connected the shield as described, the shield gets hot. Is there any way to conclude if the shield is damaged or not?
When I connect the device using voltage divider the blue LED on the shield also lights up. Without divider, it does not light up. What is the significance of the blue LED?

Hardware

ESP8266-01 pinout

Circuit using voltage divider

Circuit without voltage divider

There are a number of issues with the tutorial you've listed there.

Firstly, a voltage divider is very highly recommended as the ESP8266 cannot handle more than 3.3V, however, the connections for the voltage divider in the tutorial you linked to are the wrong way round (as you suspected).

Secondly, you cannot power the ESP8266 directly from the Arduino, as the power requirements are higher than the Arduino's on board 3.3V regulator. A separate power supply or regulator is recommended. This might be cause of it getting hot (the onboard regulator maybe - but I can't be sure as there is not enough information from your initial post as to exactly what is getting hot).

There are 2 LED's on the ESP8266 shield (the one used in the tutorial you've linked to) one is power and the blue one is wifi communication.

The other potential issue with the tutorial you've linked to is that they have used Arduino pins 0 and 1 to connect to the ESP8266 - while this will work, the problem is that the Arduino uses pins 0 and 1 to communicate over USB with a computer, which means that in in that configuration you cannot use Serial monitor to send/receive data.


Press the Windows key using "keyboard.press();" Is it possible to allow an Arduino Leonardo to simulate pressing the Windows key using the keyboard.press(......); command?

If so, what is the required value?

They Keyboard.press() command accept modifiers per the documentation. You may need to do multiple press() commands before releasing.

For example, if you want to launch File Explorer you could use:

Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('e');
Keyboard.releaseAll();

This is equivalent to shortcut keys Win + E.

The modifier GUI is what stands in for the "command key" which is the Windows Logo on a PC or clover (⌘) on a Mac.

I don't have any restriction on the higher value on my board (Pro Micro), as indicated by @frarugi87.


ESP8266 module cutting connection with PC via USB My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...

At which pins you connected the ESP8266?
The pins pin 0 (RX) an 1 (TX) are connectet internaly to the FTDI USB-to-TTL Serial chip.
If you using Serial.begin() to communicate with the ESP8266, you can't communicate with the pc at the same time.
Use SoftwareSerial to communicate with the ESP8266 an Serial to PC.

It is also recommed to feed the ESP8266 with an external 3.3V power supply and stabilize with an capacitor. This could  produces the sounds of ejecting and inserting a USB.


Store 3-dimensional char array in program memory with PROGMEM I'm running a sketch whith a quite big, constant three dimensional char array (or simply, a table of strings). As this takes lots of RAM I'd like to store it in programm memory in order to keep the RAM free. This is the Sketch I'd like to run (my first idea):

const char *rules [16][5] PROGMEM ={
 {"1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr", "sed di7am nonumy 8eirmod tempor invidunt"},
 {"2Lorem ipsum dolor sit amet, consetetur sadipscing2 elitr", "sed diam nonumy 9eirmod tempo5r invidunt"},
 {"3Lorem ipsum dolor sit amet, consetetur sadipscing 4elitr", "sed0 diam nonumy 1eirmod tempor invidunt"},
 {"4Lorem ipsum dolor sit amet, consetetur sadips3cing elitr", "sed diam nonumy 2eirmod tempor in5vidunt"},
 {"5Lorem ipsum dolor sit amet, consetetur 3sadipscing elitr", "sed 7diam nonumy 3eirmod tempor invidunt"},
 {"6Lorem ipsum dolor sit amet, conset9etur sadipscing elitr", "sed diam n8onumy 4eirmod tempor invidunt"},
 {"7Lorem ipsum dolor sit amet, consetetur sadipsc3ing elitr", "sed diam nonumy 5eirmod tempor inv4idunt"},
};

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  for(int i = 0; i < 16; i++){
    for(int j = 0; j < 5; j++){
     Serial.println(rules[i][j]);
    }
  }
}

void loop() {
}

But this fails with the following error:

variable 'rules' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

According to Arduino's FAQ this can be solved by changing the array's declaration to

const char * const rules [16][5] PROGMEM ={

The sketch compiles now without errors, but the global variables (here only the array) still need lots of RAM:

Sketch uses 2484 bytes (7%) of program storage space. Maximum is 32256 bytes.
Global variables use 880 bytes (42%) of dynamic memory, leaving 1168 bytes for local variables. Maximum is 2048 bytes.

I'm not sure what causes this, but is it possible that only the pointers to the strings are stored in program memory, while the strings theirselves are still copied to RAM?

How do I put the whole arary in programm memory?

There has already been a question like this on StackOverflow, but the answer recommends using prog_chars, which are according to the AVR documentation deprecated.

Here you have:

const char * const rules [16][5] PROGMEM ={

One const refers to the char* part. It means the pointer value doesn't change.

The other const refers to what it is pointed by. It means the thing this pointer points doesn't change (but the pointer itself can change).

In your sketch the thing that get put into PROGMEM is the pointer array; the texts themselves are still in RAM. Have a look at PROGMEM page and  study this example:

const char string_0[] PROGMEM = "String 0";   // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";

// Then set up a table to refer to your strings.

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

You need to declare each string by itself, and later put them in an array.

As you can see, pointer are inescapable.

Edit: The F() Macro

Here is a proof of concept of how to manage an array of string (lowercase "s") and strings constants in PROGMEM:

const char uno[] PROGMEM = "1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char dos[] PROGMEM = "2Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char tre[] PROGMEM = "3Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cua[] PROGMEM = "4Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cin[] PROGMEM = "5Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";

const char * const rules [3][2] = {
 {uno, dos},
 {tre, cua},
 {cua, cin}
};

void setup() {
  Serial.begin(115200);
  Serial.println(F("PROGMEM string test"));
  Serial.println(F("-------------------"));
  for(int i = 0; i < 3; i++){
    for(int j = 0; j < 2; j++){
      Serial.print(i); Serial.print(" "); Serial.print(j); Serial.print(" ");
     Serial.println((const __FlashStringHelper *) rules[i][j]);
    }
  }
}

void loop() {
}

Use the F() macro to put constant strings in PROGMEM. Otherwise, the strings will live in RAM. Are running short of RAM? Put the F() macro around those pesky strings and send them out of your RAM.


Arduino minimal power usage I know there is a lot on this subject on the net but i cant seem to be able to join the dots together.
I am trying to make sensor system than can run for as long as possible if not indefinitely using an Arduino, and also to do so very cheaply. I have a £1 Arduino Nano clone that is running with sensor and alarm fine, but currently its runs off USB power from PC.

I have followed this guide to minimize power usage code side: https://www.openhomeautomation.net/arduino-battery/

And I have read that the Vin pin needs at least 7 volts to work properly, so 2 volts would be wasted in heat making a 5V level.

I have a 3.7V lithium cell 4300mAh so I thought I would need a step up boost module.

But it looks like the Nano can run using 3V. But the 3.3V rail is apparently made for external sensors, assuming I want a mixture of cheap/simple and high efficiency. Can i just hook a 3.7 lipo into the 5V rail of the Nano and a 5V solar panel (with diode) up to same point? Will this kill my Nano?
If not, is it worth stepping the 3.7V down to the minimum the Nano can run with?

Underclocking is not an issue, it essentially wakes up every hour reads 5 sensors and if all is well (99% of the time) goes back to sleep for an hour.
Linear voltage regulators seem to burn the excess voltage as heat. And then what will happen when the battery dies off and is no longer 3.7 volts? And if my solar panel is around 5V in good light, if its partly shaded and only has 3.5 volts for example it would not charge my lipo to 100% capacity. Should I step up DC/DC boost the panel voltage to charge my cell.

Guidance please.

Arduinos are for rapidly getting something going without having to know much about the underlying electronics and microcontroller.  As a result, some design tradeoffs were made for you, generally optimized for development simplicity.

You now have a different primary concern, which is low power consumption.  If that is truly important, then you have to design the system with that goal up front.  This means starting with the bare microcontroller, designing the electronics around it carefully to minimize power, and designing the firmware architecture to minimize high-power cycles and maximize sleep time.

You are asking where to strap the big engine on a Honda Civic to make a high performance racing car.  You can make a Civic higher performance, but to get really high performance you have to start with that goal from the beginning.


RF sniffer with Arduino Hello programmers out in the world.
I am doing a capstone project for an RF sniffer to capture RF signals from Key fobs within an OEM manufacturing plant. I want to be able to decode this RF signal to show me what the battery state of the key fob is. I have the protocol, so I know what data I should be receiving. However, I have tried many libraries on the Arduino UNO and none have worked.
This Key fob specs are FSK modulation. Frequency of 433 Mhz, Bit rate -> 9.6Kbit/s, baud rate of 19.2Kbaud/s and coding is manchester.
Any help would be greatly appreciated.

I actaully found this this week that I was suing ASK RF receiver module, when I needed FSK.
I have used RC Switch, and no luck, along with Radio head.
However as mentioned the key fob will not work with ASK. I am trying to find a library for FSK but no luck as of now.
-Pete


A digital I/O pin as ground I want an I/O pin to return current in a circuit, similarly to the function of ground.

Which of these will achieve what I require?

pinMode(pinnumber, OUTPUT)
digitalWrite(pinnumber, LOW)

or

pinMode(pinnumber, input)

Your first snippet is the correct solution.

pinMode(pinnumber,OUTPUT)
digitalWrite(pinnumber,LOW)

Be careful though, you can only sink up to 6mA or 9mA per pin (as per the documentation ["Input and Output" section], I never tried more). If you need more current, use a transistor (this looks like a good example, you just need to invert the output pin to HIGH).

When the pin is configured as input it is supposed to be high impedance, not what you want.


Help with 1-Wire to I2C translate Please, someone.

I want to use a temperature sensor (DS18B20) in an I2C only shield (Tentacle Mini), but this sensor is One Wire only. Can I write an I2C code to change the 1-Wire to I2C for this sensor? I think to use the (DS2482-800) bridge, but I don't know how to do...

Thanks!

As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the  DS28E17, a module that could translate the the 2 methods of communication. It should work but I havent tested it.

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.

Hope I helped you.


Use JYETech 2.4 Inch LCD Display Screen Module with Arduino? I have this JYETech 2.4 Inch LCD Display Screen Module that I would like to use for a project I have in mind, however, I'm not sure how to wire it up with my Arudino Mega. Here is the datasheet for the display. I have also attached a picture of the display below. The display is meant to work with a DIY oscilloscope but according to the manufacturer and other forum posts, it can be used as a display with other projects as well.

Pictures of the display

That display is an ILI9341 based one. On the DSO138 it connects the data pins D0-D7 to PORTB of the STM32.

You need to connect those 8 pins to 8 pins on the Arduino, along with the RS (Register Select) and CS (Chip Select) pins. The RD pin can be connected to 3.3V and the WR pin to GND, since you only really want to write to the screen (if you do want to read from the screen then you will want to connect RD and WR to two IO pins as well). Reset can be connected to a GPIO or to 3.3V, depending on if you want to do a hard reset at any point or not.

LED-A can connect to 5V, and each of the LED-K* pins should connect to ground through a resistor each. The size of the resistor will set the backlight brightness (try 100Ω to start with).

Then it's just a matter of finding a library that works with the ILI9341 in 8-bit parallel mode (u8glib maybe? I don't know, I never use Arduino to drive a TFT).

Note that since this is a 3.3V device you should really use a level shifter for all the digital signals.


How do I calculate sampling rate of external ADC? I am wondering if someone could explain this to me.

I want to calculate sampling rate of external ADC.
I am using ADS8320 which has max sampling rate of 100kHz, with Arduino MEGA 2560.
SPI divider is set to 128, which makes SPI frequency 125kHz.
Baud rate is 115200 (I am not sure if this is important).

Thanks a lot!

Easy.

Based on your set up, figure out the spi speed.
Take a look at the adc datasheet, figure out it's frame of transmission . Aka how many pulses per frame / sampling.
The product of the numbers in 1 and 2 gives you the minimum time per frame. The inverse of it is the maximum transmission in your application. That speed is cap by the devices own max sampling rate (100ksps).
Your actual sampling rate will depend on your specific application but it should not go above the number obtained in 3.
You may need to factor in other timing requirements as well so read the datasheet carefully. But the gist is the same.


Dimmer.h issues with ATmega 128 I am using a ZCD circuit controlling a TRIAC. Now I am using Dimmer library for this purpose. It works fine with ATMega 328 but whenever I try to upload the code in ATMega 128 using Arduino IDE this error pops up:

Arduino: 1.8.4 (Windows 10), Board: "ATmega128, 2.7v, Disabled (default), 16 MHz external"

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp: In member function 'void Dimmer::begin(uint8_t, bool)':

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:15:20: error: 'TCCR2A' was not declared in this scope

 #define _TCCRxA(X) TCCR ## X ## A

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:16:19: note: in expansion of macro '_TCCRxA'

 #define TCCRxA(X) _TCCRxA(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:157:5: note: in expansion of macro 'TCCRxA'

     TCCRxA(DIMMER_TIMER) = TCCRxA_VALUE;         // Timer config byte A

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:17:20: error: 'TCCR2B' was not declared in this scope

 #define _TCCRxB(X) TCCR ## X ## B

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:18:19: note: in expansion of macro '_TCCRxB'

 #define TCCRxB(X) _TCCRxB(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:158:5: note: in expansion of macro 'TCCRxB'

     TCCRxB(DIMMER_TIMER) = TCCRxB_VALUE;         // Timer config byte B

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:19:20: error: 'TIMSK2' was not declared in this scope

 #define _TIMSKx(X) TIMSK ## X

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:20:19: note: in expansion of macro '_TIMSKx'

 #define TIMSKx(X) _TIMSKx(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:159:5: note: in expansion of macro 'TIMSKx'

     TIMSKx(DIMMER_TIMER) = 0x02;                 // Timer Compare Match Interrupt Enable

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:21:19: error: 'OCR2A' was not declared in this scope

 #define _OCRxA(X) OCR ## X ## A

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:22:18: note: in expansion of macro '_OCRxA'

 #define OCRxA(X) _OCRxA(X)

                  ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:160:5: note: in expansion of macro 'OCRxA'

     OCRxA(DIMMER_TIMER) = 100 * 60 / acFreq - 1; // Compare value (frequency adjusted)

     ^

exit status 1
Error compiling for board ATmega128.

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

Any idea what is the issue ?

The Dimmer library doesn't support Atmega128/164/16/32. It has

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define DIMMER_TIMER 4
#elif defined(__AVR_ATmega32U4__)
#define DIMMER_TIMER 3
#else
#define DIMMER_TIMER 2
#endif

For the Atmega128/164/16/32 it will use timer 2. The main errors are:

'OCR2A' was not declared in this scope
'TCCR2A' was not declared in this scope
'TCCR2B' was not declared in this scope
'TIMSK2' was not declared in this scope

Possible solution:

You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change TIMSKx(DIMMER_TIMER) = 0x02 perhaps to bitSet(ETIMSK, 3);. Check the datasheet. I can't test it, I don't have the chip.


Arduino UNO with LMT86LP temperature sensor I am trying to use the Arduino Uno with the LMT86LP temperature sensor, but I am getting strange output voltages from the sensor.

I have the pins (from left to right, flat side facing forward) as VDD, OUT, and GND. VDD is connected to 5V, GND to GND, and Vout to A0 (analog pin 0). The readings from the Arduino are consistently around 360 mV but should be somewhere around 1800 mV as I measured the output of the sensor using a multimeter and got a constant 1.8 V.

Right now the code is very simple. I am just doing analogRead() and printing to the Serial Monitor.

The result from analogRead() is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.

1.8V/5V⋅1024=368.64


Very bright cursos positions As you may can I see on the picture. I try to display the word "goodbye". Yet the problem is that the cursor positions are to bright. I hooked up a 10k ohm potmeter to the Anode. To change the backlight. Is there a way to make the cursos positions less visible?

Kind Regards,

Q

issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).

Look at the conversation between me and Majenko to see the realisation.


Arduino Uno Rx/Tx + Arduino Serial I was wondering if I can use the Rx and Tx Hardware on the Arduino Uno and also add another Rx/Tx pins using SoftwareSerial at the same time ? cause I need two to communicate with two motor Controllers (Roboclaw controller)
Thx

Yes, you can.  That's the purpose of the SoftwareSerial - to allow you to complement the hardware TX/RX with other pins defined by software.

One thing to note with SoftwareSerial - it's half duplex. It can either send or receive, it can't receive while it's sending.