Converting float to String How can I convert a float value into a String object without implementing any library?

I'd like to avoid using char array.

If you want to do it manually, rather than using the standard tools (dtostrf() for example) then you need to think mathematically.

A floating point number is made up of two distinct parts - the integer part and the decimal part.

For instance the number 123.4567 is made up of the integer part 123 and the decimal part 4567.  Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output.  In this case, though, it isn't.

So what to do?  Simple: keep dividing the number by 10 until it is just one digit.  But be sure to count the number of times you divide by 10.  So the example above would end up as 1.234567 with a divide count of 2.  This is the same as the scientific representation, 1.234567×10².

So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number.  So you end up with "1" and 0.234567 and a count of 2.

Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1.  Grab the integer portion and add it to your string, then remove it from your number.

Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.

You now just keep repeating the same process again and again until the absolute value of the count equals the number of decimal places you want to print.

For negative numbers you should start by placing a "-" in your string, then taking the absolute value of the number (the number as a positive).

Or you just use the standard library function dtostrf().


How is IF( object ) evaluated? Follows from SD card example sketch The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following if() statement is evaluated:

File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

There must be some implicit conversion on dataFile which depends on whether or not SD.open("myFile.txt") was successful. I would like to understand how this implicit conversion occurs. Which property of the File object determines if the if() statement evaulates true or false?

There is an operator bool which does the test:

File::operator bool() {
  if (_file)
    return  _file->isOpen();
  return false;
}

When used inside an if the compiler invokes the operator bool() which does the test you see above.


Help in "An error occurred while uploading the sketch" Trying to test THIS. Got following error:

esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 9600
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 356000 bytes from C:\Users\PRAMIT~1\AppData\Local\Temp\arduino_build_521093/testPersWiFiManager.ino.bin to flash at 0x00000000
    erasing flash
    size: 056ea0 address: 000000
    first_sector_index: 0
    total_sector_count: 87
    head_sector_count: 16
    adjusted_sector_count: 71
    erase_size: 047000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 22% ]
................................................................................ [ 45% ]
................................................................................ [ 68% ]
.......................An error occurred while uploading the sketch

All libraries are included, no compile error.
Steps followed:
1st uploaded the data using Tools>ESP8266 Sketch data upload.
Then Sketch>upload

After failing this, I tried a basic example similar to THIS. This uploaded successfully. The same configuration is used for both scenarios.

What am I missing? I am getting no clue.

Settings:

The upload to esp8266 with esptool used in IDE doesn't work good on slow baudrate. It fails for larger sketches. You can upload to NodeMcu at 921600 baud.


How Can I convert my arduino code to C/C++ embedded code For example I have an code for arduino but I want to change it to embedded C to create more professional project with different hardware. is there any tutorial? I know the logic and the most of the codes are the same. I just wanna know about libraries or pin definitions for LCD and buttons.

Arduinos use a standard C++ compiler. The supposed "Arduino Language" doesn't exist; it is C++. Except that the Arduino IDE will permit you some shortcuts that the compiler doesn't. The two biggies are:

The IDE will notice that your are trying to use libraries (ones it recognizes, anyway) and insert the necessary #include <SOMELIBRARY.H>, if you didn't do it.
The IDE will notice when you make forward reference to a function not yet defined nor declared, and provide the necessary forward declaration.

But if you manage these for yourself, as you would have to in any other C++ environment, your code structure will be portable.

The remaining source of incompatibility is hardware dependence. Writing embedded systems software is almost always hardware dependent. It has to be dependent on the external hardware, and quite likely is dependent on specifics of the MCU. The latter dependencies can usually be written around. Function calls or direct references to the processor's I/O registers, for example, which, on another processor, will map differently, maybe even to memory addresses instead of to registers at all.

Another processor will very likely have an entirely different set of pins with different characteristics and capabilities from the original one. Libraries to drive external hardware will likely have been designed for a given processor or processor-family and may not map gracefully to another.

If processor independence is a design-goal of the project, then you'd probably define a hypothetical set of features that you'd expect all processors to share, and hand code for anything outside of that basic set. If you wanted to take advantage of certain features if they were available on a given processors, then, in addition to the hand-coded features you wish to have, you'd also provide conditionally compiled, optimized-for-the-processor code that you could enable when you compile for that processor, and disable for all others.


Peer to Peer using Ethernet Module I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.

I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)

EDIT:
I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

You will need a crossover cable to connect two Ethernet shields peer to peer.

Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.


Pin Mappings from Arduino Metro M4 Express Board to SAMD51 After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?

I'm answering my own question below, but perhaps someone knows of a better table.

Edit: Since writing my answer, I found this Google Sheet that does a much better job.

Arduino has some schematics on their website. Here's an image I used to build the following list below.

There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description

Analog

A0  3   PA02/EINT2/AIN0/VOUT0
A1  14  PA05/I5/AIN5/VOUT1/SERCOM0.1
A2  15  PA06/I6/VREFC/AIN6/SERCOM0.2
A3  13  PA04/I4/VREFB/AIN4/SERCOM0.0
A4  11  PB08/I8/AIN2/SERCOM4.0
A5  12  PB09/I9/AIN3/SERCOM4.1

Digital

D0  44  PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
D1  43  PA22/I2C/116/SERCOM3.0+5.1/I2SDI
D2  40  PB17/SERCOM5.1/I2SMCK0
D3  39  PB16/I0/SERCOM5.0/I2SCK0
D4  26  PB13/I13/SERCOM4.1/I2SMCK1
D5  27  PB14/I14/SERCOM4.2/PCC8
D6  28  PB15/I15/SERCOM4.3/PCC9
D7  25  PB12/I12/SERCOM4.0/I2SCK1
D8  42  PA21/I5/SERCOM3+5.3/I2SDO
D9  41  PA20/I4/SERCOM3+5.2/I2SFS0
D10 37  PA18/I2/SERCOM1+3.2
D11 38  PA19/I3/SERCOM1+3.3
D12 36  PA17/I2C/I1/SERCOM1.1+3.0
D13 35  PA16/I2C/I0/SERCOM1.0+3.1
GND
AREF    4   PA03/I3/VREFA/AIN1
SDA 63  PB02/I2/AIN14/SERCOM5.0
SCL 64  PB03/I3/AIN15/SERCOM5.1

SPI

MOSI    29  PA12/I12/I2C/SERCOM2.0+4.1
SCK 30  PA13/I13/I2C/SERCOM2.1+4.0
MISO    31  PA14/I14/SERCOM2+4.2


SAMD21 Programming with Atmel ICE Fail to Write I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:

Timestamp:      2017-04-20 22:03:32.563
Severity:       ERROR
ComponentId:    20100
StatusCode:     131103
ModuleName:     TCF command: Modules:writeToMemory failed.

Failed to write segment at 0x0 to target for memorytype

I have searched the internet for hours, finding no solution to this problem.

Whats is the fuse setting of NVMCTRL_BOOTPROT?

it should be:

NVMCTRL_BOOTPROT = 0x07

which will set your memory location to 0x00 (no bootloader).

NVMCTRL_BOOTPROT sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.


Arduino ModBus RTU master communication with Power Meter problem i have an arduino UNO with RS485 module.

I have made this connection:

And i have an problem with communication of this module with power meter
"InePro PRO-1Mod"
(datasheet) over ModBus protocol. I want for example read an L1 Voltage value, which i know from the manual (page 24 & 25) that this value is stored in "read holding register" with adrress 5002. I should communicate with these paramaters:

Baud rate 9600
8 data bits
even parity
1 stop bit

There is also mention about 120 ohms resistor placed by the power meter (but it is 15cm long cable, and even with the resistor there is no change)

I have tried using many of ModBus libraries and for now none of them doesn't work. I have tried "Modbus-Master-Slave-for-Arduino" , "ModbusMaster and now at last i am using this "simple-modbus".

I think that with that simple modbus library i went far as i can, but it is still doesn't working, but i see on the display of power meter that there is some try to communication (i see a black dot which shows modbus communication)
but i don't receive any useful data.

I am using this code:

    #include <SimpleModbusMaster.h>
#include <AltSoftSerial.h>

#define TxEnablePin 2                    // RS485 modbus direction control pin:
#define baud 9600                           // modbus port speed:
#define timeout 1000                        // modbus timeout in mSec:
#define polling 500                         // modbus scan rate in mSec:
#define retry_count 15

#define TOTAL_NO_OF_REGISTERS 1// number of registers to poll for:

AltSoftSerial altSerial;

enum
{
 PACKET1,
 TOTAL_NO_OF_PACKETS                       // leave this last entry
};

Packet packets[TOTAL_NO_OF_PACKETS];        // array of Packets to be configured

//struct packetPointer packet1 = &packets[PACKET1];
unsigned int regs[TOTAL_NO_OF_REGISTERS];   // master register array
long previousMillis = 0;
long interval = 1200;
unsigned long currentMillis;

void setup() {
 Serial.begin(9600);
 altSerial.begin(9600);
 altSerial.println("Hello World");
 modbus_construct(&packets[PACKET1], 5, READ_HOLDING_REGISTERS, 5000, 2, 0);  //initialize packet
 modbus_configure(&Serial, baud, SERIAL_8E1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
}

void loop() {
 modbus_update();

 float Power;
 unsigned long temp = (unsigned long)regs[1] << 16 | regs[0];
 Power = *(float*)&temp;

  currentMillis = millis();
 if (currentMillis - previousMillis >= interval)
 {
   altSerial.print("Exception errors: ");
   altSerial.println(packets[PACKET1].exception_errors);

   altSerial.print("Failed requests: ");
   altSerial.println(packets[PACKET1].failed_requests);

   altSerial.print("Successful requests: ");
   altSerial.println(packets[PACKET1].successful_requests);
   altSerial.print("Low byte: ");
   altSerial.println(regs[0]);
   altSerial.print("High byte: ");
   altSerial.println(regs[1]);
   altSerial.print("Power ");
   altSerial.println(Power);
   altSerial.println("----------");

   previousMillis = currentMillis;
 }

}

And i have got only this output in the pc (its repeating of course):

----------
Exception errors: 0
Failed requests: 5
Successful requests: 0
Low byte: 0
High byte: 260
Power 0.00
----------

Altserial library i am using together with USB2TTL convertor on pins 8 & 9,
to see output.

I should mention that there is only A and B screw terminals on power meter, so i have no option to make common ground connection. I also using an 15cm twisted pair cable UTP.

Can someone help me to make it work ?
I have tried to change adrress of holding register to 0x5000 or 5002, tried changing number of registers.

I have tried to connect rs485 module with USB2TTL to pc and run software called "qModMaster" and it works, but with arduino it doesn't work.

Slave ID (power meter) is 5.

Thank you, for your help.

I have made it. Now it is working. I only checks A & B cables (tried a new one) and change address of register from 5000 to 0x5000 and now it works. I thought that this library already give 0x before address, because i didn't see it anywhere with 0x before.
An advice for people with the same problems:
Most of the devices which is using RS485 and ModBus protocol (and have an some kind of display) shows an communication (over 485 & modbus) on display by some kind of mark, for example in my case it was an "dot" which blinks when there's an communication. When this mark is shown, it is sign of that the communication settings is right, so data, parity bit, stop bit & baudrate is OK (data has successfully reached the dest. device).
After that, these devices send you an error message back on its line. So if you have problems with getting data, you should send your message (ask) from the arduino to that device, over an Transmit pin from arduino (of course trough an converter, for example max485) and the Receiving pin (side) connect to your PC through again some kind of converter from UART to USB. (Warning: you should have the same ground potential, so wire all grounds together)
Install some software to communication for modBus on PC (i am using this soft: https://www.simplymodbus.ca/ | you can use demo ) After that let arduino sent an message and receive it by PC. (in simplymodbus look at the "response") read that code and look to the manual for the device you using, where there should be an description of error codes, if not look at this doc.: http://www.simplymodbus.ca/exceptions.htm or THIS).After that you will have an better look on what is going on and where there is a problem.


I think I have a bad batch of TPIC6B595 I want drive a large number of LEDS from an Arduino Pro Mini using a number of TPIC6B595. I purchased these on ebay, perhaps a mistake.
Initially I connected two TPIC6B595 as I would connect 74HC595 (with the exception of taking account of how the open drain outputs work) to the SPI pins of an Arduino Mega (my test bench system) and tried sending an alternating bit pattern to the LEDs. No alternating LEDs. I checked SRCLR was Vcc and OE (G) was Gnd. I poked about with my scope (Rigol DS1102D)  and SRCK, RCK and SERIN looked as expected. Suspiciously SEROUT (pin 18) of the first chip was permanently LOW. Note that this is all on a breadboard.
I have used the 74HC595 now many times and from time to time I have made stupid mistakes in wiring/software. These usually stand out on the scope like a sore toe. Not this time.
So I decided to simplify it all and clock some data into a single TPIC6B595 using a simple non-SPI sketch and see if anything comes out of the SEROUT.
Here are the connections to the TPIC6B595 and to the Mega:
1 Not connected,  20  Not connected,
2 Vcc             19  Ground,
3 Arduino pin 12  18  Not connected (except to scope when tested),
4 Not connected   17  Not connected,
5 Not connected   16  Not connected,
6 Not connected   15  Not connected,
7 Not connected   14  Not connected,
8 Vcc             13  Arduino pin 11,
9 Ground          12 Ground (See note 1),
10 Ground         11  Ground.

The chip is bypassed by a 1uF electro across pins 2 and 10. Not ideal but the clock rates are low and it isn't unreliable, it just doesn't work at all.
Note 1: I am not trying to test the transfer between the Shift Register and the output D flip-flops so RCK should be irrelevant. I just want to see data going in to SER IN , coming out on SER OUT.
Here's the Arduino code. It generates a slow clock and an alternating data bit every few clock cycles:
const int ser_clk = 11; // blue
const int ser_in  = 12; // white
byte data, count;

void setup()
{
  pinMode(ser_clk, OUTPUT);
  pinMode(ser_in,OUTPUT);

  digitalWrite(ser_clk, LOW);
  digitalWrite(ser_in, LOW);

  count = data = 0;
}

void loop()
{
  digitalWrite(ser_clk, HIGH);
  delay(1);
  digitalWrite(ser_clk, LOW);
  delay(1);

  count++;
  if (count >= 3)
     {
       count = 0;
       if (data == 0)
          {
            data = 1;
            digitalWrite(ser_in, HIGH);
          }
       else
          {
            data = 0;
            digitalWrite(ser_in, LOW);
          }
     }
}

Here's a screenshot of the wave-forms (photo of scope - sorry can't make UltraScope work):

The cyan trace is the "clock" from pin 11 of the Arduino feeding pin 13 (SRCLK) of the TPIC6B595. The yellow trace is the data from pin 12 of the Arduino feeding pin3 (SER IN) of the TPIC6B595. I am only looking to get the same data pattern out of SEROUT, pin 18 of the TPIC6B595 and this should do it. The clock is as slow as a wet week (see cursor) and even if I have bad set up and hold times and the wrong transitions the data is held for enough cycles for something to make it through surely?? Pin 18 is persistently and forever low. No screenshot - seems to be no point.
I bought several of these TPIC6B595. Tried 3 so far. All the same. Now I might have killed them with static. I am not using wrist straps, but I also don't believe I could have killed 3 of them.
As improbable as that is I think they are dead or duds, or is there something else wrong that is so obvious I cannot see it?
Regards, Fred.

Thanks to all those who responded. I have a double embarrassment here as I have the answer. Firstly if you can answer your own question there is an argument it should never have been posted, more thought needed first. Sorry everyone. Secondly when the cause is ignoring well known good practice then it is even worse.

So when tying a pin to Vcc (in this case SRCLR) it is known bad practice to hard couple it to Vcc. A pull-up resistor is a much better method. In this case suitable pull-ups were in the next room and I could not be bothered so I just jumpered SRCLR to Vcc. After I had written the post I was staring at the breadboard and thought - I should not have really done that replaced the jumper with a 10K pullup to Vcc. Instantly the SEROUT pin of the TPIC6B595 came to life as it should have. Now I have taken this short-cut before and gotten away with it. But it seems not this time.

Subsequently I have a one chip version of the alternating LEDS running with the SPI interface.

As to the suggestion by dannyf about the datasheet, there is no doubt the datasheet is a good place place to go. Prior to developing my test sketch as per my original post I consulted the datasheet and if you look in Section 8, page 11 of the TI datasheet revised June 2015 there is a Functional Block Diagram. This block diagram clearly shows that the RCK signal is concerned only with the C2 column of D flip-flops which take the output from the shift register and latch it to the output FET through the output enable logic. RCK is independent of the process to clock data through the shift register, controlled by SRCLK. You will note my test did not exercise the transfer function it was just interested in getting data into the shift register and out again.

I stand by my assertion that for the serial shift register function and checking SEROUT, RCK is not relevant. Once you want to start data transfers from the shift register to the output register then it is different matter. No disagreement there. Having that timing wrong will lead to a mess of corrupted data.

Thanks again to all. This is solved and is a lesson to abide by good practice always.

Regards, Fred.


dot matrix arduino turn off the intermittent led I made a dot matrix that contain 10 row and 12 column , total 120 led.
I want to turn on the leds like this picture but when I open ground 1 , 2 and pin 0 , 1 , 2
6 leds light together.what kind of structure should I build?
Sheme :

I tried row by row like this:
 clear_cube();
 regWrite(cube[0][0], HIGH);
 set_array(4);
 //delay(10);

clear_cube();
regWrite(cube[1][0], HIGH);
set_array(3);
//delay(10);

clear_cube();
regWrite(cube[0][0], HIGH);
set_array(2);
//delay(10);                                                                                When I decrease the delay 5 leds blinking.

100  50  10  0 delay   Youtube

You can't just turn them on like that.
Instead you have to turn one row on. Then the next row. Then the next. Very fast.
So you first display:
O@OO
OOOO
OOOO

Then you display
OOOO
OO@O
OOOO

Then you display
OOOO
OOOO
O@OO

And you cycle through that very fast.  Usually using a timer to run it all.  The fact that you're using '595s will slow you down and make it harder to update fast enough to look non-flickery.


Why the 4.7 K Ω resistor in this pitch follower sketch? I am reading Arduino for Dummies, and I am blocked at the pitch follower exercise. It consists in making a piezo vary with a light sensor. I can't see the point of the resistor (and why 4.7?) in this sketch:

Any help for a dummy is appreciated! :-)

The resistor couples with the LDR to form a voltage divider. The voltage at the point where the resistor and LDR join will vary depending on the ratio of the two resistances - the resistance of the LDR and the 4700 ohm resistor.

The value of 4700 is chosen to allow a reasonable range of voltages when in a ratio with the LDR, and the best value depends on the resistance range of the LDR.


Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory I'm writing a library for Charlieplexed LED display (trying to write a common one actually). The library is working quite fine. In my arduino sketch, I'm using an integer to keep track of the LED, currently on. The integer value increases with time and the LED(s) glow one by one. The problem is, after couple of iterations, this integer value just goes out of chart (in Serial monitor, it has garbage values).

MatrixCharlieplex mch(Pins, 5, MXCHARLIE_CA); // instance of Class
int i = 0, j = 0;
boolean busy = false;
unsigned long time;
void setup() {
  //Serial.begin(9600);
  time=millis();
}
void loop() {
  if(millis() - time > 100){ // runs every 100 ms interval // corrected from (millis() > (time + 100))
    time=millis();
    blink();
  }
}
void blink(){
  if(!busy){
    busy = true;
    //Serial.print("i:\t");
    //Serial.println(i);
    //Serial.print("Node:\t");
    //Serial.println(i+1);
    mch.TurnOn(i+1);
    increase();
    busy = false;
  }
}
void increase(){
  i = (++i % 20); // resets after every 20 intervals
}

Output:

i:  16
Node:   17
i:  17
Node:   18
i:  18
Node:   19
i:  19
Node:   20
i:16 <-- Stopped working here. it should be "i:    0" & "Node:    1"
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20
16
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20

The sketch can also be found here

Update:
There were no hardware-fault. The problem lies in the struct variable declaration as pointers.updated the question & posted answer. The files in the github links have also been updated.

If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.

I suggest current-limiting resistors like this:


Digital Input with long cable - flickering values I have an Arduino Nano with two attached Motion sensors "PIXNOR HC-SR501". This sensor puts 5V on its middle Pin, when it detects motion. I have connected this Pin to my Arduino and read the value with digitalRead

Here is the simplified code of my loop:

void loop() {
    motion1 = digitalRead(motion_pin1);
    motion2 = digitalRead(motion_pin2);

    if(motion1== HIGH) {
      if(debug){
        Serial.println("Motion 1");
      }
    }
    if(motion2== HIGH) {
      if(debug){
        Serial.println("Motion 2");
      }
    }

    // Wait 1,0 Second
    Sleepy::loseSomeTime(1000);
  }

Problem is... This used to work fine, but I had to extend the cable to the motion sensors from ~10 cm to 500 cm. Now I have the problem, that the Arduino sometimes (quite often) detects voltage on the motion pins, although there is no motion. I guess the Input-pins are is too sensitive?
What can I do to prevent this flickering?

That device (datasheet) puts out 3.3V on the OUT pin, not 5V:

  ◦ TTL output: 3.3V, 0V

The excess cable is most likely picking up EMI and creating spurious pulses on the input. There are two basic ways of combating this:

Increase the drive strength (especially the sink capacity) of the output
Implement a balanced line communication system

You can combine both those quite easily, whilst at the same time boosting the output voltage to 5V using a 74HCT04 hex inverter chip (make sure it's the HCT variant).  Powered from 5V it will boost the logic level from 3.3V to 5V, and it will have a greater drive strength than the PIR chip alone.

Then the trick is to use multiple gates in the right way to make a crude balanced line system:

Basically you're double-inverting the signal so it remains the same logic level (high = high, low = low) but has higher drive strength, and you're also single-inverting the signal so it has inverted logic (high = low, low = high).  You then connect those to two different IO pins on the Arduino. Read both pins (instead of just one) and as long as the signal are opposite (Q = HIGH and !Q == LOW) then you have a valid signal. If both signals are HIGH then you have noise and you can ignore it.

You also need to ensure you select the right kind of cable. Ideally you need a cable with at least one twisted pair in it so that the Q and !Q signals are twined around each other. This ensures that if EMI is induced into the wire it's induced into both signals equally.  CAT5 Ethernet cable is often quite a good choice.


How do I turn on or off an array of LEDs based on the value of a variable? I've created a function whereby an int ('cleanCount') automatically goes up or down (0-1000) based on the situation. The value changes every few milliseconds.

Based on the value, I would like to turn on or off LEDs. Let's say for every increment of '100' another LED goes on. So if the value is 359 there are 3 leds on, if It would been 899 there would've been 8 LEDs on.

I could simply write

if (cleanCount <= 100) { // turn on NO LEDs
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    ...
}

...

else if (cleanCount <= 500) { // turn on 4 LEDs
    ...
    digitalwrite(led3, HIGH);
    digitalwrite(led4, HIGH);
    digitalwrite(led5, LOW);
    digitalwrite(led6, LOW);
    ...
}

but that would be a big pile of code which could be way more efficient. Perhaps.. my code isn't even correct.

So how could this be more efficient or perhaps actually working?

The whole code, here below.

int cleanCount = 1000;
int softpotPin = A0; //analog pin 0

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF AANGERAAKT
        digitalWrite(werktIeLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // 5x zo snel als leeglopen
    }
    else if (softpotReading > 980) { // IF NIET AANGERAAKT
        digitalWrite(werktIeLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconden
    }
    else {      // Als er een fout optreed..
        Serial.println("Fout!");
        digitalWrite(werktIeLED, HIGH);
        delay(250);
        digitalWrite(werktIeLED, LOW);
        delay(250);
    }

}

Here is a suggestion with the led pins in an array that you loop over.

I suggest making the array global, so put it outside any functions (usually at the top):

byte led_pins[] = {pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8};

Then put this in your loop (assumes that you have a int called cleanCount that is in scope:

const int increment = 100;

for (int i = 0; i < sizeof(led_pins) / sizeof(led_pins[0]); i++) {
  boolean onOrOff = cleanCount > (i+1) * increment;
  digitalWrite(led_pins[i], onOrOff);
}


Connect Bluetooth remote control with Arduino For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

On the Arduino-side I have an HC-05-Bluetooth module. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.

In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:

void loop() {
  sensorValue = analogRead( sensorPin );
  cm = 10650.08 * pow( sensorValue, -0.935 ) - 10;
  Serial.println( cm );
  softSerial.println(cm);
  delay( 500 );
}

Instead of sending sensor values, I need to connect said remote with the Arduino.

(Picture shows the basic model of said remote control.)

The remote control has the Bluetooth class 20258C which means:

Major Device Class: Peripheral
Limited Discoverable Mode
Audio
Pointing device
Remote control

Remote Control Bluetooth  Specifications:

BT Device Name: YL-BTM3-xxxxxx
Supplier ID and Product ID: 0x0A5C / 0x4503
Class of Device: 0x20258C

My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?

Best regards

This should be a comment, but..

For starters, you'll need to do the pairing from the Arduino with the HC-05 in master mode.

Check this out.


How do I lower clock speed for MKR1000? According to data sheets, the MKR1000 runs a SAMD21 Cortex-M0+ processor at 48 MHz. For a project I need to drop that down to 16MHz to get some accurate timing in us. How can I do this? Most of the suggestions on the internet involve the ATmega* boards.

Thanks in advance.

48 MHz is a multiple of 16MHz. Why not just adjust the timing code to account?


Arduino Attiny 85 IR library compiler error I'm about to ask a question for the most common problem which everyone has with attiny85 and the IR library. I will try to make this question as simple as possible.

Few things about the lib and the chip

First of all the lib https://github.com/shirriff/Arduino-IRremote works great on the UNO and it's the best out there.

The Attiny85 is the smallest chip you can get able to run Arduino code. It has alot of limitations but it worth it!

The common problem

Attiny85 uses different timers from the normal Attiny and Atmega chips which makes it impossible to run the standard libraries. There are some fixes for some libs. For example the IR Remote has a version which ALMOST works with the chip and it can be found over here: http://gammon.com.au/Arduino/IRremote_Attiny.zip

However the problem lies in the core. The first time i used the patched IR i had the MIT High Low Media Group versino 1 of the core files which bearly worked but it was the first released so...

After reading this guide:http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS I used an updated core which can be found here: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

And the final problem

Even with the updated core i still got only 1 last error.

Compiling 'Shit' for 'ATtiny85 @ 8 MHz  (internal oscillator; BOD disabled)'
IRremoteInt.h:101: error: 'RAWBUF' was not declared in this scope
Error compiling

Does anyone know how to fix it?

Links

MIT high-low group first version: http://highlowtech.org/?p=1229
Tutorial for the chip and the IR: http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS
The IR original lib: https://github.com/shirriff/Arduino-IRremote
Updated core: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

Just in case you wanna know i'm using the Atmel Studio 6 with the Visual Micro plugin instead of the crappy-arduino-IDE

RAWBUF is defined in IRremote.h. Make sure you include that header before including IRremoteInt.h.


String Comparison Result I've following code:

char a[5] = "bang";
char b[5] = "";
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (a != b){
  for(int i=0; i<4; i++){
      b[i] = a[i];
    }
    Serial.print("b: ");
    Serial.println(b);
    Serial.println("Not Equal");
    delay(1000);
  }
  else{
    delay(1000);
  }

}

Why the output is:

b: bang
Not Equal
b: bang
Not Equal
b: bang
Not Equal

Shouldn't a and b equal after first loop?

As Matej already mentioned, use:

strcmp(a, b) != 0

If you compare a and b, what you are actually doing is comparing two pointers (to the text characters). These pointers a and b are stored at different locations in memory, although the content itself can be the same.

See it as this:

a   memory location 0x12345: "Bang"
b   memory location 0x1234A: "Bang"    (5 memory locations further)


None of the programs in Arduino example is compiling I am new  to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\ drive

exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist
    Error compiling.

I don't know what to do. Please help me

A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it here.

What's odd looking too me is:

The double backslashes, they could be causing the file to appear not to exist, and
The arduino-nightly component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.


void loop followed by other "void" expressions I hope this is a simple request from a newcomer to Arduino and programming. I have understood that once a program enters a void loop section, it loops round indefinitely. However I have recently seen examples of sketches where another void $$$$$ section follows the closure (by}) of the void loop. As I write this, I am looking at one example concerning a 7 segment display where "void Num_Write(int)" follows the closure of the void loop. If the "loop" section does just that, as I have been lead to believe, how is a following section accessed?

Thank you,
Rob

The void loop() section is a function, the same as void setup() is a function.  When you start you Arduino program another function, that you can't see in the IDE, call setup() and then calls loop() repeatedly.

These other function you have seen, i.e. void Num_Write(int n) can be called from either setup() or loop() and they will execute their instructions before returning to the function that called them. Its also possible the Num_Write() may call other functions before it returns controller to the function that called it.

The type void is used to represent nothing (its actually more complex than that, but for this level of explanation nothing will do).  Other functions may return other types int, char, bool for instance.  So if we had a function like this:

int theMeaningOfLife(void)
{
  return 42;
}

This is a function that returns an int (a number) so you would call it like this:

void setup()
{
  int number = theMeaningOfLife();
}

There is one catch, the function has to be declared BEFORE it is used, this allows the compiler to know what you are referring to.  The simplest way of doing this is to write the function above the function that is calling it.  The second way is to just write the function's signature above the function using it, i.e.:

int theMeaningOfLife(void);

void setup()
{
  int number = theMeaningOfLife();
}

The best way (but not always practical on an Arduino) is to have all the function declarations in a header file (.h) and the code in a .cpp file.  (Have a look a library to see what I mean).

Summary

There is only one function that is called repeatedly and that is the loop function.
Just because a function returns void doesn't mean its going to loop repeatedly.


Arduino Ground Current and DC power jack I have a project where I'm providing power via the DC jack to my Arduino then accessing the DC power via the VIN pin. According to this http://forum.arduino.cc/index.php?topic=453955.0 I am ok to draw up to 1A from the VIN pin. I have measured 400ma out of VIN, so ok on that front.

But according to this http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations I can draw max 400ma, So I'm a bit confused, which is the correct amount of power VIN can supply if the Arduino is being powered via the DC jack?

If I take the first thread as correct and assume it's ok to draw up to 1A from the VIN pin (from the DC power jack), is it ok to ground that current on the Arduino GND pin ? if VIN can supply up to 1A then I assume that it's ok to ground up to 1A, is this correct?

All help appreciated

Going by the schematic here there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).
The datasheet here indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).
Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.

If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.


Using Arduino to detect when a sensor is on and off and display time elapsed I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.

Here is the code for the timer:

int main(void) {
  LARGE_INTEGER frequency; // ticks per second
  LARGE_INTEGER t1,t2; // ticks
  double elapsedTime;
  // get ticks per second
  QueryPerformanceFrequency(&frequency);
  // start timer
  QueryPerformanceCounter(&t1);
  //the code for sensorwill be written here
  QueryPerformanceCounter(&t2);
  elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
  printf("\nElapsed time : %lf ms.\n", elapsedTime );
  return 0;
}

You can easily do this in Arduino.

However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the millis() and micros() functions? The only problem with the micros() function is that it will overflow after 70 minutes.

The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.

Most of the code for this can be extracted from the various Arduino examples that are on the website.

For the pressure sensor threshold you can use the Arduino AnalogInput example and add an if statement after the analog read and combine that with the millis() function from the Arduino BlinkWithoutDelay example:

int sensorPin = A0; // Choose whichever analog pin you like
int sensorValue = 0;
int flagA = 0;
// flag is used just to indicate if timer has started or stopped

unsigned long startTime;
unsigned long stopTime;
unsigned long elapsedTime;

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

void loop() {
  sensorValue = analogRead(sensorPin);
  // read the value from the sensor
  if(flagA == 0  && sensorValue > xxx) then {
    // if above threshold run timer
    startTime = millis();
    flagA = 1;
  }
  if(flagA == 1 && sensorValue < xxx) then {
    // if falls below threshold stop timer
    stopTime = millis();
    elapsedTime = stopTime - startTime;
    Serial.print("Elapsed time = ");
    // Put your print function in here
    Serial.print(elapsedTime);
    Serial.println(" ms");
    flagA = 0;
  }


How can I scan for a HIGH signal on digitalRead during the main loop, while running other things? I'm working on a program which listens for certain bytes on serial through an if/then/elseif ladder. I want to also check if a pin (say, A15) has been given a HIGH state, by another Arduino with shared ground. The slave Arduino will turn a digital pin to HIGH and I want the MEGA2560 to check every time it loops if a HIGH is present from the other board. A "While button not pressed do nothing statement won't work, because that won't let the loop go. I tried doing an if statement, using something to the effect of this:

if (digitalRead(A15)==HIGH) {
  //things to do
}

But it seems no matter what I put, be it HIGH, LOW, != HIGH, != LOW, etc. or either input pinmodes, pullup or not, it always thinks the board is transmitting HIGH. In fact, it only doesn't think it's HIGH when it actually is HIGH. I'm pretty stumped on this. If you ask me, digitalRead is really odd with what's HIGH and what's LOW.

Simplify, and show your setup code.

First, do you have a pinMode call in your setup function:

void setup() {
  pinMode(A15, INPUT_PULLUP);
  Serial.begin(115200);
}

Then use test code like this:

void loop() {
   if (digitalRead(A15) == HIGH) {
      Serial.println("Pin A15 is HIGH");
   } else {
      Serial.println("Pin A15 is LOW");
   }
}

Connect your A15 pin directly to ground with a jumper and run the sketch above. Open the serial monitor and see what is output. It should be LOW. Then disconnect the jumper and check again. It should now be HIGH. Finally, connect the jumper between A15 and +5V and check the output again. It should still show HIGH.

That lets you troubleshoot just the software piece. Once you get that working, connect pin A15 to the remote Arduino's output pin and try again.


MIDI controlled analog RGB LED strip (code problem) I have a an Arduino Uno doing PWM on an RGB analog LED strip ala the Adafruit guide: https://learn.adafruit.com/rgb-led-strips?view=all. I've written a sketch that accepts MIDI data over USB and uses it to control the LEDs.

#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>

#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

byte commandByte;
byte noteByte;
byte velocityByte;

byte noteOn = 144;
byte noteOff = 128;

int colorGroup;
int pColor;
int sColor;

void setup()
{
    pinMode(REDPIN, OUTPUT);
    pinMode(GREENPIN, OUTPUT);
    pinMode(BLUEPIN, OUTPUT);
    MIDI.begin(1);
    Serial.begin(115200);
}

void checkMIDI(){
  do{
    if (Serial.available()){
      commandByte = Serial.read();//read first byte
      noteByte = Serial.read();//read next byte
      velocityByte = Serial.read();//read final byte
      }
    }
  while (Serial.available() > 2);//when at least three bytes available
}

void updateLights(){
  colorGroup = noteByte/42;
  pColor = noteByte%41*127/41;
  sColor = 127 - pColor;
  pColor = pColor*velocityByte/127;
  sColor = sColor*velocityByte/127;
  if (commandByte == noteOn && velocityByte > 0){
    if (colorGroup == 1){
      analogWrite(REDPIN, pColor);
      analogWrite(GREENPIN, sColor);
      analogWrite(BLUEPIN, 0);
    }
    else if(colorGroup == 1){
      analogWrite(GREENPIN, pColor);
      analogWrite(BLUEPIN, sColor);
      analogWrite(REDPIN, 0);
    }
    else{
      analogWrite(BLUEPIN, pColor);
      analogWrite(REDPIN, sColor);
      analogWrite(GREENPIN, 0);
    }
  }
  else if(commandByte == noteOff || velocityByte == 0){
    analogWrite(REDPIN, 0);
    analogWrite(GREENPIN, 0);
    analogWrite(BLUEPIN, 0);
  }
}

void loop()
{
    checkMIDI();
    updateLights();
}

Currently this code will turn the lights on and off in accordance with noteOn and noteOff messages. However, the color doesn't seem responsive to the note value and the brightness doesn't seem responsive to the velocity value. I suspect that the problem has to do with my arithmetic combined with the data type (maybe a problem with the order of operations), but I haven't been successful in debugging this.

The idea behind the RGB control is that I take the possible note values (0–127) and map it onto three different combinations of colors: R+G, G+B, and B+R. That's three groups of 42 values: 0-41, 42-84, and 85-127. Then I rescale the 42 values onto 0-127 for the intensity values of the LEDs. Finally I scale the intensity of all the colors by the velocity value over its possible max value.

I suggest that you write separate test programs for MIDI input and LED control, before trying to combine them together.  That is, write a sketch to report back on Serial what MIDI data was read, and a sketch to cycle the LEDs through obvious patterns.

For example, if you read 10,20,30 as the three MIDI bytes, output "Got 10,20,30" (or similar).  If that appears to be working, then add your arithmetic and output the results of colorGroup, pColor, and sColor calculations.

Note, the comment after do{ ...} while (Serial.available() > 2); says //when at least three bytes available, which does not correctly represent what that do loop does.  When one or more bytes are available, that loop immediately reads three bytes (getting a value of -1 for any not-available byte).  To do the read only if three bytes are available, get rid of the do{ ...} while construct, and instead say if (Serial.available() > 2) { <read 3 bytes> }.

Note, use parentheses in expressions like pColor*velocityByte/127.  IIRC the C spec allows evaluation of that as either (pColor*velocityByte)/127 or as pColor*(velocityByte/127).  Since velocityByte/127 can only evaluate to 0 or 1, the result of the latter form is either pColor or 0.

Note, your code shows if (colorGroup == 1){ twice.  Change 1 to some other number in the second instance.

To cycle the LEDs through obvious patterns, you could have three different sketches, one that gradually raises and lowers the PWM level on Red, one that does the same for Green, and another for Blue.


Seeedstudio Wifi shield v1.1 Not working with Arduino Mega 2560 I have been trying use the Seeedstudio wifi shield v1.1 with Arduino Mega 2560 as part of my project but I could not make the WiFly library provided on the wiki work with the Mega. I tried to run the example sketch wifly_test but it did not work I tried some troubleshooting and found that the write commands to the shield were not successful. After a few hours of searching on the internet, I found out the problem and was able to solve it. I am posting my solution below. Anyone is welcome to add to my solution.

The WiFly library provided at the Seeedstudio wiki uses the software serial to communicate with the WiFi shield. All the example files provided by the WiFly library use pins 2 and 3 as the Rx and Tx of the software serial. Moreover, the Wifi shield only allows pins 0-7 to be chosen as Rx and Tx by using different jumper combinations.
The SoftwareSerial library, on the other hand, has the following limitation for the Arduino Mega

  Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

Thus, as a workaround, I jumped pin 2 of the shiled with pin 10 (Rx of Software Serial) and pin 3 with pin 11 (Tx of Software Serial) using connecting wires and used the jumper setting given on the wiki. Finally I made the following changes in the example code

// Pins' connection
// Arduino       WiFly
//  10    <---->    TX (via connecting pin 2 to 10 on wifi shield)
//  11    <---->    RX (via connecting pin 3 to 11 on wifi shield)

SoftwareSerial uart(10, 11); //change software serial pins for Mega

This allowed the Mega to communicate with the Wifi shield successfully using the WiFly library.


How to use web data from GSM Sim900 to be used as input for Arduino? I have a GSM Sim900 connected to an Arduino Uno. I'm successfully able to use HTTP READ commands to show data from the web on the Arduino's serial monitor. It is showing complete HTML from that URL on the serial monitor.

Now, how should I filter data from the web? I mean I just want to display selected numbers in the serial monitor and not the complete HTML.

And secondly, how should I store these numbers into a variable so I could use them as input data for Arduino?

Thank you.

You should read the manual.
More specifically the "Sim900 AT reference".
I've found it on a russian server (https://www.google.nl/url?sa=t&source=web&rct=j&url=http://wiki.amperka.ru/_media/%25D0%25BF%25D1%2580%25D0%25BE%25D0%25B4%25D1%2583%25D0%25BA%25D1%2582%25D1%258B:gprs_shield:gprs-shield_sim900_at_commands.pdf&ved=0ahUKEwinze2Tp7fQAhWBMSYKHQFkBh0QFghEMA0&usg=AFQjCNGKd5Uohe7CmcJcIc1Am-SKdRsWXg&sig2=XIsvvkLWHs60sTo7FZ7tWw) but you may want to try and get it directly from the manufacturer.

In the datasheet, it will explained what values are allowed with the "at+httpread" command. You can actually specify which part you want to read. This is usefull when your Arduino can't parse the complete page.

If you have control over the page, you may also generate a device-friendly page consisting of key-value pairs, instead of it being a whole HTML page.


Is my code triggering the N-Channel MOSFET as I have intended to I have a certain bit of code that I believe after 10 seconds will send a high signal to the second digital pin for 50 seconds. After it will not do anything.

For some reason the nichrome wire is not heating up. I realize there could be a problem with my circuit but just want to make sure for the final time it is not an issue with my code. Thanks.

int nichromePin = 2;

unsigned long burnTime = 10000;
unsigned long dt = 50000;
unsigned long time;

void setup()
{
  pinMode(nichromePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Balloon Countdown...");
  Serial.print("When Will It Burn: ");
  Serial.println(burnTime);

}

void loop()
{
  time = millis();

  if (time > burnTime && time < burnTime+dt)
  {
  digitalWrite(nichromePin, HIGH);
  Serial.print("Time: ");
  Serial.println(time);
  }
}

The code is as follows: After 10 seconds following Arduino power up, burn the nichrome for 60 seconds, after which do nothing. I just tested it on my UNO and it works fine, so it must be your circuit. Post your nichrome question in the EE forums for help on that.

P.S. This code is kinda silly tho there's no trigger event!


how to stop the relay after it is getting on and let the sensor get the result I want to provide a delay in the following iteration reading so that the sensor can read the condition after the pump starts.
void loop() {
  //-------------Fungsi Read sensor-----------
  // sensorAll();

  hasilec = (ppmcensor - inputec);
  ph = (phcensor - inputph);

  //  hasilec = random(-200, 0) / 100.0;
  //  ph = random(-200, 200) / 100.0;

  //  ph = -180/100.0;
  //  hasilec = -1.2;

  unsigned long now = millis();

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph); Serial.print(" ");
  Serial.print(hasilec); Serial.print(" ");
  Serial.println(" ");

  //  delay (500000);

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1);//pHDOWN
  float pompa02 = fuzzy->defuzzify(2);//pHUP
  float pompa03 = fuzzy->defuzzify(3);//ABMIX

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa01);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa02);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa03);
  Serial.println("");
  Serial.println("");
  Serial.println("");

  delay (2000);

  long int pompa1 = pompa01 * 1000;
  long int pompa2 = pompa02 * 1000;
  long int pompa3 = pompa03 * 1000;

  pump_periods[0] = pompa1; //PHdown
  pump_periods[1] = pompa2; //PHup
  pump_periods[2] = pompa3; //ABMIX

  for (int i = 0; i < jml_pump; i++) {
    if (now - pump_last_actuations[i] >= pump_periods[i]) {
      pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;
      digitalWrite(pump_pins[i], pump_states[i]);
      pump_last_actuations[i] = now;
    }
  }
}

If I put the delay after millis iteration it causes the pump to only turn on based on the delay, not the timer millis. What should I do?

If all the pumps have to work for pump_periods[i] time on every loop, and you will have a long delay() anyway, you could replace the for loop with:
for (int i = 0; i < jml_pump; i++) { // For every pump:
  digitalWrite(pump_pins[i], 1);     // Start pump i
  delay(pump_periods[i]);            // Wait for pump_periods[i] ms
  digitalWrite(pump_pins[i], 0);     // Stop pump i
}
delay(120000);                       // Wait 2 minutes until mixed

This will block the loop, but you will have a long delay anyway. The pumps will work sequentially, and not at the same time.
Is that what you want?


How to put together an HKT30 optical rotary encoder? I'm working on a project involving stepper motors. It is important for this project to track the position of these motors, so I decided to buy an optical rotary encoder, specifically an HKT30(HKT3005-C03G-1000B-5E) pictured here. I've found it difficult to find resources on how to put this together. I've found datasheets, like this one, but it does not seem to be made up of the same components I have. I think I've basically gotten the gist of how one puts this together from google images, but I would like to be pointed in the way of an explicit resource in case I damage my parts.
Additionally, I was hoping for an explanation on the 5 wires (red, green, black, white, and gray), their purpose and how to set one up on a board.
If any clarification or images are needed, I would be happy to provide.
Thank you!

It's not hard...

The sensor screws into the screw holes.
The disc slots into the gap in the sensor
The case clips on the outside

As to what the wires are, only the datasheet / manual / manufacturer can tell you that. Maybe if you trace them on the sensor board you can work out what is what.


Handle reading timing in Python using pySerial I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every 5 seconds.

From Arduino I could do,

Serial.println(value);
delay(5000); // should I wait here?

Inside Python script I could do,

import serial
import time

arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?

while True and arduino.isOpen():

    try:
        value = arduino.readline().strip()
        print value

        time.sleep(5) # should I wait here?

    except KeyboardInterrupt:
        print "\nClosing..."
        arduino.close()

EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer.
I've found out that to solve that I should add arduino.flushInput() just after opening the port.

The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.

Arduino delays

You don't need to deal with the timing delay in python if the Arduino is delaying. According to the documentation readline will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.

Note that readline will block your program from doing anything else while it waits. As such, It is pretty useful to explore python threading when you are writing a program which collects data over a serial stream unless the program is only collecting data.

Python sleeps

If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each loop, and for the python script to only read the data every 5 seconds. In this case you could have python sleep and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using sleep by using a timer object to periodically call a function that opens the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream.


How to load program into Arduino pro mini using FTDI cable? Do we need a ftdi basic board to connect a ftdi 232R USB - TTL serial level converter cable via a 6 pin 0.1" male header into an Arduino pro mini/ nano 328 to upload the sketch?

For the Arduino Nano:

NO, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.

For the Arduino Pro Mini:

YES, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.

NOTE:

If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.


Does int array[100] = {0} contruct work on Arduino? I'm compiling my code in Arduino IDE. I have an array that I want to 0-initialize. I know memset works on Arduino, but I'm used to this way from my desktop C++ programming practice:

int array[100] = {0};

I couldn't find any info on whether or not this construct works on Arduino. I think it should since it uses GCC compiler. Even though it may be modified, I still expect it to remain C and C++-compliant. Still, can you confirm for me that this standard-compliant C/C++ construct works on Arduino?

I'm used to this way from my desktop C++ programming practice:

int array[100] = {0};

  I couldn't find any info on whether or not this construct works on Arduino.

The = {0} has no actual effect. It is the same as:

int array[100];

Uninitialized static / global variables, and variables explicitly initialized to 0, are placed in the .bss section of memory.

This section is initialized to 0 by the CRT (C Runtime) code (the startup code for the system).

The compiler is responsible for placing these variables in the .bss, but it is the job of the startup (CRT) code to initialize it to zero.

This is standard C operation and is not likely to ever change since it would break all sorts of things.

Note: this does NOT apply to local variables allocated on the stack. These must be initialized to 0 if you want them to start as 0.


How to add .h file in library I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h
not available". Please tell me how to add this .h file.

In you Arduino Sketch folder there is a folder called Libraries, create a folder there and put your header file in that folder and restart the Arduino IDE.

For example (PC):

Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

You can now use it in all your projects.

If you only want to use with a particular sketch, place in in the same folder as you  sketch and restart Arduino IDE.


Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding? I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as vim). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that vim and other packages have disappeared, as well as my Python code.

Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?

After upgrading the firmware and rebooting:

Log in to your Yun through your browser and use the LuCI interface.
Navigate to "System" > "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)


Hand-held programmable device needed Hopefully this question is not too off-topic for this board. I need a ready-made programmable hand-held device with an ethernet-connection. Something like an Arduino with batteries and display and some buttons in a box.
This is for my company so a complete ground-up assembly is too expensive and time-consuming in this case. Any hints to companies that produce something like this are welcome. And yes, I tried searching with different search-engines already. :-)
Thanks for your time!

I have no opinion about this hardware (I don't own it) so please treat my answer as information only. When I was searching through web I found M5Stack

It looks like hardware made for IoT development.
It has a LCD and 3 buttons and think it can be programmed using ArduinoIDE.
It's designed that you can design any hardware you want and "stack" the device on top of it. Found if available to buy from China for below 30USD.

https://www.youtube.com/watch?v=U2es-l4z2Zg


Error compiling for board Arduino/Genuino Uno I am getting the following error message when compiling a program on my Arduino IDE. This does not happen when compiling the given example programs in the IDE.

The error message is as follows :

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
C:\Program Files\Arduino\hardware -tools
C:\Program Files\Arduino\tools-builder -tools
C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries
C:\Program Files\Arduino\libraries -libraries
C:\Users\mahim\OneDrive\Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path
C:\Users\mahim\AppData\Local\Temp\arduino_build_361527 -warnings=none -build-cache
C:\Users\mahim\AppData\Local\Temp\arduino_cache_227236 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=
C:\Program Files\Arduino\hardware\tools\avr -verbose
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino
readlink
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino: The system cannot find the file specified.

Error compiling for board Arduino/Genuino Uno.

This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.


WS2812B Power Supply I have a WS2812b addressable RGB led ribbon that is 5m (150 RGB leds). I purchased a 5v 10amp power supply to power it; however, whenever I try to use it to power the LED strip the leds start flashing colors like crazy. Is there a reason I would be seeing this behavior or is this a sign of a bad power supply?
The setup is very simple, the data line is coming from an Arduino Uno, the voltage and ground are from the power supply. The program is just one of the sample ones with FastLED library and works "fine" when just powered by the arudino's 5V pin.
Thank you

The strip and the Arduino need to share the same ground connection. They are communicating through voltage and voltage is always a difference between two points. The power supply sets the supply voltage as the difference between + and ground. The chips in the strip will then try to measure the voltage on the data line relative to their ground. When the grounds are not connected, the Arduinos output pin is floating somewhere else, depending on external factors. By connecting the grounds, both devices (Arduino and strip) use the same ground value to measure voltages. Only this enables communication between the devices.


FastLED: Can't address led individually I'm unable to access the first led in my strip with this code:

void loop()
{
  leds[0] = CRGB::White; FastLED.show(); delay(100);
  leds[0] = CRGB::Black; FastLED.show(); delay(100);
}

Instead, it blinks 3 leds, though I expect it to blink only the first one.

Here's how my setup code looks like:

#define DATA_PIN    1
#define CLK_PIN   5
#define LED_TYPE    WS2812B
#define COLOR_ORDER RGB
#define NUM_LEDS    60
CRGB leds[NUM_LEDS];

#define BRIGHTNESS          10

void setup() {
  delay(1000); // Power-up delay

  // tell FastLED about the LED strip configuration
  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

  // set master brightness control
  FastLED.setBrightness(BRIGHTNESS);
}

The led was bought from here: https://www.aliexpress.com/item/0-5-5M-30-60-LEDs-M-2811-Pixels-Programmable-Individual-Addressable-LED-Strip-light-WS2811/32849630888.html?spm=a2g0s.9042311.0.0.8e664c4dU4dru2

The description in the link of where you bought the strip says:

  Description:

  LED Type: 5050SMD with External IC WS2811 （1 IC control 3leds）

So, this is probably as intended.

Note the application circuits in the datasheet for the controller IC (WS2811) [Page 5] where, for 5V, you can address a single LED, but for a 12V configuration, you must group the LEDs in sets of 3.


confirming this will blink LED at given frequency I want to blink an LED at an specific frequency, ie: 7Hz
here what Im doing
int ledPin = 4;
float freq = 7;

void setup() {
  pinMode(ledPin, OUTPUT);
}

float periodo() {
  float peri = 1/freq;
  float halfer = peri/2;
  float millisec = halfer*1000;
  return millisec;
  //return ((1/freq)/2)*1000;
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(periodo());
  digitalWrite(ledPin, LOW);
  delay(periodo());
}

Is this correct? is that the best way to do it?
thanks in advance!

You can check if it is correct by timing it for one minute and check if it is (approximately) ok.
However, I see a few improvements:

First is that you always return 1/7/2*1000 = 71.429, which is rounded down to 71. 71 * 14 = 994 ms so you get a bit faster speed than 7 Hz. if this is a problem you have to compensate for this.
Another small problem is that you delay, but the digitalWrite commands also take some time which is not included for the delays. So you need also to take this into account when using a precise delay.
When using floats I always use float constant numbers, like 1.0 and 7.0 instead of 1 and 7. This can especially be useful when you divide two integers (e.g. 1/7), which results in 0.14 this is rounded down to 0 as it is an int.

The best you can do is using the millis command. You keep a timer and compare it to the current millis value. If it is too high, do a state change. This will take into account every other method you do meanwhile the digitalWrites.
Something like: (code fixed due to EdgarBonet's remarks)
const float FREQ = 7.0; // Hz
const int PIN_NR = 4;

unsigned long _startTime;
unsigned long _counter;

int _currentState = LOW;

void setup()
{
  _startTime = millis();
  _counter = 0;
  _currentState = LOW;
  digitalWrite(PIN_NR, _currentState);
}

void loop()
{
  if (_startTime + _counter * 1000.0 / FREQ / 2.0 >= millis())
  {
    _counter++;
    _currentState = ~_currentState;
    digitalWrite(PIN_NR, _currentState);
  }
}

Some small notes:

_currentState is the current state of the LED, with ~ you can flip it (it's called the not operator).
_startTime is the (close to zero) value of the millis value at startup.
Take in mind there is a limit how long this app can run or precise. millis works with ms, meaning you cannot get beyond 500 Hz, and you get 'approximations' with frequencies below in some cases. E.g. when Freq = 80 Hz, you get 1000 * 1 / 80 / 2 = 1000 / 160 = 6.25 => 6, which is actually 1000/6/2=83.3 Hz.
Also the counter is added once per state change, and because of 1000 * _counter ... an overflow exists when _counter >= 256 * 256 * 256 * 256 / 1000 = about 4 million. With 1000 state changes per second, this happens after 4000 seconds, which is 66 minutes. For 7 Hz it will not occur fast.


D1 mini / esp8266 WifiManager So i have a D1 mini that I want to connect to the wifi.
I found the following code on the internet that is supposed to start a web server, that you can visit and then connect to the chosen wifi through the website. It will then remember the settings and try to connect to that wifi next time before it starts a web server - which is just what I need!
The problem is that when I connect to the wifi the d1 mini thinks it did just than - but when I visit my router and check it is not connected.

I cannot figure out why it thinks it's connected but is not, can anyone help me?

#include <FS.h>                   //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

void setup() {

  Serial.begin(115200);
  Serial.println();

  //WiFiManager

  WiFiManager wifiManager;

  //reset settings - for testing
  wifiManager.resetSettings();

  IPAddress _ip = IPAddress(192, 168, 0, 35);
  IPAddress _gw = IPAddress(192, 168, 0, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
  if (!wifiManager.autoConnect("WemosAP", "ConfigureMe")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}
void loop() {
}

btw: the ip 192.168.0.35 is free, and I have checked both the gateway and the subnet mask from my laptop by running ipconfig in cmd.

So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

}

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

}


LED strip problem... getting red when expecting white with lots of pixels. Fine with 1 pixel I have an Arduino Uno.  I bought this LED strip:  https://www.amazon.com/gp/product/B019DYZNO6/ref=oh_aui_detailpage_o08_s02?ie=UTF8&psc=1

Starting initially using FastLED library. When I tried to set the entire strip to white (255,255,255), it was coming out red. Any color close to white was coming out red.

I thought maybe there was an issue with the library, so I tried the neopixel library. Same thing until... If I just set one pixel to 255,255,255 and don't set any other, it comes out white!  If I set about 10 pixels, they still look white. As I set more pixels, they start to loose their whiteness and become red.

I want to say that maybe this was a power issue... but I tested this both when it was running off my PC and running standalone with a power supply (supplying 5V).

Any suggestions??  I also thought that maybe it's a bum strip, but I also bought https://www.amazon.com/gp/product/B01AG923GI/ref=ask_ql_qh_dp_hza and did the same experiment, and am getting the same results...

According to https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels a Neopixel can consume 60 mA at full brightness white.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue). In actual use though, it’s rare for all pixels to be turned on that way. When mixing colors and displaying animations, the current draw will be much less. It’s impossible to estimate a single number for all circumstances, but we’ve been using 1/3 this (20 mA per pixel) as a gross rule of thumb with no ill effects. But if you know for a fact that you need every pixel on at maximum brightness, use the full 60 mA figure.

So your 144 Neopixels would require 8.4 amps. You would need a pretty solid power supply to supply that much.
One way of confirming that would be to measure the voltage in to the Neopixel strip (at the strip end) when it is displaying all white. I'd be surprised if it measures 5V.
The Amazon page you linked says:

Voltage: DC 5V
Power: 0.3W ± 0.01% per LED

That agrees with the figure of 60 mA (0.060A * 5V = 0.3W)

To put it another way, your power supply would need to supply 43.2W (144 * 0.3W). None of the bench power supplies I have here can put out 43W (or 8A), nor any of the wall-warts. You may have a really massive one, but you haven't specified what sort of power supply you are using.

I run them with a power supply (one that is working as expected, but still have it connected to the PC/USB?

Yes, there is a technique for doing that (similar to powering motors etc.).

You have one low-current supply to the Arduino (this could be your USB port even).
You have a high-current supply to the pixels/motor/whatever. This would require thicker cables.
You connect the grounds of both supplies so that they have a common ground reference.
The data line (the pixel information) is sent from the Arduino to the Neopixels

The one power supply can do both roles, just connect the wires together at the power supply end (this automatically connects the grounds, of course).
This way, the heavy-duty current does not go through the Arduino board.

If you are using the USB port for logic power you still connect the grounds like this:


Arduino PWM fading led in assembly I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:

.nolist
.include "m328pdef.inc"
.list

.cseg
.org 0x00
     rjmp start
.org 0x34
 start: sbi ddrb, 5 ;pin 13
        sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
        sbi ddrd, 5 ;pin 5 pwm
        ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
        out tccr0a, r16 ;I'm using Timer0
        ldi r16, 0b00000001 ;no prescaler
        out tccr0b, r16
        ldi r16, 128 ; duty cycle = 50%
        out ocr0b, r16

  loop: rjmp loop

I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its logarithmic perception.


How to keep track of if data is outdated I have a large set of data and it is refreshed every 30 seconds or so. However, not all data is refreshed every time. It is possible that no new data for a particular calculation isn't received for even a few hours. For this reason I need to track what data is possibly outdated, but hasn't been updated (maybe due to technical malfunctions or a sensor is down). I was thinking about creating an additional (large) 2d array to do this, and increment some sort of counter. This way if a particular spot is at 1000 this means it is old. When new data is received it can be reset to 0. However, this seems like a slow, ineffective way to do this. How could I keep track of data more efficiently?

OK, so you have three possible states for your values:

No valid data (-1, or 0xFFFF in 16-bit 2's complement)
Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.

By masking and shifting you can separate out the two values:

val = data[x] & 0x3FF;
sec = data[x] >> 10;

Every second add one to the seconds count of each and every data entry that is less than (say) 60.

val = data[x] & 0x3FF;
sec = data[x] >> 10;
if (sec < 60) sec++;
data[x] = val | (sec << 10);

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.

You can make it easier to program by using a union/struct combination:

typedef union {
    int16_t rawval;
    struct {
        unsigned value:10;
        unsigned seconds:6;
    } __attribute__((packed));
} data_t __attribute__((packed));

If your data array is now made up of that type instead of integers:

data_t data[500];

you can now access:

data[x].rawval as the raw 16 bit signed value (to look for -1).
data[x].value as the unsigned 10 bit value from 0 to 1000.
data[x].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:

if (data[x].seconds < 60) data[x].seconds++;

When you store a new value using

data[x].rawval = sensor.getValue();

the seconds is automatically overwritten with 0 which resets the count for you.

And both methods give you data ageing without using a single byte more memory.


Should I buy Arduino as a Computer Engineering Student? I'm going to be in the third year of university in a month. I'm satisfied with the software part of my bachelor but I feel like I lack in practice in practical implementation. Would getting an Arduino board and playing around with it worth it and useful for me?

It depends. If you don't have any knowledge about microcontrollers it might be useful.

However, Arduino hides a lot of concepts in their libraries. If you want to go more indepth check other systems like STM32 or PIC.

You also can do both, start with Arduino to get a rough feeling, continue with another.

More important is WHAT you try, don't stop with LEDs/switches, but check communication protocols like SPI, I2c, UART etc. And learn what timers, interrupts etc. are and how to use them.


Alternative to patching core library source and header files I am following a DIY guide that requires me to patch two arduino core library files: HID.cpp and USBAPI.h. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

Unfortunately there really isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.


How do I figure out if my board is approaching end of life? I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?

Unfortunately, there isn't much way to really determine "wear" in the context of solid-state electronics.

Probably the things that are most likely to fail are the electrolytic capacitors and the connectors.

First, if you're using an ATmega CPU for something that could possibly injure someone CONTACT ATMEL AND TALK ABOUT SAFETY PRECAUTIONS. The ATmega CPU used in most of the arduino models is not rated for use in such situations.

In EVERY datasheet:

  Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

Now, realistically, this is probably mostly lawyer repellent, but you should still take appropriate precautions.

Really, while there isn't anything on a common arduino board that really wears out except the connectors, why are you trying to save $30 at a potential huge cost? Just buy a new board.

I'd also strongly reccomend you chose a board with a SMT ATmega328P, since that removes the IC socket contacts from the list of concerns. If possible, also remove the pin-headers, and solder wires to the board directly. Try to minimize connectors, since they are frequent points of failure.


Pushbutton to initiate a 5 time flash The following code operates in a way that LED starts to flash only if the pushbutton is pushed for one second. I want to change this and make the LED flash for 5 times, immediately on push, regardless if the button is held "long" or released immediately. Can anyone help me out with this? I'm using the LC_baseTools library btw. I managed to do this with another library with doFlash(5) but I have to work with LC basetools in this scenario and I can't figure out how to do it.
#include <mechButton.h>
#include <blinker.h>

#define BUTTON_PIN   11
#define LED_PIN      13
#define BLINK_MS     500.0
#define HOLD_MS      1000

mechButton  theButton(BUTTON_PIN);                    // A debounced button object. (Hook button between pin & ground)
blinker     theBlinker(LED_PIN,BLINK_MS/2,BLINK_MS);  // A fire and forget blinker object.
timeObj     pushTimer(HOLD_MS);                       // A timer object

void setup(void) {
   theBlinker.setOnOff(false);            // Make sure the blinker is acutally off.
   theButton.setCallback(btnClicked);     // Set the callback for the button.
}

// This gets called when the button is clicked.
void btnClicked(void) {
   if (!theButton.trueFalse()) {    // If it has been grounded..
      pushTimer.start();            // Start the timer.
      theBlinker.setPercent(100);   // Set the blinker to full on.
      theBlinker.setOnOff(true);    // Fire it up.
   } else {                         // Else, button released..
      theBlinker.setOnOff(false);   // SHut off the blinker.
   }
}

void loop(void) {
   idle();                             // idle runs the stuff in the background (button & binker)
   if (!theButton.trueFalse()) {       // If the button is currently pressed..
      if (pushTimer.ding()) {          // If the timer has expired..
         theBlinker.setPercent(50);    // Start blinking!
      }
   }
}

First of all, considering your comment: "I don't have time [...] to tackle arduino programming" - If you don't learn how to code, then you can't work with code (and that includes putting together libraries you find on the internet). And learning takes time, it's that simple.
I recommend you forget about those libraries and implement that easy task from scratch, so you actually learn something. The below code has the logic you ask for, try to understand what it does.
#define BUTTON_PIN   11
#define LED_PIN      13

bool button_was_pressed=false;

void setup(){
  pinMode(LED_PIN,OUTPUT);
}

void loop() {
  if (digitalRead(BUTTON_PIN)) {
    if(!button_was_pressed) {
      for (int i=0;i<5;i++) {
        digitalWrite(LED_PIN,HIGH);
        delay(50);
        digitalWrite(LED_PIN,LOW);
        delay(50);
      }
    }
    button_was_pressed=true;
  }
  else {
    button_was_pressed=false;
  }
}

...pretty simple and it's only a few lines. You may want to debounce the button and use a non-blocking coding style, but that's a different chapter.
My advice is that you learn programming in a structured manner, e.g. by watching tutorials. A Q&A site is not the right place to do so, as we only answer questions.


Deactivate pushbuttons at initial stage Pl someone answer my question. I have 4 pushbuttons namely add/reject/start & finish. I want to
1.Deactivate add/reject buttons at initial stage until start button pressed &
2.Once add/reject activated, again should deactivate once finish button pressed &
3.Again if start button pressed, add/reject should be released.
with following code I able to do 2 & 3. However I still lack at 1.pl help on this.
const int bt_Select = 2; // #define BUTTON_PIN 2
const int bt_Reject = 3;
const int bt_Start = 7;
const int bt_Finish = 8;

boolean decision=false;

int bt_Select_state=0;
int bt_Reject_state=0;
int bt_Start_state;
int bt_Finish_state;

int selected;
int rejected;
int started;
int finished;

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(bt_Select, INPUT_PULLUP);
    pinMode(bt_Reject, INPUT_PULLUP);
    pinMode(bt_Finish, INPUT_PULLUP);
    pinMode(bt_Start, INPUT_PULLUP);
    Serial.println("Welcome to Nano");
    delay(1000);
  }
//========================================================================
      void loop() {

        started=bt_Start_pressed();
        selected =bt_Select_pressed();
        rejected=bt_Reject_pressed();
        finished=bt_Finish_pressed();
        decision=Stop_Main();

          int x=0;
          int Lx=0;

       if (selected&&decision){x=1;}
       if (rejected&&decision){x=2;}
        if (started&&decision){x=3;}

       if (x!=Lx){
        switch(x) {
          case 1:Serial.println("Selected");delay(250);Serial.print("");
                 break;
          case 2:Serial.println("Rejected");delay(250);Serial.print("");
                 break;
          case 3:Serial.println("Started");delay(250);Serial.print("");
                 break;

          /*case 3://do something when var equals 1
                 Serial.println("Removed");
                 break; */
             }//switch(x)
                 x=Lx;
      }//eof  if (x!=Lx)

      }
//====================================================================
      int bt_Select_pressed(){
         bt_Select_state=digitalRead(bt_Select);
           if (bt_Select_state == LOW){return 1;}
           else {return 0;}
      }
//====================================================================
      int bt_Reject_pressed(){
         bt_Reject_state=digitalRead(bt_Reject);
          if (bt_Reject_state == LOW){return 1;}
          else {return 0;}
           }
//====================================================================
    int bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){return 1;}
          else{return 0;}
            }
//====================================================================
      int bt_Finish_pressed(){
        bt_Finish_state=digitalRead(bt_Finish);
          if (bt_Finish_state == LOW){return 1;}
          else {return 0;}
      }
//=====================================================================

      boolean Stop_Main(){
        bt_Start_state=digitalRead(bt_Start);
        bt_Finish_state=digitalRead(bt_Finish);

        if (bt_Finish_state == LOW){decision=false;return decision;}
        if (bt_Start_state == LOW){decision=true; return decision;}

       // else if (bt_Start_state ==HIGH  && bt_Finish_state == HIGH){decision=false;return decision;}
          }

/*  boolean bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){started=true; return decision;}
          else{started=false; return decision;}
            }   */
    //===================

Keep a boolean that begins as false. Set it to true when the start button is pressed, and set it to false again when the finish button is pressed. Then you can read and respond to the add and reject buttons only if that boolean is true, and otherwise ignore them.


How to use potentiometer data from slave to master Arduino? I'm trying to make a game where i can use one Arduino as a controller (the controller is a potentiometer) and the other Arduino sending the signals to the computer. Im trying to figure out communication with two Arduino's so i would like to use two instead of one although using one would be logical and easier. Ive tried looking into I2C but cant seem to figure it out.

Start by reading the potentiometer. Add a Wire request service function and that makes the Slave:

#include <Wire.h>

const uint8_t controllerAddress = 8;
const int controllerPin = A0;
volatile int controllerValue = 0;

void setup() {
  Wire.begin(controllerAddress);
  Wire.onRequest(requestEvent);
}

void loop() {
  int value = analogRead(controllerPin);
  noInterrupts();
    controllerValue = value;
  interrupts();
}

void requestEvent() {
  Wire.write((const uint8_t*) &controllerValue, sizeof(controllerValue));
}

This is minor update of the Arduino Wire Master Reader tutorial. The sketch for the Master is left as an exercise.

Cheers!


Dynamically switching pin out I have a connector with 10 pins, and a bus which uses 2 of the 10 pins.

What I need to do is, in software, attach my arduino to 2 of the 10 pins. I cannot wire it directly as the 2 pins required may be in a different position in different environments.

What are my options?

EDIT: Just some background. I have to connect to an OBD II port of a vehicle and cannot to the CAN bus. On some vehicles is may not be on the standard pins in the OBD connector, so I would like to be able to programatically switch the pins being used, in software.

Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.


How does the reset button work on the Arduino? I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.

I have been using this board for many weeks with no problem and just now I have been getting this error:

avrdude: stk500_getsync()

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.

The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.

When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

If you have anything else plugged into the Arduino then unplug it.
Try powering the Arduino from different power supplies.
If you have another Arduino or an AVR programmer try re-flashing the bootloader.


Use server.arg results as a function parameter? I've got an ESP8266 (NodeMCU) and I am trying to understand the ESP8266WebServer library, as how to use the results across functions.

In my setup function, I have the following:

   server.on("/marquee", []() {
      varOne = server.arg("baseColor");
      varTwo = server.arg("marqueeColor");
      server.send(200, "text/html", webPage);
      Serial.println("Marquee  activated");
      state = true;
      ledMode = "marquee";
    });

In my loop, I detect the ledMode and if it is set to marquee then it runs the following FastLED function, amongst others:

fill_solid(leds, NUM_LEDS, 0xFF0000);

What I am trying to figure out is how I go from taking a hex color code of say FF0000 from the URL parameter, and use that in my fill_solid function.

server.arg stores get the parameter as a string, so I am not sure what needs to be done.  Also, using a variable name in place of the Hex code in the fill_solid function results in an error due to not expecting the variable

server.arg stores get the parameter as a string, so I am not sure what needs to be done.

The parameter needs to be converted to an uint32_t (and then to a CRGB or CHSV struct). The simplest way is to use the C library function strtoul

uint32_t color = strtoul(arg, NULL, 16);

This can be improved so that it checks that a number was scanned, etc.

Cheers!