Can I use an AC signal to make an LED light up with arduino? I want to use a 220VAC load as a signal and act as a switch to my arduino so Labview could interpret it as an LED ON state. I used a 4n33 octocoupler but it seems that the LED Simulation on labview keeps fluctuating. I think it's because of the negative half of the signal being blocked. Is there a way to fix this?

Here is my schematic

There's certainly an issue with your optocoupler circuit aside from the fluctuation you observe.

During a negative half-wave of 220V, you expect D1 to block the current through the LED. However, 1N4007 as any power rectifier has significant leakage current, about 5μA at normal temperature and up to 50μA when the diode is hot. This current will go though the LED which may have a much lower admissible reverse current (typical 0.1μA), damaging it. One possible schematic would be:

simulate this circuit – Schematic created using CircuitLab

Note that D1 is here not to block reverse current, but rather conduct it safely, protecting the LED of the optocoupler. Also, consider reducing the value of R2 while realising the bulk of current limitation with a non-polar capacitor: this setup will limit the current just the same but will dissipate 0.5W of heat instead of 2W as your resistor would.

Now, in either case the LED is only active when it's forwad-biased, which is less than half of the time, so it's quite normal that you see this fluctuation. In most cases, it can be reasonably dealt with by software: read your pin 3 times with a 5ms delay after each reading, and make a logical AND of your three readings.

If, for some reason you cannot do that in software, you could implement an envelope detector in hardware. I strongly suggest to do it on the low-voltage side instead of 220V side (as e.g. here)


How should you predict the battery size required for a project? I am using an Arduino nano along with an ESP8266.  The nano is connected to an OLED display and a keypad. The ESP8266 uploads the data entered from the keypad onto a server. I wish to make the device portable; i.e. add a battery to it so that it can last for at least 8 hours.

How can I calculate the rating for the LiPo battery to use? I understand that it is very important to know the current rating of the devices in use.

How can I make an approximate guess?

Yes, you need to know the average current draw over the period of an hour (or over a period that you then extrapolate to an hour).  That is the mAh (milliamps per hour) that your circuit draws.

It can be hard to calculate the actual current, though, since it is always changing depending on what is actually happening in your system at the time.  So I would suggest picking up a cheap current monitoring USB dongle from eBay / Amazon / Wherever (one with an LCD screen that gives mAh, such as this one and use that to get the total mAh of your system over an hour.

Multiply that mAh by 8 (the number of hours you want it to run for), and that will give you the minimum mAh for your battery. And then add some more as a safety margin, since the capacity of a battery is subject to many things (like temperature, age, etc), and the rated value is only a rough guide.

For instance, if you find your circuit uses on average 387mAh, then a battery of 3600mAh should be adequate.


How to get different parsed JSON data? In my recent project, I have to parse incoming JSON data in Arduino and I successfully did it. But it is only for one constant data string.

For example, if my incoming JSON string like:

{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

And Arduino code for parsing this data is below:

#include <LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  while(Serial.available() || !begin) {
    char in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      response += (in);
    }
    if(in == '}') {
        break;
    }
    delay(1);
  }
  JsonObject& root = jsonBuffer.parseObject(response);
  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);
}

Then the output looks like:

TPS  : 0.40
MAP  : 0.95
LOAD : 14

That's fine, but when the incoming JSON string changes, what should I do?

Suppose the incoming JSON string looks like:

{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

Because I have to handle both incoming JSON strings, I can't replace any part like:

  String LOAD = root["LOAD"];
  String RPM = root["RPM"];
  String INJECTION_TIME = root["INJECTION_TIME"];
  lcd.setCursor(0, 0);
  lcd.print(LOAD);
  lcd.setCursor(8, 0);
  lcd.print(RPM);
  lcd.setCursor(0, 1);
  lcd.print(INJECTION_TIME);

Instead of

  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);

If you want to read 3 values of a object that you don't know the names of the key, you can use an iterator as shown in the ArduinoJson library's docs.

And as already mentioned in the comments, you can also replace all the serial reading code with just Serial passed into the jsonBuffer.parseObject function.

#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

void setup() {
  Serial.begin(115200);
  lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i<(sizeof(lcd_pos)/sizeof(lcd_pos[0])); ++it, i++)
  {
    lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    lcd.print(it->value.asString());
  }
}

You will need to make sure, that the values are sent in the order that you want them on your LCD.

EDIT:
I don't have an LCD screen, so I didn't test the code with an LCD, but the code that just dumps the parsed data back to serial works.

//#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

//LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

void setup() {
  Serial.begin(115200);
  //lcd.begin(16, 2);
}

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received");
  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i < (sizeof(lcd_pos) / sizeof(lcd_pos[0])); ++it, i++)
  {
    //lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    //lcd.print(it->value.asString());
    Serial.print(i);
    Serial.print(':');
    Serial.print(lcd_pos[i].x);
    Serial.print(',');
    Serial.print(lcd_pos[i].y);
    Serial.print(' ');
    Serial.println(it->value.asString());
  }
  Serial.println();
}

If I send

{"TPS":"0.40","MAP":"0.95","LOAD":"14"}{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

over the serial, it returns

JSON received
0:0,0 0.40
1:8,0 0.95
2:0,1 14

JSON received
0:0,0 2.40
1:8,0 4200
2:0,1 4.87


Is it possible to add an additional board on Arduino Web Editor (create.arduino.cc)? I'm using a board that can be programmed via Arduino IDE (a NodeMCU with ESP8266) and I've configured the Windows client successfully. I've added an additional board through "Preferences" menu by specifying its configuration url, following manufacturer's directions.

Now, I'm quite happy with the web editor, the one at create.arduino.cc, and I'd like to use it with this board too. Is there any way to configure additional boards?

No, there isn't.

The web editor is completely closed. It's a service run by Arduino, and as such it will only support Arduino's own boards.

Two reasons:

Why should they spend the time, effort and money adding support for other people's products?
It adds value to their products to encourage you to use real Ardiuno hardware.

Business is business, after all.


datalogging sampling frequency bottleneck My datalogging system which consits of the Flora, RTC, SD card breakout board, LSM9DS0 sensor is shown in the picture below;

https://www.dropbox.com/s/d8pwcn59nq11lzs/2014-11-25%2012.26.56.jpg?dl=0

The sampling rate/s is capped at 30 when writing into the sd card. If I disable the sensor and only save the time it goes up to 65. Writing into the serial interface rather than the sd card makes the rate goes up even higher at 127. for my application I need at least 100 samples/s. I am thinking the sd card is the problem after making the tests mentioned. The flora clock at 16Mhz is surely able to provide a higher sampling frequency. After checking the sensor datasheet and library I haven't found any limitation either. any input on this issue?

First, based on my experience with similar hardware, something about the sd card I/O stinks: it should be plenty fast enough. Using a class 4 (cheapo) sd card I've seen a 16mhz AVR do a FAT filesystem open for appending, write a new record of maybe 70 characters and close the file, all a few hundred times per second. This was with the Arduino "SD" library apparently written by Sparkfun in 2010 and improved by Adafruit sometime later.

Maybe the I/O library you're using is dog slow? Another possibility is that your SD card has a lot of files on it and something about directory (folder) traversal during an open is the bottleneck? (my experience is with just a few files on a given sd card)

But you could try buffering N samples so each sd card write records N samples.

If you do this, don't forget to "flush" any remaining samples when you go from "sampling" to "not sampling" modes, if that's possible. That is, if something is telling the thing 'start', then 'stop', part of the response to 'stop' is to get the N-m buffered samples written out to the sd card.


How can I PWM 4 LEDs from 0 to full brightness using a two axiz resistive joystick? I am trying to use the Arduino MAP function to allow me to PWM 4 LEDs between 0 and full brightness. I guess the tricky part is that the joystick neutral position is at the venter of the range of the potentiometers so the analog voltage to the inputs is at +2.5V when the joystick at neutral). Ideally I want to make a red LED that is associated with the Y axis to go from 0 to full as the joystick is pushed away. Similarly, I want a blue LED associated with the Y axis to go from 0 to Full on when the joystick is pulled toward me. I want to duplicate that action for the X axis with green and yellow LEDS but I can't seem to be able to figure out how to compensate for the 2.5V offset* I hoped I could just use mapping of the values.

There's a number of steps you need to go through:

Read the ADC to get the joystick position
Subtract 50% of the full range (512) to get a ±512 value
Note the sign to get the direction
Take the absolute value to get the distance
Subtract a small amount to create a "dead zone" in the centre of the joystick
Map the result to 0-255 for the PWM.

The code might look like (note: untested):
int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead
}

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.

And do the exact same thing for X with different pins.


analogWrite causes value from IR receiver to change I'm playing around with an IR receiver and an RGB led.

I had it up and running, until I changed around some code. The remote seeming stopped working, but after looking at the values in the Serial Monitor it appeared that the values that were being printed out weren't the same.

After playing around a bit I found that if analogWrite is run on pin 11, the value changes. Why is this so?

Code is as follows:

#include <IRremote.h>

int ir_recv_pin = 2;

IRrecv irrecv(ir_recv_pin);

decode_results results;

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

void loop()
{
    if (irrecv.decode(&results))
    {
        //Serial.println(results.value);
        Serial.println(results.value == CH_MINUS);
        Serial.println(results.value);
        Serial.println(CH_MINUS);

        analogWrite(11, 125);
        irrecv.resume();
    }
}

Output is as such when pressing the button twice in a row (without holding the button down):

1
16753245
16753245
0
3810010651
16753245

Initially the values come out as expected (16753245), but after the analogWrite, the value changes (3810010651).

Looking at the documentation it says that pin 11 runs at 980Hz. Is this why the value changes? If so, why?

Because IRremote uses timer 2 by default, and the PWM output on pin 11 is generated via OC2A. Either edit IRremoteInt.h to use timer 1, use a pin on timer 1 for PWM, or frob OCR2A directly instead.


Building Multidimensional Arrays from simple arrays Hi I am trying to write a functiont that will build a 2x4 array based on 2 1x4 arrays.

the two relevant functions are below. The first function gets information from some sensors and outputs it (I think) as a 1x4 array.

The second function is the problem and I have attached the error messages.

{
double quatCalib_mat[2][4];
double quatCalib_ABC[4];
double quatCalib_GHI[4];

 double  get_quat(Adafruit_BNO055 ref, double quatArray[])
{
  imu::Quaternion quat2 = ref.getQuat();

  quatArray[0]= quat2.w();
  quatArray[1]= quat2.x();
  quatArray[2]= quat2.y();
  quatArray[3] =quat2.z();

}

void Calibrate()
{
quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

quatCalib_mat= {
  {quatCalib_ABC},
  {quatCalib_GHI}
  };
}

the error messages

Arduino: 1.6.9 (Windows 7), Board: "Arduino/Genuino Uno"

E:\UNI2016\thesis\gizmo programming\Thesis_V3_M\Thesis_V3_M.ino: In function 'void Calibrate()':

Thesis_V3_M:101: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

              ^

Thesis_V3_M:103: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

              ^

Thesis_V3_M:105: error: assigning to an array from an initializer list

 quatCalib_mat= {

              ^

exit status 1
incompatible types in assignment of 'double' to 'double [4]'

Cheers

Alex

As Mikael Patel said, the compiler is already hinting you about what is
wrong. But there are other issues.

In get_quat(), there is no point in returning anything, as the
function is already putting the relevant info in the quatArray
parameter.
Then, when calling get_quat(), you don't want to assign the return
value to anything.
You cannot assign an array like you did, unless it's an
initialization. I would explicitly copy the sub-arrays with
memcpy():

void get_quat(Adafruit_BNO055 ref, double quatArray[])
{
    imu::Quaternion quat2 = ref.getQuat();
    quatArray[0] = quat2.w();
    quatArray[1] = quat2.x();
    quatArray[2] = quat2.y();
    quatArray[3] = quat2.z();
}

void Calibrate()
{
    get_quat(bnoABC, quatCalib_ABC);
    get_quat(bnoGHI, quatCalib_GHI);
    memcpy(quatCalib_mat[0], quatCalib_ABC, sizeof quatCalib_ABC);
    memcpy(quatCalib_mat[1], quatCalib_GHI, sizeof quatCalib_GHI);
}

It could be noted that storing the calibration array twice (as both one
2D array and two 1D arrays) is a waste of RAM. You could get rid of the
1D arrays and have instead get_quat() fill the lines of the 2D array
directly:

void Calibrate()
{
    get_quat(bnoABC, quatCalib_mat[0]);
    get_quat(bnoGHI, quatCalib_mat[1]);
}


Heart Pulse sensor analog value doesn't change even if sensor pressed by finger I have recently bought a Heart Pulse Sensor. Then, to check whether the sensor is working correctly or not, I uploaded this below code:
void setup() {

 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);

 Serial.println(sensorValue);
 delay(1);        // delay in between reads for stability
}

I know, that this code doesn't calculate the actual BPM. It sends 380-400 sensor value through
the Serial monitor, while the sensor is not being pressed by my finger. But when I press it with
my finger, the sensor value doesn't even come out of the range 380-400. But the sensor value was supposed to jump over 500 when a beat happened.
I think, that probably means my sensor is unable to detect beats. And now, my question is, why
my sensor is unable to detect beats?
After looking at some forums, I learned that this sensor can be a clone. After looking at my sensor
carefully, I found some little differences in my sensor than the sensors other people used in their
tutorials. And, the most spottable differences were:
*the colors of my sensor's pre-soldered jumper wires were different than other sensors.
*"pulsesensor.com" was written in the other sensors, but it wasn't written on my sensor
There were also some other differences. I have given three pictures of my pulse sensor below.

My final questions:-

Why my pulse sensor is unable to detect beats?
Is my pulse sensor a clone or not?
If it is a clone, can it be fixed somehow?
Do I need to buy another one?

That's all I know. Can anyone help me! Any help appreciated.
Thanks a lot!

Why my pulse sensor is unable to detect beats?
Chances are something wrong.  The only way to tell what specifically is to keep debugging.  If you don't have access to an Oscilloscope or Multimeter, this will involve checking your wiring and altering code.  To check wiring, make sure:

Minus (-) is to ground
Plus (+) s to your + voltage
S is to the A0.

Is my pulse sensor a clone or not?
It is likely.  Open-Source Hardware tends to have many clones.
If it is a clone, can it be fixed somehow?
Clones sell repeatedly if they work.  There is little point making a clone sensor that does not- if scamming was the point, one could ship empty envelopes.  If two different people make the exact same electronics, we hope that they behave very similarly regardless of who made them.
Do I need to buy another one?
Possible but unlikely.  If you can prove your sensor is defective, a seller might be willing to ship a replacement.
Try the following code to test the sensor.  My guess is that you are missing something due to Serial spamming.  Beyond that, taking a pulse may be tricky - the unskilled can easily pronounce some of the living as dead from just the wrist.  I suggest putting it to your throat to be on the safe side.

int minSV;
int maxSV;
unsigned int Frame;

void setup() {
 minSV=500;
 maxSV=0;
 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);
 if(sensorValue > maxSV) maxSV = sensorValue;
 if(sensorValue < minSV) minSV= sensorValue;
 Frame = Frame +1;
 if(Frame > 10000) //would be 1s if frame takes 0.1 ms
 {
  //might want to reset min and max here after debug is complete and sensor is verified to work.  Until then, reset the arduino to reset min and max.
  Frame =0;
  Serial.print("Min: ");
  Serial.print(minSV);
  Serial.print("; Max: ");
  Serial.println(maxSV);
 }
 // removed: delay(1);        // delay in between reads for stability
}


ESP8266 Timing question / Do something in 2 seconds even I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

The MC recieves the signal for trigger by the user on 09:25:18:312
It waits until it is exactly 09:25:19:000
It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!

Edit: Corrected Times.

You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...

The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).

Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.

You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.


Driving power MOSFET from 3.3v or lower Arduino Pro Mini I want to control a low voltage (hobby class) motor with a 8Mhz/3.3v Arduino Pro Micro.  I'd like to power both from 2 alkaline cells.  The motor draws approximately 1 A @ 3V with new batteries.  I would be doing PWM of a couple of channels at the normal Arduino rates.

My thought is to connect the batteries to the Vcc pin (not Vraw) and run the Arduino unregulated at about 3V, but somewhat less when the motor is running.  I'm willing to reprogram the fuses for a lower brownout voltage (or none) if needed.

I'm feeling my way on the rest of this - I'll lay out my (perhaps naive) approach and get some feedback about whether I'm understanding it, and how to proceed.

With such a low battery voltage, a TIP120 darlington seems to drop too much voltage and substantially reduce the motor speed/power.  So I'm thinking that I need to use a power N channel MOSFET, and it appears that I need to be fairly selective to get one which can sufficiently turn on with a <3V gate to source voltage.

I'm considering something like the

FQP30N06L http://www.mouser.com/ds/2/149/FQP30N06L-244344.pdf

If I read the datasheet correctly, Vgs of 3V and a load Ids of 1A would result in less than 100mV drop Vds.  But this transistor may be overkill, and the TO220 package is larger than I'd prefer.

If I'm willing to deal with SOT-23-3 surface mount packaging, there are some options like:

Toshiba SSM3K324RLF http://www.semicon.toshiba.co.jp/info/docget.jsp?type=datasheet&lang=en&pid=SSM3K324R
Infineon BSS806NE  http://www.mouser.com/ds/2/196/BSS806NE_Rev2%2001-359816.pdf

If I'm reading it right, with 2x1.5v (nominal) batteries directly powering an Arduino Pro Micro, I can sufficiently drive Vgs to handle 1A Ids at a small Vds and a low enough power dissipation, with any of these three.

I would put a reverse diode and a cap across the motor.  I've seen devices with a small electrolytic across the motor terminals, and I've seen a smaller value ceramic cap - what's the best practices?

Is this a feasible and reasonable approach?  What are the gotcha's that I need to take into consideration?  Any advice about choosing among these (or other) transistors?

My concerns are: not understanding MOSFETs enough, and the unregulated power supply being too noisy for the ATMega328p when it's also powering the motor.  Can I handle the latter by adding another cap or two across the Arduino Pro Micro's Vcc/Ground?

Backup option: run 3x1.5v alkalines and power the Arduino Pro Micro through its regulated Vraw input.

I don't think the mosfets will be an issue. Looking at the last one (BSS806NE); in figure 5 in the datasheet you see that for 1A and 1.4v (Vgs) you'd get a Vds of only .1v.

I think a bigger problem might be the voltage of the batteries dropping under load. You'd have to measure that with a multimeter while the motor is running. A simple cap might help with a little noise, but not with the voltage dropping while the motor is running. Not sure how much the AVR would mind having its supply voltage dropping all of a sudden.

Of the top of my head the minimal voltage of the Atmega328 @8mhz is 1.8v, while default fuse settings use 2.7v, so I'd probably change to fuses to make BOD at 1.8v. Other fuses don't need to change.

Backup option sound good, though you might have to go with 4 x 1.5v depending on the voltage drop under load. Another alternative might be to have two sets of 1.5v batteries in parallel, halving the current load on each battery.


Burning arduino generate hex file to blank atmel chip Is it possible to burn the hex file to a blank chip, generated by Arduino to burn using USBASP to that particular chip without using Arduino board ? Will the program work ?

My main goal is to use Atmega328P for low power. Should I select Arduino pro mini in the arduino IDE ?

Ater successful testing I will just burn the hex file to another 50 chips. thats why I dont want to use arduino board.

Yes. The binary generated by the Arduino IDE in no way requires the presence of the Arduino bootloader in order to operate. Note that certain characteristics such as the MCU and clock rate are set at build time and cannot be changed in the final binary.


Arduino reading serial data non-blocking I have an Arduino reading serial data and responding to other inputs as well, I'm trying to read incoming serial data without using the while, if at all possible. the incoming serial data will be formatted in a specific manner each time and will be CSV; It will look like such:

19,1400700083, 1-0,1-10,and other values delimited with a new line character "/n".

The first value will tell how many bytes are coming in so the serial receive function wont parse data until it gets all the bytes,second value is a Unix time-stamp, the third value (1-0) is the "get" or set" value; which will tell the Arduino to return a value or to set a value. The fourth (1-10) value will correspond to what variable to get or set. and the other values will be integers as well but are dependent on the other values.

My code is as follows:

void CheckSerialData() { // begin function

  if(Serial.available() >= 2) { // begin one, first line will be how many bytes incoming.
  int NumberOfIncomingBytes = Serial.parseInt();
    if(Serial.available() >= NumberOfIncomingBytes) { //begin two
    int IncomingTime = Serial.parseInt();
    setTime(IncomingTime); //time is always incoming with serial values
    int GetOrSetValue = Serial.parseInt(); //this value should be 1 or 0 for "getting values(1)" or "setting values(0)"
      if(GetOrSetValue == 1) { //BEGIN THREE
        int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              Serial.print(GetTemp());
              Serial.print("/n");
              break;
            case 1:
              //serialwrite yaw pitch roll
              break;
            case 2:
              Serial.print(GetVoltage());
              Serial.print("/n");
              break;
            case 3:
              //append all RGB final values together and serial print it
              break;
            case 4:
              //print out accel values
              break;
            case 5:
              //print alarm alarmed status
              break;
            case 6:
              //print out last time alarm set off
              break;
            case 7:
              //print out time allowed lights to turn on
              break;
            case 8:
              //print out arduino time
              break;
            case 9:
              //print out system summary, (time,voltage,temp,yaw,pitch,roll,accel
              break;

          }//END SWITCH
         }//END THREE
      else { //BEGIN TWO B //SET VALUES
      int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              //set global rgb value set LEFT
              break;
            case 1:
              //set global rgb value set RIGHT
              break;
            case 2:
              //set global alarm value
              break;
            case 3:
              //set global angle to start flashing emergency led's
              break;
            case 4:
              //set turn signal RGB value
              break;
            case 5:
              //set time that lights are ok to turn on
              break;
            case 6:
              //set light override value
              break;
            case 7:
              //set pattern enable
              break;

          } //END SWITCH

      }//END TWO B

          }
        }//end two
      }//end one
    }//end function
    //**********************END SERIAL FUNCTION**************************

I would like to know if this looks like it can work, or am I going about this all wrong?

(I don't have access to my Arduino currently to test the code)

Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.

Let's say your code has successfully read the first couple of bytes into NumberOfIncomingBytes. However, when it reaches begin two, let's imagine the sender hasn't finished sending all the data yet.

Your code will drop through to end two, discarding the NumberOfIncomingBytes value it just read. Next time round, it will start all over again from scratch, and attempt to read NumberOfIncomingBytes again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.

From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.

A way to fix it would be to store the NumberOfIncomingBytes value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of CheckSerialData(), the code should check that flag. If it's true, then it should skip trying to read NumberOfIncomingBytes. Instead, go straight on to begin two.

An alternative approach would be to avoid using NumberOfIncomingBytes at all. Each call to CheckSerialData() would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.


Error using Adafruit Feather M0 I am trying to upload an empty program on the Adafruit feather to see if it connects to my PC. So far, it isn't. I'm running a Windows 10 and I followed this guide:

https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500?view=all

But I get this error:

Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

And the PORT submenu is greyed out.

I found out the issue I was having, though I have a Gemma.

What worked for me:

Selecting the correct board under "Tools" -> "Board:" (in your case, the Adafruit Feather 32u4 is probably the one you want)
Selecting the "USBtinyISP" under "Tools" -> "Programmer:"

Then it was able to upload to the Gemma, after hitting it's reset button twice to get it into a 'programming mode' (I don't know if the feather has such a feature).

If you are still having problems make sure that you have properly set up your arduino IDE for adafruit boards, and just play around with settings (try different programmers).

I don't know why it was so hard finding this info out, and why it is not more visible on the documentation to set these things up. I think I found out the 'hitting reset twice' thing somewhere buried in a forum... I digress, but Adafruit does need to consolidate their documentation to make it clearer.

Hope this helps


DigiSpark attiny85 computer not detecting I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.
I am trying on a Windows 10 machine.
I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip
I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.
I tried different cables. I tried to install the drivers on another computer and the same thing happens.
What should I try next? Am I missing other drivers?

Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers.  You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't stay recognised or that it isn't recognized as a serial device.  If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.
I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is expected behaviour:

In addition remember the Digispark only shows up as a programmable
device for 5 seconds, after that it will start running its code (when
it is new and un-programmed this means it will blink) and disappear or
act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it would continually reconnect for 5 second intervals.  They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it.  But then you got this from ebay, so who knows what they did or did not put on it.  I haven't studied the micronucleous bootloader enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed.  If it is unprogrammed then it is probably nop-sliding, for lack of a more appropriate term, right back into the bootloader.
You're not going to see it recognized as a serial port device like a typical Arduino.  The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.
Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch.  After which it should blink the LED.  If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.


Built-In Digital Map for Robot Driving So, I'm creating this project for school. It's a simple robot with Arduino MEGA 2560 and basically, I create a digital map, feed it into the Arduino program and then the robot can drive. However, I've run into some problems while trying to implement my idea. Parsing errors mostly. And I want to know if there is another and different approach.

So, basically at the moment, this is how my digital map works:

Using C# and Visual Studio IDE I've created a program with which I can create the map. Basically, I create connections(lines/roads) and the connection has a starting and end point, a median point and a label(what it is). So, each connection info token is something like this:

"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"

"Connection[x1: 13, y1: 0|x2: 13, y2: 28|xm: 13, ym: 14|label: library]"

Now, I have figured out a way to import this information into Arduino, and I've stored the information into a class object I created. Now, the difficulty I'm experiencing is how am I going to drive the robot from one point to another, store the robot's position and go to any point in the map when asked to.

Edit:

As for the implementation and storage of the map, it's like this:

So, I have a class Vertex. It basically the equivalent of a point and store (x, y) values.

class Vertex {
  public:
    int x;
    int y;

    Vertex(int _x, int _y) {
       x = _x;
       y = _y;
    }
};

Then there's the connection class. It stores the starting vertex, the end vertex, the median vertex and the label(string). It's like this:

class Connection {
  Vertex v1();
  Vertex v2();
  Vertex median();
  String label;

  public:
    Connection(Vertex _v1, Vertex _v2, Vertex _median, String _label) {
        v1() =  Vertex(_v1.x, _v1.y);
        v2() =  Vertex(_v2.x, _v2.y);
        median() = Vertex(_median.x, _median.y);
        String label = _label;
  }
};

And, finally, there's the map class where the user passes in the info tokens produced by my map creating application made in Visual Studio and it works like this:

#include "Connection.h"

class Map {
  public:
    Map(string infoTokens[]) {
      //I import the info tokens here.
    }

    void drawMap(MCUFRIEND_kbv tft, String ) {
      //This is a totally different function, it is just for drawing the map
        on top of the TFT screen that I have on my robot.
    }

    void driveTo(Vertex rP, String destinationLabel) {
      //This is where I drive my robot when the user requests to go to a
        destination and provides the label.
    }
};

As for the importing of the info tokens(the map information) I just do some String Manipulation on, for example, this
"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"
and get back all the info in the required data types. As for the importing it doesn't really change anything because I have tested my function(not present here) a lot of times and it works brilliantly. My question is how to use that information to hopefully drive the robot.

You were able to create a custom data structure from your string, but it seems, that the connections, that are stored in the Map class, are not connected. So the map does not really represent the structure of the "street" net. I would propose a different approach:

Instead of defining connections you can define the nodes of your net (where 2 or more streets meet). For each node you save the position (x, y) (or an instance of your vertex class), a label (like "library") and an array of pointers to other node objects. In code this may look like this (I left the methods out):

class Node {
    Vertex pos;
    char label[25];
    Node *connections[6];
}

Excursion: If you don't know, what pointers are in C/C++, here a short introduction. You should definitely read more about it on the web.

A pointer variable contains the address of another variable in the RAM. You can change this address and let the pointer point to another variable. A variable is marked as pointer with a * at the declaration. You can get the address of a variable (to set the pointer to this variable) through the & operator: pointer = &variable . If you dereference a pointer (by writing a * before the pointer name), you can work with the value, that the pointer points to. Each pointer variable has a type. It is the type of the object, that it points to. The pointer declaration int *var let's var point to int variables. If the type is a class or struct and you want to access members of the target (where it points to), you can use the shortened version pointer->member.

You define each node and add pointers to other nodes to represent connections. To traverse through the map, you need a start node. You save the address of the current node in a pointer. Then you can use it to access the connections of the current node. To actually go to the next node, you would set your pointer to the value saved in one of the connections elements, because that are pointers to the connected nodes.

The robot can then be moved along the straight lines between 2 nodes. When you want to also have non-straight, you can also do that by defining a middle point. You just to define the geometrical form, that the line should take.

The Map class can contain an array of Nodes. You can loop through all nodes in the array, if you need to, or you can traverse through the net by using the pointers.

The actual algorithm to find the path with the smallest travel distance is a big out of scope here. Doing that efficiently can be a complex task. You can research these algorithms on the web. The easiest way is to test all different paths in your program (without actually moving the robot), save the needed distance for each path and then choose the path based on that. You would need to write a termination condition, so that no connected will be taken twice on the same path (which would mean some kind of loop). Also keep in mind, that this will need more and more computation time, as your net grows. If it stays small and you don't need very fast computation, it might stay sufficient. If your implementation is recursive, you also have to consider, that each recursion takes up memory on the stack. You don't want to get out of memory.

Speaking of memory: In your implementation you use String for the label and you might want to use dynamic memory allocation for your map. That is not a good idea, because it can make swiss cheese out of your heap memory (heap fragmentation). It is better to define a fixed array, that can hold the maximal number of elements (as I have done with the connection of a node). The not needed elements can be set to something meaningless (for the connections you can use the null pointer and for unused nodes simply only null pointer connections).


Array, hexadecimal and serial write I am trying to write a pice of code which send to a receiver the frequency to listen.
As per its documentation, it should receive the following sequence:

Example with 123.456 MHz
Command to send (frequency converted in 4 bytes, followed by 2 instruction bytes
0x12 0x23 0x56 0x00 0x01

To be able to memorize six frequencies, I fill an array:
uint32_t mem_freq[6] = {
   0x121050,
   0x126500,
   0x120500,
   0x121700,
   0x121825,
   0x118700,
};

My concern is that when I do :
Serial.write(mem_freq[mem_index]);
//Serial.write(0x00);
//Serial.write(0x01);

Only 1 byte is sent, and it's hard to debug as the serial console displays only ascii characters.
When I use Serial.print instead, mem_freq[2] shows correctly 0x120500
After Majenko's answer, I tried this:
Serial.print(0x123456 >> 16,HEX);
Serial.print(0x123456 >> 8,HEX);
Serial.print(0x123456,HEX);
Serial.print(0x00,HEX);
Serial.print(0x01,HEX);

And it outputs:

12123412345601

Is this normal ?

You need to manually split your values into bytes. You can either do that by storing them as individual bytes (as shown by Ignacio), or by using bit shifting:

Serial.write(mem_freq[mem_index] >> 16);
Serial.write(mem_freq[mem_index] >> 8);
Serial.write(mem_freq[mem_index]);

That sends the bits 16-23 (0x12) then bits 8-15 (0x10) followed by bits 0-7 (0x50).


Arduino: How does digitalRead read a value? And what is this value? I have a Arduino Uno with 14 digital pins. I believe they have an output of 5V.
But they can also input values. I'm not sure of what exactly it reads when it does that (amperage, voltage ...). Also, how do they read it? How can such a tiny thing possibly know what it's receiving?

Just to provide a little more context to the reading part of this question, here's an example circuit. I have a 5V battery connected to an LED and a 220 Ohm resistor. Next thing in the circuit is a wire, which exits the main circuit and connects to a digital pin on the Arduino Uno (here it reads the value). Then the main circuit closes by connecting to ground.

Hope my question is clear enough :)

Modern digital electronics is made from many tiny electronic components called MOSFETs (a type of transistor). They can be switched on and off using a voltage, and a very small amount of current. They use the majority of the power when they are switching on and off; the rest of the time they use virtually no power. It this very low-power capability which allows us to make complex digital electronics.

Electronically, a MOSFET looks like a tiny capacitor, which triggers a very low-power switch, on and off. Once there is charge on the MOSFETs capacitor, the switch will stay on or off.

A modern large-scale processor, for example the type of device Intel makes, contains billions of MOSFETs, but requires less than 100W, and switches billions of times/second. So we can be confident that a MOSFET can be switched using much less than 1/10,000,000W. At 5V, that means 1/50,000,000A, or 0.000,000,02A, i.e. 0.02µA.

So, the input circuit, connected to an Arduino's pin has some protection, to protect the MOSFETs from static electricity (which could damage or destroy the capacitor), then a complementary pair of MOSFETs (called N-Chanel and P-Chanel). The input voltage switches one on, and the other off. It typically requires less than a micro-amp of current, but at a voltage close to ground or 5V. See pjc50's diagram.

So an Arduino input pin, connected to the 5V end of the resistor and LED will take a tiny amount of current, for a short time, to switch on.

If that pin is connected between the LED and resistor, at some voltage less than 5V, but more than 0V, then it might not switch fully. It might not give a reliable value of digital 0 or digital 1, and might switch high and low rapidly influenced by electrical noise in the environment.


How to decrease delay for String concatenation + Arduino Due In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?

#include <CStringBuilder.h>

int Max_pack_size = 100;

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

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}

I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.

This is the original code as you can see i can use only Max_pack_size of 5

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

The timer displays values around 2.08 milliseconds for the code above.

First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.

Note that when we generate String from long the implicit cast allocates char buf[2 + 3 * sizeof(long)]; so the max length of such string is 14 characters. String is of course terminated by null character '\0'

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!

Let's drop the String. It's just an over complicated wrapper for a char array anyway.

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.


delete[] crashes ESP32 (Bad tail error) Because I wanted to support both ESP32 and AVR based boards, I had to change from the things like std::string to an alternate method. I wanted to avoid the String class because I've heard that's a bit of a mess memory wise.
I decided to use char arrays and null terminated strings, and make sure to free them all myself.
From my app, over Bluetooth, I recieve data in the format <id>:<data>, where id is a two digit number (i.e. 01).
Once I receive data, I pass it on to this function, which does some processing:
void CDataUtils::process(char *data) {
    char *split = strtok(data, ":");
    m_id = static_cast<ActionID>(atoi(split));

    uint16_t len = strlen(data) - (strlen(split) + 1);
    char *d = new char[len + 1];

    strcpy(d, split + strlen(split) + 1);

    delete[] split;
    //......
    delete[] d;
}

I split the string with strtok, and use both side so I store that in a variable called split. I take the first section which is the id and cast it to an enum but that is irrelevant for this. I then calculate the length of the data after the colon and create a char array of that size (plus 1).
I then copy the data that comes after the colon into d. Once that is done, because I no longer need split, I free it with delete[]. This causes my ESP to crash though
CORRUPT HEAP: Bad tail at 0x3ffdc795. Expected 0xbaad5678 got 0xbaad5600
abort() was called at PC 0x40081d91 on core 1

ELF file SHA256: 0000000000000000

Backtrace: 0x4008e254:0x3ffc71f0 0x4008e4d1:0x3ffc7210 0x40081d91:0x3ffc7230 0x40081ebd:0x3ffc7260 0x400dd653:0x3ffc7280 0x400d8c65:0x3ffc7540 0x400d8bf4:0x3ffc7590 0x400931b5:0x3ffc75c0 0x400817f6:0x3ffc75e0 0x40081cd5:0x3ffc7600 0x4000bec7:0x3ffc7620 0x40104059:0x3ffc7640 0x400d1fa7:0x3ffc7660 0x400d1e9c:0x3ffc7680 0x400d1b0e:0x3ffc76a0 0x400d32e5:0x3ffc76c0 0x4008ffda:0x3ffc76e0

According to the first link when googling for CORRUPT HEAP: Bad tail, this is usually a sign of writing data outside of a buffer. Surely if that was the case here, the error would occur at the strcpy line, not at the delete line?
What confuses me is I have this little utility function that deletes and reallocates a new array:
char *_realloc_and_null_array(char *arr, uint16_t size)
{
    delete[] arr;         //Free array
    arr = new char[size]; //Create new one of specified length

    memset(arr, 0x00, size); //Fill with null

    return arr;
}

I used to use this in the process function above, and I did not get any errors with it even though I am freeing an array with delete[].
What have I done wrong?
EDIT: I'll reply to the comments here because there's a lot. I appreciate the info on strtok and how I don't need to work out the length of the data, or copy the data to any buffer.
The reason I was trying to delete the pointer to the split was because I didn't realise it was a pointer. I'm not sure how I thought it could be a string but I did/
In terms on the _realloc_and_null_array function it was purely to remove duplicate code. I got the snippet from an SO post but I can't remember the one. When I create a program (in any language) I don't like to just create variables all willy-nilly. In this instance, if I have an array d, I can use that for something, free it, create a new one and fill it with different data. This saves having another unnecessary array.
I re-use arrays a fair bit so it allows me to just create a new array with a different length and get rid of the old one (I don't do it a stupid amount as to where the program is hard to understand. I'll use the function at max once in some functions).
Maybe it's a dumb thing to do but it worked for me so I stuck with it.

Ok, so you have some misconceptions here:

strtok() will not create a new c-string/character array. It returns a pointer, which points to the place in data, where your current token begins. So dong delete[] on split does not make much sense. Also note, that strtok() will alter the c-string, that you give to it. So data will be altered, after the function executed. strtok() inserts a null character \0 at the place of the delimiter (: in this case. That way c-string functions can be provided with the pointer, that strtok()` returns, and will only read until the end of the token (since they look of the null character as end of string).

The String class is bad on Arduino (also on the ESP, but not in the same urgency), because they have very few memory for variables. The String class allocates its memory dynamically, everytime, that you do concat, assign or change the size of the string. That means, it creates and destroys arrays with different sizes rather often, which will lead to memory fragmentation. You will get small holes in your memory, which are too small for new allocations. With the time you will get more and more holes, until your memory is full. Then the Arduino crashes. Since Arduinos often have very few memory (and don't have an OS, that manages the RAM), that happens rather fast. The ESP has more memory, so it doesn't happen that fast, but the problem is still the same.
It is the same situation with every dynamic memory allocation. In the rare cases, where you don't get memory fragmentation, you can as easy use a local variable (managed automatically on the stack for you).

In this instance, if I have an array d, I can use that for something, free it, create a new one and fill it with different data. This saves having another unnecessary array.

Actually: No, not really. The array d is created somewhere at the start of the process() function and deleted at the end of it. Just like a local variable (statically allocated). The only benefit here is, that d can have a variable size (not know at compile time). Though that can also create problems with the dynamic allocation, as described above (depends on if you are doing dynamic allocation in between of the allocation and deletion).

The _realloc_and_null_array() function makes only sense, when the size is different from the size of the provided array. But then again you can run into the issue described above.

I don't like to just create variables all willy-nilly.

What do you mean with "willy-nilly"? You are only creating variables, that you really need. But that doesn't mean, that these variables cannot be statically allocated. A common misconception, that programmers coming from bigger platforms (like PCs) often have, is that you should keep the memory footprint as low as possible, thus using dynamic allocation to free resources, that aren't currently needed. On a PC the freed memory can be used by other programs running on it. But on an Arduino there is only one program running. Memory, that you don't use, will just be doing nothing. So keeping the memory footprint is important, when you are actually running out of memory for your program, but not important, when you still have enough memory. As dynamic memory allocation comes with big caveats on these platforms, it is mostly not really worth it.

All in all: Dynamic memory allocation comes with huge caveats. You cannot just use it like on a PC. If you still can use it depends on your code and your requirements (like on code runtime, before it gets unstable). There are situations, where you can get away with it, and others, where you don't.


In system programming for avr? I generally use sockets for AVRs in standalone circuits, but sometimes I sell my items and therefore I soldier the chip on the circuit. As you guess I can upgrade the code inside the chip with socket simply putting the chip out and putting it into the programmer board, but It doesn't work the same way with the ones which are soldiered on the circuit.

I know there are some ISP devices like USBtinyISP etc., but I want to be more professional and know exactly how an in system programmer work.

Do I have to use Avrdude If I design my own In system programmer? Isn't there any way that is more universal?

I searched the internet for a long time and I found only hobbyist stuff. Can anyone explain or simply direct me to a good source that explains this topic? Thank you in advance.

ISP works by using a serial connection (usually via the SPI and nRESET pins) to the MCU. The programmer talks to the device using the low-level protocol that the device expects, and connects to the host using a different, high-level protocol. The host then directs the programmer to perform the various programming actions on the device, and in turn the programmer reports to the host about its current status.

There are a number of programming protocols that already exist, such as the one described in AVR910. As long as both the connection type and the protocol itself are supported by AVRDUDE it will work transparently once the hardware is assembled.

Further details about ISP are available in both AVR910 as well as the "Serial Programming" section of the datasheet for the device in question.


Sensor that detects when metal sieve is clogged with debris I'm a newbie here and would really appreciate all kinds of suggestions and answers from the experts here.
I am trying to make a small grey water recycling system project, and for the my primary filtration process tank, I will be using a combination of Metal Sieve and Cloth filter medium.
The problem is, I will be making the system alert the user when filters are in need of changing and maintenance.

I made a quick sketch of my idea on paint, and as you can see, I am planning to make my grey water collection tank to look that way.
I am thinking of using pressure sensor to sense the change of weight in the sieve and cloth part of the tank for a minimum amount of time so that the system will not confuse water flow weight vs. the weight of the debris on the metal sieve, but I'm thinking that the pressure sensor is not waterproof.
I'm also thinking of like the laser module, and when the light breaks at certain level, meaning there is too much debris that has to be removed.
I also googled load cells or weight sensors, but I'm really sorry I'm new to this, I don't know what is the best sensor to use for my problem.
I'm thinking of a float switch a few inches on top of my metal sieve and cloth and when it does not go on a OFF state for a certain amount if time, then the sieve is clogged, but my tank could overflow..
I need something that, when the sieve is clogged, the tank will no longer accept grey water input to avoid overflow.
It has to be submersible in water too :'(
Is there a type of sensor that is most suitable for my problem?
Thank you so much everyone. Have a nice day.

I would tackle this not from the point of view of the filter, but from the point of view of the water itself.
The water will be impeded by the filter. As the filter gradually clogs that impediment will increase.  The net result will be a slower flow of water through your filter.
There's a number of things you could do to detect that:

Measure the incoming water flow rate and the outgoing water flow rate and calculate the difference.

This would mean having all the water flowing through two flow meters which would complicate your design as the filter will no longer be able to deposit directly into the tank. But when the difference in flow between the in and out sensors gets above a certain point (to be determined by you) then you can safely say that the filter is blocked.

Measure the "backlog" of water. To do this the input portion of the filter will have to be sealed (or largely sealed). Again the filter will impede water flow, and the more it's clogged the more it impedes. Once the impediment becomes too high the water will start "backing up" up the input pipe as it can't get through the filter fast enough. At this time you can detect that rise in water level with a float switch.

You'd have a simpler design now, as the filter can deposit straight into the tank. Whether you want to detect the rise in water level in the incoming pipe itself or in the gap between the filter and where the pipe comes in depends largely on the size of your filter. With a large filter it may be better to have a smaller space at the top and measure in the pipe. That will "amplify" the level rise and make it easier to detect.


What’s the most common (and low cost) microprocessor with at least two threads? I want to make a next version of my current project. I’m hoping to use an Arduino compatible processor that also supports at least 2 processes simultaneously without using pro threading or any other software workaround. The more commonly used the processor is, the better the user support will be if something goes wrong.

ESP32.  Dual core 240MHz, plus an extra XLP state machine.  Cheap and easily available on eBay/Amazon/Ali Express etc.  And with full Arduino support.


Arduino Uno still boots and runs but no serial communication over USB After having the Arduino Uno running for a short period of time, it seems to no longer communicate over the USB port when connected to the computer. It still seems to turn on and run the program uploaded. However, it no longer receives or outputs any data and any attempts to re-upload code are met with timeout errors in the Arduino IDE. The TX/RX lights do not blink at all, but the "L" light always flashes right after the Arduino is plugged in.

I have the Arduino/Genuino Uno board selected in the Arduino IDE.

This is a legitimate board that I bought directly from Arduino.

Loopback test fails.

Nothing is connected to any of the pins on the Arduino whatsoever.

I have an Arduino Nano that communicates fine with my Windows 10 PC so that rules out the drivers and the PC itself.

My computer still recognizes the USB device as an Arduino Uno and assigns it to COM5.

Leaving it plugged in for a solid 15 minutes shows no chips on the board getting hot to the touch.

I have tried resetting the board before, during, and after attempting to upload code, no dice.

Are there other steps that I can take to try to fix the board, or am I going to have to accept that I fried the ATMEL16 chip on my Uno?

As @Juraj mentioned, if it's enumerating as a serial port, the atmega16u2 is fine.

You may be able to replace the atmega328p/au. It will take some doing; you'll need to remove the chip, insert a new one, and use another Arduino as an ArduinoISP to program the bootloader into your new blank atmega328p.

Any chance you might have uploaded a sketch that is spamming the serial port on startup? If so, try this procedure (h/t to the Arduino forums, it has saved my bacon a number of times):

Disconnect the usb connection
Begin holding the Reset button
Connect the Arduino
Initiate upload (while still holding Reset continuously)
As soon as you see the RX light flash, release the Reset button.
The first attempt to upload will fail, but with luck, the second try will occur before the 2-second bootloader delay ends (and your sketch begins to execute).

If this works, I'd suggest including a delay(3000); or similar in your setup().


DigiKeyboard - type a backslash (\) I'm using digiKeyboard library to type to a powershell, but I need to type a backslash (a lot of them), but I can't figure it out.

I have been looking for the solution for about 3 hours and I still can't find it.
Please let me know how to make a backslash work.

The powershell command that I want to execute:

cmd /C "start /MIN powershell iwr -Uri https://tinyurl.com/WjnAU6 -OutFile c:\windows\temp\b.jpg;sp 'HKCU:Control Panel\Desktop' WallPaper 'c:\windows\temp\b.jpg';$a=1;do{RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True;sleep 1}while($a++-le59)"

It just changes the wallpaper with a downloaded image, try in on your friend.

To include \ in a string so it can be printed you have to escape it.  \ is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.

So to print "c:\windows" you would actually have to type "c:\\windows" and the \\ gets changed by the compiler into just \


ESP8266 - One server sending data to multiple clients I have a few arduinos with ESPs, one of which is set up to measure temperature, and I'd like to have it send commands to other connected arduinos to perform various functions (open/close valves etc.)

In other words, the only communication I need is for one server to hopefully broadcast to a few clients. I don't really need to discern which client is which.

I am struggling to make sense of some of the documentation, and this is new to me.

For starters, I'm just trying to get any communication at all functional before I do the next parts.

My server device is set up as a soft access point and a WiFiServer.

My server ESP code looks a little something like this.

#include <ESP8266WiFi.h>

const byte ON = 2;
const byte OFF = 1;
int message;

WiFiServer server(80);

void setup()
{
  Serial.begin(9600);
  WiFi.softAP("access", "point");
  server.begin();
}

void loop()
{
    server.write(ON);
    delay(1000);
    server.write(OFF);
    delay(1000);
  }
}

My client code looks a little something like this:

#include <ESP8266WiFi.h>

const byte ON = 2;
const byte OFF = 1;

byte ip[] = {192, 168, 4, 1};
WiFiClient client;

int message;

void setup() {
  Serial.begin(9600);
  // connect to wifi.
  WiFi.mode(WIFI_STA);
  WiFi.begin("access", "point");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  //Now connect to server object
  if (client.connect(ip, 80) == 1) {
    Serial.println("Connected");
  } else {
    Serial.println("Not Connected");
  }
  delay(10000);

}

void loop() {
  if (client.connected()) {
    Serial.println("Waiting for Data");
    while(!client.available()){}
    String message = client.read();
    Serial.println(message);
  }
}

The client code does connect to the server, and get stuck at the "Waiting for Data" line, never getting out of the while (!client.available) loop, so it clearly isn't receiving anything.

I'm sure I must look super dumb here, can someone help me understand the proper way to do what I want to do? Stuff I have seen online is primarily client -> server communication, do I HAVE to ping the server with something in order to receive something back?

Any help is appreciated. This is for a big project and I hope that I can make it all work. Thank you all very much!

Your server doesn't handle clients. It is only a listening TCP socket. You must handle incoming TCP connections by checking if the server has a client available.

This is from ChatServer example. A telnet server to connect to with telnet terminal.

void loop() {
  // wait for a new client:
  WiFiClient client = server.available();

  // when the client sends the first byte, say hello:
  if (client) {
    if (client.connected()) {
      if (!alreadyConnected) {
        Serial.println("We have a new client");
        client.println("Hello, client!");
        alreadyConnected = true;
      }

      if (client.available() > 0) {
        // read the byte incoming from the client:
        char c = client.read();
        // echo the byte back to the client:
        client.write(c);
        // echo the byte to the server as well:
        Serial.write(c);
      }
    } else {
      alreadyConnected = false;
      client.disconnect();
    }
  }
}


Varying motor speed with the L293D Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.

Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.

Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..

int Speed = analogRead(speedChange);
int SpeedMap = map(Speed,0,1023,0,255);
analogWrite(enable1, SpeedMap);
analogWrite(enable2, SpeedMap);

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

Although I am still figuring things out, but i hope the following things help:

http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf

The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.

Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).


Arduino Nano + RC522 + w5500 Ethernet Module has anyone had any experience wiring up an arduino nano with an RC522 RFID module and a W5500 ethernet module? i can get each of them to work individually, but i cannot get them to work together. i am not super experienced, but this seems to be some sort of SPI collision

The RobotDyn Ethernet Module i am using:

The RFID Module i am using:

If both modules use SPI then they should each have a separate pin connected to the slave select.

This lets you select which module you are talking to every time you start a communication. If the modules are well behaved then its MISO pin will be in high impedance when it is not selected instead of pulling it low or high trying to send data.

If it is not well behaved then you will need to add a buffer.


Mac won't detect Serial Port for Leonardo EDIT: The problem was the cable I was using (see answer below).

I have a MacBook Pro running OS X Yosemite (10.10.1). I connected my Arduino Leonardo to my computer for the first time today (using a Micro USB to USB cable), but my computer isn't detecting it.

When I opened the Arduino IDE I selected Tools > Board > "Arduino Leonardo", but when I try to choose a Serial Port the only options are:

/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

I have tried closing and relaunching the Arduino IDE, disconnecting and reconnecting my Arduino Leonardo, and restarting my computer, but I still only see the four Bluetooth ports.

System Information (aka System Profiler) doesn't show anything connected to any of my USB ports.

Thanks in advance!

@IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.


Make LED blink using AVR assembly I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?

; DDRB       = 0x04
; PORTB      = 0x05
; TCCROB     = 0x25
; TCNT0      = 0x26
; 0b00000000 = OFF
; 0b00100000 = ON

setup:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x04, r16           ; Set DDRB to output
    out 0x05, r16           ; Set PORTB to ON
    ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
    out 0x25, r16           ; Set the TCCROB to 1024
    ldi r20, 0              ; Reset r20
    ldi r21, 1              ; Hold value 1 to increment r20
loop:
    in r17, 0x26            ; Read the timer
    cpi r17, 128            ; Check to see if the timer is halfway done (1/2 second, max 255 value)
    brbc 0, increment       ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
    rjmp loop
increment:
    adc r20, r21            ; Add r21 (1) to r20 (with carry)
    brbs 0, reset           ; If the carry branch is set, reset the register
    rjmp loop               ; Otherwise, run the clock
reset:
    ldi r20, 0              ; Reset the delay register
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.

That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.

Some of the following items might make it easier to debug the problem:

• Instead of brbc 0,..., say brcc ...
• Instead of brbs 0,..., say brcs ...
• Instead of brbs 1,..., say breq ...

That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.

• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after cpi r17, 128) with cpi r17, 0 followed by a breq, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.

• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.

• Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace

    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

with

    eor   r18, r16          ; Toggle LED bit
    out   PORTB, r18        ; Set the LED to the new state
    rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:

    ldi r16, 0b00100000     ; bit mask for LED pin
    mov r18, r16


"port" is greyed out in 1.6.13, running win 10 for an Uno R3 I am new to this, and my kid got an Elegoo smart robot car kit v2.0 for Christmas. We assembled the car, but after downloading the software, the program always states:

  Arduino: 1.6.13 (Windows Store 1.6.13.0) (Windows 10), Board: "Arduino/Genuino Uno"

  Sketch uses 2,242 bytes (6%) of program storage space. Maximum is 32,256 bytes.

  Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes.
  avrdude: ser_open(): can't open device "\.\COM1": The system cannot find the file specified.

  Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

I don't know what other information is important. Can somebody please help me?

Thank you.

When the port is greyed out its not available (I know you had worked that out) so you have a problem with you serial to USB drivers.

Looking at the kit I think you are connecting the UNO to a USB port on your PC/laptop using a blue cable.
 1. Please can you check that the cable is connected properly.
 2. Can you try a different USB port on the PC (don't use a USB hub - some don't work).
 3. Does Windows recognise a device has been plugged?
 4. Are you running it as administrator, you will need to be to install the drivers.
 5. Can you try connecting it to a different PC?

If these don't fix it then, please comment and well go through looking at the device manager.

Hope it works, it looks like fun.


ESP32 Alexa Integration; Cannot correctly control more than one device I created a garage door opener recently that is controllable through Alexa, using this library: https://github.com/Aircoookie/Espalexa

Everything is operating as expected, meaning I was able to detect my device and control the garage (using routines).

The issue came when I went to integrate Alexa into another previously completed/operational project. I was able to successfully discover and control the second board, kind of.

At this point I have added two ESP32 boards to Alexa, named differently of course. When I went to test the second board(meaning that it was successully discovered, and the ESP was receiving most commands) I noticed that Alexa was also opening my garage. If i unplugged my garage door opener(first board to be added) the second board starts to all receive commands, although degraded; for example;

In the above noted library Alexa should be able to control 'brightness' of dimmable lights. Of course this device is not a dimmable light but for the purposes of the integration, this library emulates smart lights. I am never able to see Alexa trying to set a brightness whose value is not 0.

Example, this is successfully executed on board 2, sometimes only when board 1 is unplugged:

void alexa_change_hdmi(EspalexaDevice* d) {
    Serial.println("Executing");
    uint8_t brightness = d->getValue();
    Serial.println(brightness);
    doing more things....

Here, brightness is always printed as 0.

So, after I added board X to alexa and tested successfully, I added board Y to alexa. Board X receives both commands for X and Y most of the time. Vice versa if board Y is the only device on. This is not intended by design. I would like to control them separately(preferably through the use of one alexa device).

I'm not sure if this (^) is related to the inability of Alexa to tell the two distinct board apart. I'm not sure why i'm not getting a brightness level, I would like to use it to make decisions, example;

if (brightness == '2.55') {
unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
}

Has anyone seen this issue integrating several ESP32 devices with one Amazon Echo? Has anyone ever gotten brightness to successfully pass into the function that alexa triggers?

EDIT*

After doing some more testing it appears that ESPALEXAWITHASYNCWEBSERVER is causing Alexa to not be able to differentiate between the distinct boards. This implies that if you want to use more than one device with this library, you cannot use the async example.

As a side effect, brightness always returns 0 when not using the async library, meaning you can really only use this library to control on and off state, not brightness, if you have more than one ESP device. ASYNC example correctly returns brightness, all other examples return 0, no matter what you set the brightness to.

Try this library , in past i have used 5 device at a time

fauxmoesp


using millis() for a timer Basically the user presses a button and cycles thru 3 different modes. Mode 1 the LED is on, mode 2 the LED is off and mode 3 the LED is kept on for a certain amount of time. I'm using the millis() to keep track of the time. the LED in the third mode just stays on and never switches to off. I have the Serial.Writes in there to help me debug. I have the delay after the button read since if I didnt put it in it would register a lot of button presses.

int ledPin = 5;
int buttonApin = 9;
int ledMode = 0;

boolean lastButton = HIGH;
boolean currentAButton = HIGH;

// debounce button
boolean debounceFUNC(boolean last)
{
    boolean current = digitalRead(buttonApin);
    if (last != current)
    {
        delay(5);
        current = digitalRead(buttonApin);
    }
    return current;
}

void setMode(int ledMode)
{
    // turns on led
    if (ledMode == 1)
    {
        digitalWrite(ledPin, HIGH);
    }
    // turns off led
    if (ledMode == 2)
    {
    digitalWrite(ledPin, LOW);
    }
    // timer - turns off after 5000
    if (ledMode == 3)
    {
        long interval = 5000;
        unsigned long cMillis = millis();
        static unsigned long pMillis;

        if (cMillis - pMillis > interval)
        {
        pMillis = cMillis;
        digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
        }
        else
        {
        digitalWrite(ledPin, LOW);
        Serial.println("Off");
        }

        }
    }

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    pinMode(buttonApin, INPUT_PULLUP);
}

void loop()
{
    // sets led mode
    currentAButton = debounceFUNC(lastButton);
    delay(500);
    if (currentAButton == LOW)
    {
        ledMode++;
        Serial.println(ledMode);
    }
    else if (ledMode > 3)
    {
        ledMode = 0;
    }
    // ledMode function call
    setMode(ledMode);
}

screenshot of the serial monitor.

The problem is in the logic, basically your statement:

    if (cMillis - pMillis > interval)
    {
       pMillis = cMillis;
       digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
    }
    else
    {
       digitalWrite(ledPin, LOW);
       Serial.println("Off");
    }

will always be true, this is as the difference in time, cMillis - pMillis is always greater than interval.

This means that it never enters the else statement to turn off the LED, and thus means the else statement is usually the first thing that rune at ledMode = 3.

What you need to do as the simplest fix is to change your comparison, change > to <, in the is statement:

if (cMillis - pMillis > interval)

to

if (cMillis - pMillis < interval)

this will ensure the LED is always on during the 5000 mS and then as soon as it is greater it will definitely go to the else


What is the purpose of '&' while passing bool as a function parameter If I use this function without & before change_x (in function parameter), change_x never changes to false and it keeps on printing forever. Why do I need &?

void some_function(bool &change_x, int pin_x) {
 if (change_x == true) {
 delay(time_delay);
 if (digitalRead(pocket_pin_1) == HIGH) {
  Serial.print("State 1");
  }

 else {
  Serial.println("state 2");
 }
 change_x = false;
 }
}

If you have a boolean b you normally assign it to true or false. If you pass in a function a boolean (or integer, char and most other simple types), a copy is made. So if you change it in the function, when the function returns, the copy is destroyed and the original value is kept.

However, you do not want a copy, so you need a reference (pointer) to that boolean. That is where the & is for. So bool &change is not a boolean, but a reference to a boolean. Whenever you change that reference, the original value of the boolean is changed, which is what you want.

Note, this is a C++ feature, it does not exist in C (there you use pointers instead: bool* change).


AnalogWrite custom voltage I want to get a low voltage on output pin of Arduino mega. I have connected Pin 46 to A3, and wrote 120 value to 46 port. Expected was to get 2-3v on A3 input pin. Instead I always get 1023 values as input. Am I doing something wrong ?

void setup(){
  Serial.begin(9600);
  pinMode(46, OUTPUT);
  pinMode(A3,INPUT);
  }

void loop(){
  analogWrite(46,120);
  Serial.println(analogRead(A3));
  }

The analog outputs aren't real analog outputs, they are PWM.

That means that they rapidly switch from OFF to ON and back to OFF again.  The analog value is the ration of OFF time to ON time, known as the Duty Cycle.

You can convert that rapid switching to a real voltage by passing the signal through a low pass filter.  The simplest form is the RC filter:


Networking Multiple Arduinos -- Is It "Rocket Science?" Have a set of Arduinos that need to swap data--for a model rocket launch controller!
How to send 24 bits of info (launch commands) from a "master" Arduino, 12 bits each to two "slave" Arduinos that are 15' to 150' away from the "master.
Each "slave" needs to send 12 bits of info (continuity statii) to the "master."
"Master" <--- 15' to 115' ---> "Slave 1" <--- 10' to 35' --> "Slave 2"
Seems too long for I2C?

The best solution would be to use an RS485 adapter connected to each Arduino via serial port. This is a tried and true solution that is perfect for a setup like this and only costs a few bucks of extra hardware per node.
If you can't use additional hardware, you can also create a poor-man's current loop system like RS485 using normal Arduino pins since they are capable of sourcing and sinking 20mA.
With either of these solutions, you can send however much data as you want as long as you have some kind of minimal protocol to serialize it into a sequence of bits on the wire. To send 12 bits, you might just define a start condition as an idle "0" on the wire for a certain period of time, followed by a "1" start bit, followed by you 12 data bits, followed  maybe a parity bit or a checksum, and completed by a "1" stop bit.
Check out how, say RS232 or RS485 serialize bits to get an idea of how this works. If you end up using hardware that only supports sending data in 8 bit chunks, then you could, say, send two bytes per data "packet" where each byte has 6 bits of your data, plus one bit that indicates if ths byte is the first group of 6 bits or the second group, and then one bit of parity for error checking.


nRF24L01 - leaves out end characters during transmission This is my Master's code.

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8);

const byte address[6] = "00001";
char text[20] = "";
int flag;
char *p;
int i;

void print();
void read();
void rfwrite();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

  flag = 0;
  p = text;
}

void loop() {

  if (Serial.available()) {
    read();

  }
  if (flag) {
    print();
    rfwrite();

  }

}

void print() {
  Serial.println(text);
  flag = 0;
}

void read() {
  p = &text[0];
  for (i = 0; Serial.available(); p++, i++) {
    *p = Serial.read();
  }
  text[i + 1] = '\0';
  flag = 1;
}

void rfwrite() {

  radio.startWrite(text, strlen(text)+1);

}

Slave code:

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //ce,csn

const byte address[6] = "00001";
char text[20] = "";
int  i;

void write_to_array();
void print();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  while (radio.available()) {

    write_to_array();
    print();

  }

}

void write_to_array() {
  radio.read(text, strlen(text)+1);

}

void print() {
  Serial.println(text);

}

I edited the code and made it with an array like @Kwasmich said. But now some end characters are not getting printed. When I type 1234567890-= into the transmitter, only 1234567890- gets printed. When I type a new set of characters following that, the missing = gets printed. Also, this happens only on the second transmission after I upload the code to the Arduino. The first set of characters are received and printed correctly. How do I fix this? Will flushing the buffer help(I doubt this because the first transmission is received correctly)?

This is not a proper solution explaining why the issue occurred in the first place but merely a workaround to anyone encountering the same problem.

There is another function in the RF24 library called startWriting(). The description in the library was not clear about the differences between this and write(). But I noticed that the last character was missing with the use of startWriting(). So I simply changed

radio.read(&text, sizeof(text));

in the master to

 radio.read(&text, sizeof(text+1));

and voila!
The code now does its intended purpose!!


Arduino controlled light dimmer software I found this software:

/*

AC Voltage dimmer with Zero cross detection
Author: Charith Fernanado   http://www.inmojo.com

Adapted by DIY_bloke
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table
(the Pin numbers are digital pins, NOT physical pins:
digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)
check:   http://www.inmojo.com

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All -But it is INT1 on the Leonardo
3      |  1            |  All -But it is INT0 on the Leonardo
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only
0      |  0            |  Leonardo
1      |  3            |  Leonardo
7      |  4            |  Leonardo
The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin.

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
                 // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  for (int i=5; i <= 128; i++){
    dimming=i;
    delay(10);
   }
}

But don't uderstand this part:

  (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

I know 10000us is 10ms, and we need to wait less then 10ms to dim light.

But don't understand why here we has -10us and /128.

Anyone know why is that?

-10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.


Why does Arduino Due Native Port change serial ports after every reset? (Linux) Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button.

For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?

I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports.

It happens because of Linux, not because of the Arduino.
Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created.
Just close the port before resetting the DUE and you will see that after the reset it will have the same one.

You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.

To make your program more robust, you should listen for kernel events and open the port accordingly.


Arduino UNO serial send and receive issue I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?

You need a common ground between the Arduino and the PIC. Connect both grounds one to each other.


How to get neopixel to fade colorwipe? I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.

#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
void setup() {
  strip.begin();
}

void loop() {
  colorWipe(strip.Color(255, 255, 255), 150); // Red
 colorWipe(strip.Color(0, 0, 0), 150); // Red
 delay(5000);
}

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

You could change the intensity of each colour in steps till you get to your target colour.

void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
  for(uint16_t i = 0; i < strip.numPixels(); i++) {
      uint8_t curr_r, curr_g, curr_b;
      uint32_t curr_col = strip.getPixelColor(i); // get the current colour
      curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

      while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
        if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
        if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
        if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
        strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
        strip.show();
        // delay(wait);  // add a delay if its too fast
      }
      delay(1000);
  }
}

To use it:

void loop() {
  colorFade(255, 0, 0, 150); // fade into red
  colorFade(255, 255, 255, 150); // and then into white
  delay(5000);
}

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.


Will this AC-DC converter chip really work with arduino? I am looking for a compact solution to convert some 220V/20amp AC to something edible by our arduinos (like 5V/2amp DC). I would like to plug directly my arduino to the wall. I found many things like some Hi-link (HLK-PM01) chips ... But I also found this one :

LNK564DN - US $0.34 / piece
LNK564DN - US $1.14 / piece

That seems perfect, but unfortunatly, I can not find any tuto or example of use for this, shipping included, really cheap chip.

The datasheet is here.

What do you think about it ?

What do you think about it ?

If you have to ask, don't do it. Mains voltage can be dangerous and should only be done if you know what you are doing and how to be safe. The best choice is to just use pre-built adapters from reputable sources.