connecting 5 mq sensor at a time I want to take a reading from 5 different mq sensor at a time. do I need an external power source to power these sensors or it will be ok to power sensors from 5v available from the board? I am using arduino uno board .

I only had experience with the MQ2 sensor (more info here), so I'm going to use it as an example. If you have different sensors double check their datasheets.

Now, the main current consumption for these comes from the heater. Can you turn the heater off to save some power? Apparently not, since they say that

  Please note that the best preheat time for the sensor is above 24
  hours.

So, for the moment, let's consider all five sensors turned on at the same time.

The heater specs say that its resistance is around 33 ohm +/- 5% in the worst case this means 31.35 ohms. At 5V, this means 160mA for each sensor. Five of them are 800mA, and then let's add something like 50mA for the rest of the circuit (just a random number, and highly depends on the rest of the circuit).

Now, how is the UNO powered? If it is powered from the USB, the maximum current you can draw is 500mA (so 850mA is not allowed). So.. No powering from USB. If, on the other hand, the board is powered by the barrel jack, the onboard regulator can dissipate roughly 1-1.5W (taken from this thread). The power dissipation comes from the input voltage. With a 9V input, about 3V (slightly more) will need to be handled by the regulator. At 850mA, this means 2.5W (Not ok). In both cases you will need an external 5V power supply. With a 7V input (the very minimum you can apply) you will have to dissipate roughly 1.2V, at 850mA this means 1.02W. Please beware that this means something like 80-90°C of temperature increase in that area, so the part will become very hot. And moreover its lifespan will be reduced. So use this path only if really necessary.

If you reduce the performances and start powering just one sensor at a time (this means longer time before having it fully operational, and adding some transistor to switch them on and off) this data can change. I mean, if put a transistor to stop powering it, and then turn on one sensor at a time, you will be able to reduce the maximum current consumption to 210mA.

This means that you will be able to get power from the USB port; moreover you will be able to use the external power connector for voltages up to 10.5V (0.8V on the diode, so 4.7V on the regulator - around 1W). This comes at a price, of course: the heater will work for 1/5 of the time, so it will be harder to reach the temperature required for the measurement


Script stops functioning after calling irsend() function in irlibrary! I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.

/*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

IRsend irsend;

decode_results results;

int intValue;
String strValue;
String str3;

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

void loop() {
  if (irrecv.decode(&results)) {
    intValue = results.value;

    Serial.print("Integer value : ");
    Serial.println(intValue);

    strValue = String(intValue);
    Serial.print("String str : ");
    Serial.println(strValue);

    Serial.print("Length : ");
    Serial.print(strValue.length());
    Serial.println();

    if(strValue.length() <= 1){
      str3 += strValue;
      Serial.println(str3);
       // Receive the next value
   }

    delay(200);
    irrecv.resume();
  }
  //Serial.println(str3);
  if(str3.endsWith("770")){
    powerOff();
    str3 = "";
  }
  else if(str3.endsWith("769")){
    powerOff();
    str3 = "";
  }

  else{}
  //powerOff();
}

void powerOff(){
    irsend.sendRC6( 0xC0000C, 24);
    irrecv.resume(); // Receive the next value
}

Apparently you should be calling irrecv.enableIRIn() after sending, not irrecv.resume(). Sorry for suggesting the wrong thing on IRC before :-)


PCF8583 with Arduino delay of one second? I'm trying to interface the RTC chip : PCF8583 with Arduino Uno. I'm using exactly the circuit shown below except instead of the variable capacitor near the crystal oscillator, I've used a 22pF ceramic capacitor.

For the programming side, I've used the Arduino PCF8583 library

The code I'm using is the following :

#include <Wire.h> // necessary, or the application won't build properly
#include <stdio.h>
#include <PCF8583.h>

/*
*  read/write serial interface to PCF8583 RTC via I2C interface
*
*  Arduino analog input 5 - I2C SCL (PCF8583 pin 6)
*  Arduino analog input 4 - I2C SDA (PCF8583 pin 5)
*
*  You can set the type by sending it YYMMddhhmmss;
*  the semicolon on the end tells it you're done...
*
*/

int correct_address = 0;
PCF8583 p (0xA0);
void setup(void){
 Serial.begin(9600);
 Serial.print("booting...");
 Serial.println(" done");
}

void loop(void){
 if(Serial.available() > 0){
   p.year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48)) + 2000;
   p.month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.day = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
   // Use of (byte) type casting and ascii math to achieve result.

   if(Serial.read() == ';'){
     Serial.println("setting date");
     p.set_time();
   }
 }

 p.get_time();
 char time[50];
 sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d",
  p.year, p.month, p.day, p.hour, p.minute, p.second);
 Serial.println(time);
 delay(3000);
}

When setting the time and date, everything went ok, but when getting date/time the result is always HALF the period of the elapsed time, for example if I set the time 10:30 and I check it after 30 MINUTES, I get 10:45 instead of 11:00.

I really don't know if this is a hardware or software issue. If anybody has any idea about this issue, that would be highly appreciable !

Thanks in advance !

Check your schematic vs the datasheet and make sure that it makes sense.
Check to make sure that your input is right. You can print it back right away, or set the etc to a known good time and see if it keeps time.
Check the library to make sure that it is good.


Minimum number of Pins to use for multiplexing LEDs whats the minimum number of pins to use when multiplexing 6 LEDs?

is there some kind of formula that can be applied to n LEDs?

Or in other words, how many LEDs can an Arduino Uno control without the help of a separate IC?

It depends on the style of multiplexing.

For basic Row-Column multiplexing you have N=RC - the number of LEDs is the number of rows multiplied by the number of columns. The LEDs, of course, don't have to be arranged physically in rows and columns, those are purely logical wiring concepts.

For Charlieplexing (used by the LOL shield) it's slightly more complex. The formula is: N = n² - n, where n is the number of pins, and N is the number of LEDs they can drive.

Charlieplexing can multiplex far more LEDs than traditional R/C multiplexing, but is harder to program for and wire up.


Millis timer question Trying to figure out how to do this in millis. So right now the code works just fine, plays mp3_play(2) while a push button is closed then plays mp3_play(1) when its open. Lets say I want mp3_play(2) to play while the push button closed but after 4 seconds if the button is still closed another audio file will be triggered to play. Cant figure that one out.
thanks
Jason
void fire(){

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW) {
        mp3_play (2);  // fire sound
      }

    }
  }
  lastButtonState = reading;
}

You have to keep track of time once a button is pressed (LOW). So buttonLowTime is initialized every time you press the button. In the if logic, you first check if the buttonstate is LOW and if the said time has been passed.
But you also mentioned you want to play the audio once. So you need to keep track if you already played the audio. So, a flag, timeoutAudioPlayed has been created to keep track of that. So, now, the 3rd audio will only play if:

The button is pressed
and is pressed for more than said time (BUTTON_LOW_TIME_MAX)
and if the audio hasn't been played.

void fire()
{
  static int buttonLowTime = 0; <-------------------
  static bool timeoutAudioPlayed = true; <---------

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW)
      {
        mp3_play (2);  // fire sound
        buttonLowTime = millis(); <-----------
        timeoutAudioPlayed = false; <---------
      }
    }
  }

  // The logic for timeout audio <------------
  if((buttonState == LOW) && (millis() - buttonLowTime) > BUTTON_LOW_TIME_MAX && timeoutAudioPlayed == false)
  {
    mp3_play (3);
    timeoutAudioPlayed = true;
  }

  lastButtonState = reading;
}


How much code can an Arduino board run? I'm getting back up and running with microcontrollers after about 5 years of hibernation time, and I am trying to understand a lot of different things. I have been experimenting with Arduinos for the past few weeks and am having a ton of fun. I'm a software engineer by day and a hardware hacker / manufacturer by night. At my day job, I write scripts and applications that are thousands of lines long and highly complex, using external libraries of thousands more lines of code, etc. These are full-fledge, professional software applications.

So, here is my question. Is the Arduino capable of running full-fledged robotics and other large, complex hardware applications, or is it more of a tinkering, hobbyist tool?

How big of a project can be built using Arduino? Are there memory concerns? Can an Arduino run thousands and thousands of lines of code out of the box, and if not, is there a way to add more memory for larger, more complex projects?

There are several "Arduinos" with memory capacities ranging from slightly less than 32k/2k/16MHz (Flash/RAM/CPUClock) ("Uno") to 512k/96k/84MHz ("Due".)  In addition, there are "mostly compatible" boards that expand that range down to less than 8k/512/8MHz ("Gemma", "Digistump") and up to about 1M/256k/120MHz (TI "EK-TM4C1294XL Launchpad"), and "somewhat compatible" boards with 4G/1G/400MHz (Intel "Edison")

Whether these are sufficient for "full fledged robotics" depends on what you consider that to mean.  Edison is probably the only contender if you wanted to include computer vision, for example, and it probably doesn't do that very well. ("What did you expect at ONLY 1 core at 400MHz?!")

The small Arduinos probably do not support your "very large libraries", either.  For example, while the "Arduino Language" is technically C++, support for the C++ STL is not included due to limitations of the small CPUs used and their run-time environment.

32k of program memory (on the popular Uno) is sufficient for "thousands of lines of code", but I'd think robotics would tend to run toward much more than that.  The small amount of RAM available on most of the flash-based microcontrollers also tends to be a serious limitation when you start looking at standard data-intensive algorithms.  32k/2k disappears quite quickly if you start implementing an extensive user interface, networking, or graphics.  I would say that an Uno-class Arduino is suitable for implementing COMPONENTS of robotics systems (motor drivers, sensor management, etc), but probably not a whole robot.

A good example of large robotics-like software that runs on Arduino-class hardware can probably be found in the 3D Printer space.  "Marlin" firmware runs on an Arduino Mega or equivalent (256k/8k/16MHz) (with RAMPS shield), and there are alternative driver packages that run on smaller and larger arduino-like hardware.  Marlin is about 280k lines of code, according to cloc.

Most Arduino hardware does NOT have expandable memory.  The AVR cpus cannot run code except from their internal Flash, and few of the other boards have any sort of memory bus that could be used for expansion.


Store floats in and reading them from flash How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)

The storing part doesn't seem to be so difficult as this compiles:

PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

There is a helper macro in avr-libc that is designed just for this purpose:

#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space.

Use it like:

PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);


Arduino Bootloader availability When I look at arduino and arduino-like boards featuring ATMEGA328 chip, I see that they either use a micro controller or a FTDI chip to program the ATMEGA through Arduino board pin 0 and 1.

This only works because there is a bootloader available on the chip. Is the bootloader present by default or do I need to install it.
What I mean is can I just buy 10,000 ATMEGA328 from ATMEL, put them on boards and program them through UART or do I need to first flash them with a bootloader?

The bootloader is the feature supplied with the Arduino board, but not a chip itself. If you want to clone Arduino (fully or partially), you will have to burn the bootloader yourself.


How do I know if I have a short circuit I just got my first arduino starters kit so I'm a total noob in it. My simple LED blinker did work, afterwards I used a switch button with a debouncer script. It worked like I wanted but I wanted to try a buzzer instead of the LED, which did not work. Afterwards when I put the LED back in it didn't work anymore either.

The onboard LED does still work. Does this mean my breadboard had a short circuit? Is there any way I can know this for sure? And what exactly went wrong? Did I have to use a higher resistor?

I would highly recommend using a digital multimeter in this case. They are not too expensive and a must for electrical projects. Most have functions such as checking for shorts. In addition, you can check to see if the pin in question changes voltage when activated. The thing to remember is that heat kills electrical components, and high current causes heat (high power, really, but watch your current and you will be fine) get familiar with the formula v=I/R and don't put too much current through your buzzer or LED. LEDs have very little resistance.


Pause running program using a pushbutton I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?

Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?

Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.

Here's my code at the moment (sorry, it's not very clean):

int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}

The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.


How to read a PWM OUTPUT PIN value? How to get a pwm pin value that is in pinMode OUTPUT?

How to get a digital OUTPUT PIN value:

#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    digitalWrite(pin, HIGH);
    Serial.println(bitRead(PORTD,pin));
    delay(1000);
    digitalWrite(pin, LOW);
    Serial.println(bitRead(PORTD,pin));
}

For testing reasons, I want to get PWM output pin value.

Incorrect sketch:

#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    analogWrite(pin, 100);
    Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
}

This sketch was created for example only.
I don't know PWM value because PWM value will be generating dynamically.
Could you explain how to get a PWM output pin value, please?

According to the source code implementation of analogWrite function
(Arduino analogWrite source code explanation).

You can use OCRnx register for reading PWM value.


Posting TinyGPS++ co-ordinates as paramaters with GPRS I'm able to view my co-ords on the Serial Monitor using Serial.println(gps.location.lat(), 6);

I believe the data type returned by gps.location.lat() is double. I need to pass this value to a webservice with AT commands over GPRS.

double latitude = gps.location.lat()

Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.

gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude); < This is not allowed.

How can I pass this parameter to my web service.

One solution may be to split the commands:

gsm.print("latitude=");
gsm.println(latitude);

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like

gsm.print("latitude=");
gsm.print(latitude);
gsm.print("&longitude=");
gsm.println("longitude);

If I have the time I'll research into this a bit.

To check what is the problem, you may try to send "static" messages, like

gsm.println("latitude=12.345");

To check if this format is the correct one

EDIT: after a very quick research

It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

send the HTTPDATA command (the first parameter is the length of the payload)
wait for the board to send you the command DOWNLOAD
Send the body of the request, which is formatted as a JSON object. This means you have to send something like { "latitude" : 12.345, "longitude": 98.765 }

After all, it is much faster to use a library already developed for this, for instance ArduinoSIM800L (check a library available for your GPRS modem, or modify this one)


Control/Interacting with Android OS using Arduino board I am new to arduino, and based on my search, it is possible to connect Android devices and Arduino board thru bluetooth module. But most solutions i found are either for controlling Arduino board using an Android app, or controlling Android app using Arduino board.

My question is, is there a way to control/interact with the Android OS on the phone using Arduino, thru whatever connection?

I am asking this because I am thinking of building a portable keyboard or touchscreen device for Android devices, and want to see if Arduino is a good platform for prototype.

What you've seen is most usually a bluetooth module which has a "virtual COM port" service -- you connect to the bluetooth module and you can then send a data stream up and down through this COM port, just like you are able to do with a normal Serial port.

If you want a bluetooth keyboard:

What you want for seamless integration is a bluetooth module which natively exposes a "HID" (Human Interface Device) profile. Keyboard, mice and gamepads are examples of an HID.

There is a multitude of projects which use Arduino + Bluetooth HID module:

http://www.kobakant.at/DIY/?p=3310 uses an Arduino Pro Mini and and BlueSMiRF HID (from Sparkfun)
Evan Kale's video: https://www.youtube.com/watch?v=BBqsVKMYz1I (uses HC05 bluetooth module with altered firmware)
https://mitxela.com/projects/bluetooth_hid_gamepad
Bluefruit EZ-Key: https://www.adafruit.com/product/1535

When you are a beginner you should buy the more expensive modules which don't require you to do any firmware hacking. Adafruit's product might work for you. As the description page says, you can connect a microcontroller's UART TX to the modules RX pin to send arbitrary keystrokes. You can then add a keyboard matrix, or lots of buttons, or whatever you desire to that microcontroller to make it trigger the keypresses you want.

This should get you started on your own research.


Can RX pin(s) be used as TX instead? Title question. I do not need any receive communication pins, only transmission.

Actually, I need as many transmission pins as possible on any Arduino besides a Mega2560 (to re/write the EEPROM of slave devices). A Mega2560 has 23 TX/RX pin pairs.
Maybe I'm misunderstanding serial communication. And maybe some sort of multiplexing deal can work like One-Wire temperature sensors...such as softwareSerials[x].write()...

SoftwareSerial serialOne(2, 3); // Software Serial ONE
SoftwareSerial serialTwo(8, 9); // Software Serial TWO
                     // RX, TX

Is there a way to make all the pins using SoftwareSerial TX? Or do half need to be RX?

"Just take a better microcontroller, and that is all." - user1829200

What off-the-shelf microcontroller is geared for serial communication?

One way to communicate Arduino to Arduino device is UART (and Software Serial for additional pins). For the ESP32, it seems this allows 28 TX pins using Majenko's method (in their answer). In other words, slave 28 devices.
After further research, isn't I2C the clear route to go?

With more slave devices the less times per second to talk to them all
The application needs to have all the slave devices execute commands synchronously:

At least, the slave devices need to start functioning at the same time.

How many slave Uno's/Nano's can be connected to an ESP32?

Each device on an i2c network has a 7-bit address, so a single network theoretically supports up to 128 slave devices. In practice though, the limit is much lower. i2c slave chips often support only 8 different bus addresses, no more than 8 of that chip can be attached to the same i2c network.

https://mindbleach.com/words/2012/10/23/i2c-and-device-limits
Unclear answer:

https://forum.arduino.cc/index.php?topic=159860.0
https://forum.arduino.cc/index.php?topic=367961.0


Electret microphone board strange offset using Arduino I'm experimenting with an electret microphone, specifically this one.  I put it on my scope and I see what I expect - a really small voltage, typically under 20mV, that varies appropriately with sound.

However, when I put it into my Arduino (connecting signal pin to A0, V to 5V, and G to GND) and read it using analogRead on the appropriate pin, I end up getting a strange offset.  The analog read should read 0 more or less constantly, due to the low voltage coming out of the board.  However, I get an offset of around 425 counts on the ADC, implying that the voltage is somewhere around 2.5V.

What's going on?  Why would the arduino be reading a voltage when there isn't any?

An electret microphone is like a resistor which changes its value according to the sound.

To use it you must form a voltage divider with it, as if it were half of a potentiometer.

Thus you add a resistor to +5V (which is already on the board).  This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.

If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.

It's just like a potentiometer.  When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.

To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.

Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).


Send and receive text between Arduino Mega 2560 and C# via ENC28J60 I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

You can use TCP or UDP protocols.

https://www.arduino.cc/en/Tutorial/UDPSendReceiveString

https://www.arduino.cc/en/Tutorial/DhcpChatServer

You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.

For C# development:

https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

and

https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text


Using a SPI based ADC (ADE7912) with Arduino I'm trying to use Analog Devices' isolated ADC ADE7912 to build a native product for voltage and current sensing, using an Arduino as a microcontroller. The IC communicates with the Arduino using SPI (and SCK frequencies of 8,4,2 and 1 MHz), and I have followed the datasheet and written down some basic code using SPI-transactions and all, which seems to be giving correct results when I apply a positive voltage to the inputs of the ADC. I have two problems here:

When I try to display the SCLK, MISO and MOSI signals on an oscilloscope, the clock seems to have trouble maintaining its value (it becomes erratic and hence the SPI communication also misses some values etc.) Why is this happening?
When I apply a negative voltage to the ADC inputs, the IC does not really show any response to that even though it clearly supports negative voltage inputs to the ADC, as mentioned in the datasheet. This might be an IC related problem, but I am not sure.

Also, is there anyone who has built a library for this IC? Would be greatly obliged if they could share it.

I have not written a full library, but I have recently been using the ADE7913 (same as ADE7912 but with an extra voltage channel) with an Arduino MEGA.

The basic sketch located here talks to the ADE7913 over SPI, and then prints the results of the measurement registers over serial (so you can see them using a serial monitor).

I have not yet done much measurement testing, so can't comment on the negative voltage issue you have seen, but the sketch sets up the ADE7913 to use the V2WV register for monitoring temperature, and converts the result into degrees C, so you should be able to tell if its working properly.

In terms of the issues you have been having with the SPI comms, I can offer the following suggestions based on my troubleshooting experience (I also had glitchy comms initially):

I'm pretty new to SPI, but my interpretation of the data-sheet is that the ADE791X chips use SPI_MODE3 (i.e. SCLK is normally high, and samples are read on the trailing clock edge). I have found SPI_MODE1 also works, but unless others can correct me would suggest using 3.
I found having physically long jumper wires (my prototyping is still on a bread-board) caused issues. I have read elsewhere that at frequencies in the ones of MHz, distances less than tens of meters shouldn't be an issue; but I shortened / tidied my wiring and it seemed to help.
I would run everything at lowest possible speeds to troubleshoot, i.e. set the ADC sampling rate to 1kHz (set CONFIG bits 5:4 to 11), and set the SCLK at 250kHz.
In the attached sketch, I am reading the register values based on an interrupt from the CLKOUT\!DREADY pin. You have to be careful that this reading routine takes less than one ADC sampling time to read all the registers. There is a good explanation of this timing constraint in Figure 8 of this application note. The attached sketch also reports some timing information over serial to help with this.

Hope that helps,

Khalid.


Conver char value to variable? I want to pass the preprocessor values(AT commands) to the Serial.println function. Im trying TCP connection using arduino-SIM900A. I've declared all AT commands to each preprocessor variables like below

#define A "AT\r"
#define B "AT+CPIN?\"
...

I've assigned all preprocessor variables in char array and pass it into Serial.print using for loop.

char varAT[12]={'A','B'....};
for(int i=0;i<=12;i++)
{
Serial.print(varAT[i]);
}

Its not printing AT, instead it print preprocessor variable name A. I searched the google how to convert char value to variable, in C there is a function called "eval". Using eval we can acheive, but it wont work in arduino lang. How to solve this?

Thanks.

Ok, first, char varAT[12] indicates an array of 12 characters.

Second, quotes indicate literals - 'A' means, literally, the character 'A'. Variables and constants are without quotes (same way you use  i).

I think you mean:

char *varAT[12]={A,B....};

Also, your constant B is invalid - I think you meant for it to end in \r", not \".


It appears from the data you've posted, the remote is holding the presets for what the A/C unit needs to be doing when after every button is pressed.  This will keep the remote with LCD disply? in Sync with the A/C master.

Ie.  The remote is sending an entire setup string EVERY time ANY button is pressed.

Can you post a capture of an ON and OFF Raw's only?  Do not press any other buttons after pressing ON, or before pressing OFF.


Difference between char array and unsigned char array I have written a small test code for Arduino Uno which is as follows:
unsigned char tes[4];
char testing[4];

void setup() {
    Serial.begin(9600);
    for (int i = 0; i < 4; i++) {
        testing[i] = i;
        tes[i] = i;
    }
    for (int i = 0; i < 4; i++) {
        Serial.print("unsigned char is: ");
        Serial.println(tes[i]);
        Serial.print("char is: ");
        Serial.println(testing[i]);
    }
}

void loop() {
}

and the output which I get is as follows
unsigned char is: 0
char is:
unsigned char is: 1
char is:
unsigned char is: 2
char is:
unsigned char is: 3
char is:

Can someone help me out why is the difference in output.

tl;dr : Since unsigned char is represented as a byte value, the output to the serial is the byte representation, not the char
I re-wrote the code you had for reference:
#define CHARS 255
#define BAUD 115200

unsigned char unsChar[CHARS];
char sinChar[CHARS];

void setup() {
  Serial.begin(BAUD);
  Serial.println("~~Setup~~");
  for(int i = 0; i < CHARS; i++) {
    unsChar[i] = (unsigned char)i;
    sinChar[i] = (char)i;
  }
}

void loop() {
  Serial.println("~~Loop~~");
  for(int i = 0; i < CHARS; i++) {
    Serial.print("INDEX        : ");
    Serial.println(i);
    Serial.print("unsigned char: ");
    Serial.println(unsChar[i]);
    Serial.print("         char: ");
    Serial.println(sinChar[i]);
    Serial.println("---------------------");
  }
  delay(10000);
}

When you run this you'll see the unsigned char is simply printed to the serial like any other byte value but the char value is printed as a character according to the ASCII chart.
If you compare the documentation for unsigned char

An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.

The unsigned char datatype encodes numbers from 0 to 255.

For consistency of Arduino programming style, the byte data type is to be preferred.

versus a normal (signed) char:

A data type used to store a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See Serial.println reference for more on how characters are translated to numbers.The size of the char datatype is at least 8 bits. It’s recommended to only use char for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.

So size wise an array of chars and unsigned chars are going to be the same. It's more about the representation of the underlying number (byte) and what works best for your use case.


Reading Arduino serial stream in Java using jSerialComm I'm having issues reading the actual double values from my Arduino Serial.println() in my Java app. I've tried following usage examples found here but get what I guess is a hex value. The serial monitor within the Arduino program is displaying the correct values.

This is the code: I'm fairly new to this and would appreciate any comments regarding style/problems/inefficiencies within my code!

import com.fazecast.jSerialComm.*;
import java.util.*;
import java.io.*;

public class PortRead {
  public static SerialPort userPort;
  static InputStream in;

  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    /*
     This returns an array of commport addresses, not useful for the client
     but useful for iterating through to get an actual list of com parts available
    */
    SerialPort ports[] = SerialPort.getCommPorts();
    int i = 1;
    //User port selection
    System.out.println("COM Ports available on machine");
    for (SerialPort port : ports) {
      //iterator to pass through port array
      System.out.println(i++ + ": " + port.getSystemPortName()); //print windows com ports
    }
    System.out.println("Please select COM PORT: 'COM#'");
    SerialPort userPort = SerialPort.getCommPort(input.nextLine());

    //Initializing port
    userPort.openPort();
    if (userPort.isOpen()) {
    System.out.println("Port initialized!");
    //timeout not needed for event based reading
    //userPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
    } else {
    System.out.println("Port not available");
    return;
    }

    userPort.addDataListener(new SerialPortDataListener() {
      @Override
      public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
      }
      public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
        return;
        byte[] newData = new byte[userPort.bytesAvailable()];
        int numRead = userPort.readBytes(newData, newData.length);
        System.out.println("Read " + numRead + " bytes.");
      }
    });
  }
}

Since you are reading received data into array newData, you should replace System.out.println("Read " + numRead + " bytes."); with System.out.print(newData); (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.


What are these wires called? I'm currently developing a quad copter for my school project and I am coming to the part where I am collecting all the parts before I assemble everything.

I have recently encountered a roadblock. I am going to solder an Arduino nano onto a strip board, but the problem is I cannot seem to find cables/wires to connect the nano to the module.

Excuse my ignorance, but where can I find these cables for soldering and what are they called?

If they are an intentional part of the design they are jumper wires. If they are to correct a mistake in the design they are bodge wires.

They aren't anything special, just wire. They look to be in the range of 24 to 30 AWG and PVC jacketed.

You can buy it in any electronic store.

You can also salvage it from things like old SCART cables and similar things.


Java + JSSC + Arduino + Windows I want to know the basics of Arduino serial communications and connection with a Java application in Windows.

Can anybody provide me with a sample Java program that upon running just makes an Arduino pin high as well as the corresponding Arduino sketch, and some explanation on how the Arduino communicates with the Java app?

I am now starting with Arduino, and I have some experience with Java

I found this code on the net - will this work?

Java code

package arduino;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException {

    SerialPort serialPort = new SerialPort("COM3");
    try {
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("o".getBytes()));
        Thread.sleep(1000);
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("f".getBytes()));
        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
  }
}

Arduino

  void setup()   {
  Serial.begin(9600);
  pinMode(8, OUTPUT);
  digitalWrite(8,HIGH);
  delay(500);
  digitalWrite(8,LOW);
  }

  int incomingByte = 0;

  void loop()
  {
 // send data only when you receive data:
    if (Serial.available() > 0) {
           int text = Serial.read();
           Serial.println(text);
           if (text == 'o') {

            digitalWrite(8,HIGH);

           }

           if (text = 'f') {

            digitalWrite(8,LOW);

           }
     }

  }

I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).

The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:

comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

The last parameter is DTR and its default is true, the second to last parameter is RTS (it defaults to true too). I set both of these parameters to false and my board reads commands from the computer without resetting.

I write this for other people who had this problem.


Is there a way to set an interrupt to go off after a certain period of time? I'm trying to save power by putting my device to sleep once it has run through the code once and turn it back on every 33 milliseconds. So basically, if the code finishes executing in 20 milliseconds the device can go to sleep for the remaining 13 milliseconds and it will be turned on by the interupt which is set to go off every 33 milliseocnds.

According to the documentation an interrupt is based on a change to the pin state, but I'm sure there must be a way to base it on time. If there isn't then is there a way to set the total time that a device sleeps? The sleep function seemed to just turn the device off, but can it be given a parameter to just turn off for a certain amount of time?

The easiest way to achieve your purpose seems to be to configure a
timer to fire every 33 ms, and use this interrupt to wake up the
MCU. For this, you first have to choose what timer to use. On the Mega, I
would rather use the 16-bit timer, but the ATtiny85 only has 8-bit
timers. Next you have to choose a prescaler value (clock frequency
division) among those available for that timer. The prescaler should be
large enough to avoid overflowing your timer, but smaller prescaler
values give better time resolution.

Then you configure the timer to run in “CTC mode” (clear timer on
compare match). In this mode, it counts from zero to the value that you
programmed in the OCRxA register (where x is the number identifying
the timer), and then goes back to zero. This way you can get an
interrupt every OCRxA + 1 timer cycles.

In the example code below, you have to replace x with the appropriate
timer number, and check the datasheet for the bits to set in the control
registers TCCR*:

#include <avr/interrupt.h>

// Interrupt period, in prescaled clock cycles.
const uint16_t PERIOD = ...;  // or uint8_t for an 8-bit timer.

// The timer interrupt is used ONLY to wake the CPU, so there is no job
// to be done inside the interrupt service routine.
EMPTY_INTERRUPT(TIMERx_COMPA_vect);

void setup()
{
    // Disable Timer 0 interrupts.
    // Warning: this will prevent the Arduino from keeping time.
    TIMSK0 = 0;

    // Configure Timer x.
    TCCRxA = 0;            // undo the timer config done...
    TCCRxB = 0;            // ...by the Arduino core library
    TCNTx = 0;             // reset the timer
    OCRxA = PERIOD - 1;    // set the period
    TIMSKx = _BV(OCIExA);  // enable TIMERx_COMPA interrupt
    TCCRxA = ...;          // set the counting mode to CTC...
    TCCRxB = ...;          // ...and set the prescaler
}

void loop()
{
    // Sleep while waiting for the timer interrupt.
    sleep_mode();

    // Now that we have been waken up...
    do_the_job();
}

Edit: As noticed by Gerben, the Arduino core library configures
Timer 0 to send periodic interrupts (one every 1024 µs), which
are used for timekeeping (millis(), delay() and co.). This
interrupts will wake up the MCU and prevent it from sleeping as long as
you want. The simplest solution, which is implemented in the code above,
is to disable the Timer 0 interrupts. The drawback is that the
Arduino timekeeping functions will not work anymore.

If you need those timekeeping functions, then the proper solution is the
one sketched by Gerben in his comment: set a boolean in the interrupt
that can be checked in the main loop. Here is the naive implementation
of this idea: EMPTY_INTERRUPT(TIMERx_COMPA_vect); is replaced by

volatile bool time_elapsed;

ISR(TIMERx_COMPA_vect)
{
    time_elapsed = true;
}

Then, in the main loop you sleep repeatedly until the ISR sets the flag:

void loop()
{
    // Warning: race condition here!
    while (!time_elapsed)
        sleep_mode();
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

As stated in the comment, this naive implementation suffers from what is
known as a race condition. The problem is in the following scenario:

The main loop reads the value of time_elapsed and it turns out to
be false
At this point the interrupt fires and the ISR sets that boolean to
true
Returning from the ISR, the main loop does not test the flag again
(since it just did it) and goes straight to sleep_mode();.

At this point the MCU ends up sleeping although it should be performing
the job which is due now.

This race condition may not a be a big deal to you: The MCU will be
eventually woken up by the Timer 0 interrupt no more than 1024 µs
later. In some cases it is an issue, but fortunately there is a proper
solution. It is described in the page about sleeping of the avr-libc
documentation. It relies on the fact that when interrupts are
disabled, then enabled again with sei(), the machine instruction right
after the sei() is guaranteed to be executed before any interrupt is
serviced. Then the proper way to test the flag and sleep is:

void loop()
{
    while (!time_elapsed) {
        cli();
        if (!time_elapsed) {
            sleep_enable();
            sei();          // interrupts enabled
            sleep_cpu();    // this will be executed before any ISR
            sleep_disable();
        }
        sei();
    }
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

With this version, if the interrupt fires right after the test
if (!time_elapsed), it will be serviced after sleep_cpu(), which
will have the effect of waking the MCU right away.


Why does my LED turn off automatically after about 18 seconds on its own? I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:

#include <asf.h>
#include "pio.h"

// Define the LED pins
#define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
#define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
#define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
#define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
#define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

// Define the button pins
#define BUTTON_1 PIO_PC22
#define BUTTON_2 PIO_PC21

// Define function prototype for button interrupt
void button_press_handler(uint32_t, uint32_t);
void toggle_LED(uint32_t);

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init();

    // Initialize input/out
    ioport_init();
    pmc_enable_periph_clk(ID_PIOC);
    pmc_enable_periph_clk(ID_PIOB);

    // Set LED pins as outputs and set there default values (off)
    pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

    // Set button pins as pull-up inputs
    pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
    pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

    // Configure button input pin interrupt mode and handler (Falling Edge)
    pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
    pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

    // Enable the interrupts
    pio_enable_interrupt(PIOC, BUTTON_1);
    pio_enable_interrupt(PIOC, BUTTON_2);
    NVIC_EnableIRQ(PIOC_IRQn);

    while(1){
         // Doing stuff in here...
    }
}

Then this is my interrupt routine:

// Interrupt handler for button press
void button_press_handler(uint32_t a, uint32_t b)
{
    // Turn the LED's on or off
    toggle_LED(BLUE_LED2);
    toggle_LED(BLUE_LED3);
    toggle_LED(BLUE_LED4);
    toggle_LED(BLUE_LED5);
    toggle_LED(BLUE_LED6);
}

// Function to toggle LED on/off
void toggle_LED(uint32_t LED){

    if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
    pio_clear(PIOC, LED);
    else
    pio_set(PIOC, LED);
}

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:

pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?

Again, figured this out. I simply forgot to put in board_init(); Also, since board_init() already calls ioport_init(), I had to disable that.

Now I have this:

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init(); // Initialize the System Clock
    board_init();  // Initialize the board

....


WiFi problem on Mega + WiFi R3 ATmega2560 + ESP8266 I've got 2 "Mega + WiFi R3 ATmega2560 + ESP8266" (link) and both have same issue when trying to use the ESP chip.

Hope someone can point me toward something else to try in order to get them working properly.

Context

I'm able to flash the ESP chip using Arduino IDE or PlatformIO.
Dip switch need to be : 5, 6 and 7 ON to flash, and only 5 and 6 to debug through serial.

I've tried using different boards (Generic ESP8266 module, Wemos D1 R2 & mini, Node MCU) as well as different flash mode (DIO, QIO), crystal frequency (26 Mhz, 40 Mhz), CPU frequency (80 Mhz, 160 Mhz)

They all flash correctly without any error and I can get my serial output.

It's written ESP8266EX on the ESP chip. And I've tried with or without an antenna plugged on the board.

Problem

The problem I got on both of them is huge instability when using wifi. I cannot connect to them when they are in AP mode, they drop immediately.. And I cannot connect to or see my own wifi network from the Mega's ESP.

The same script and flashing config used on other ESPs devices work as expected (see [output other ESP board] below). I've tried on WeMos and NodeMCU devices.

But with the mega+wifi, it only see between 0 and 2 access point that are at a greater distance and weaker signal than my own wifi ([output mega+wifi] below).

Question

I don't have any clue on what can cause such a different result on device from same family (ESP/espressif). As if there was some sort of setting that need to be changed on those ESPs.

Any help or insight would be truly appreciated.

[code]

#include "ESP8266WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

[output other ESP board]

scandone
scan done
8 networks found
1: 412 Precondition Failed (-67)*
2: VIDEOTRON1547 (-90)*
3: BELL275 (-94)*
4: BELL558 (-72)*
5: C-PC_Network (-88)*
6: BELL387 (-90)*
7: EBOX-4229 (-94)*
8: VIDEOTRON6825 (-80)*

scan start
scandone
scan done
11 networks found
1: 412 Precondition Failed (-63)*
2: VIDEOTRON1547 (-88)*
3: BELL681 (-90)*
4: BELL275 (-90)*
5: VIDEOTRON0442 (-90)*
6: BELL558 (-71)*
7: BELL602 (-90)*
8: IKA COIFFURE (-90)*
9: C-PC_Network (-87)*
10: EBOX-4229 (-87)*
11: BELL387 (-90)*

scan start
scandone
scan done
7 networks found
1: 412 Precondition Failed (-65)*
2: BELL681 (-88)*
3: VIDEOTRON1547 (-88)*
4: EBOX-4229 (-88)*
5: BELL387 (-87)*
6: BELL558 (-71)*
7: dlink-Ares (-75)*

[output mega+wifi]

SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
bcn 0
del if1
usl
mode : sta(2c:3a:e8:26:36:13)
add if0
wifi evt: 8
Setup done
scan start
scandone
scan done
1 networks found
1: BELL558 (-69)*

scan start
scandone
scan done
1 networks found
1: BELL387 (-88)*

scan start
scandone
scan done
no networks found

scan start
scandone
scan done
1 networks found
1: BELL387 (-87)*

[erasing flash]

PS \tool-esptoolpy> python .\esptool.py -p COM10 erase_flash
esptool.py v2.3.1
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 14.2s
Hard resetting via RTS pin...

I had this problem. On Robotdyn D1 mini the esp8266 flash erase did help. On Robotdyn D1 R2 only the flashing of the AT firmware with Espressif Flash Download Tool restored the esp8266. After then the sketches from IDE had working WiFi.

There are some settings of the Espressif basic esp8266 libraries (SDK) saved on flash and there is some incompatibility between SDK versions. The Flash Download Tool creates right esp settings binary and flashes it to right address on flash.


Why is LED lid when pin is set low? I made this simple piece of code, to make my LED flash.. Which it does when the pin is set low.. But how does that makes sense?

#include "pins_arduino.h"

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

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

I am using the Wemos d1 - http://www.wemos.cc/

If the LED is ON when LOW and OFF when HIGH then chances are the LED is connected between +3.3V and the IO pin with a suitable resistor.

When HIGH the IO pin is at +3.3V, so the voltage across the LED is 0V (3.3 - 3.3 = 0) and it is turned off.  When LOW the IO pin is at (nearly) 0V and the voltage across the LED (and its resistor) is 3.3V (3.3 - 0 = 3.3), so it lights up.


I'm looking for a way to emulate addressable LED strip using LED diodes in a custom arrangement What I want to achieve is, I want to use my own LED pin diodes, customly place them into my sculpture and animate them. This is as I understand quite straightforward. The problem is the amount of wiring . I would want them to connect one another in series with addresses, rather then each led needing a direct data from the controller on a separate cable.
I know that addressable LEDs use a single data line through the all lights, eliminating the need to connect each led physically to the controller to get data. Is there any way to build a similar system with a bus-like structure, I believe it is possible. And if so, how? What would I need? I guess I need individual small chips for each LED, but I don't know if that's the case or even if it is how so.
I consider myself quite a newbie in electronics-arduino or LEDs, however I'm actively looking into it and researching.

You can buy individually addressable LEDs like the ones in LED strips. If you are fairly new to electronics I would not try to build your own serial LED controller.


Arduino Vin pin does not work, but Arduino 5v pin power works I have a very weird problem, at least it seems to me that way. I have connected L298N motor driver, Arduino and a hobby servo with a 6v power supply (tested with both 4xAA and 9v alkaline batteries). And wrote a simple program to rotate the servo every 10ms. There are no other motors connected as of yet.

Power supply is connected to the L298N 12v and GND.
Arduino is connected to the 5v and GND of L298N driver with the Vin and GND of Arduino respectively.
Servo's power (red wire) is connected to L298N 5v, GND is connected to the L298N's GND, and, servo's control (orange wire) is connected to pin 9 of Arduino.

The problem is that the servo hardly moves when Arduino gets power supply gets from the Vin input. However, if I connect it to the 5v of the Arduino power it works as expected. But I was under the impression that 5v pin of Arduino was to for the output and not for the input power supply. Could you guys please tell me what am I doing wrong here?

The Vin pin on the Arduino Uno board is connected to the input of the 5V onboard voltage regulator of the Arduino board.
This voltage regulator needs an input voltage that’s about 1.5V above its (regulated) 5V output that will feed the Arduino.
Arduino - note the recommended values of the Input Voltage (7-12V)
If you feed 5V into Vin, the voltage drop on the internal regulator will cause the Arduino board to be supplied with only about 3.5V, which is probably enough to make it function, but not enough to control the servos.
The solution, as you already found out, is to feed the 5V from the L298N board directly into the 5V pin of the Arduino. Please take care to measure the actual voltage from the L298N before you do this (it should be 5 Volts). Alternatively you could connect 12V to the Vin pin of the Arduino, but again, make sure you know what you’re doing.


Pros and Cons of using a non-pointer class object In this example I have an one object which uses a pointer and one object which does not.

class MyClass {
  public:
    void myMethod() {
      // do nothing
    }
};

MyClass* mc1;
MyClass mc2;

void setup() {
  mc1 = new MyClass();
}

void loop() {
  mc1->myMethod();
  mc2.myMethod();
}

Is one implementation better than the other? Why?

In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.

The static declaration (MyClass mc2) will reserve space in the BSS. The dynamic allocation (mc1 = new MyClass()) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).

The only trouble starts to come when you want to free (delete) the object created with new. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.

For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.


Arduino relay power supply question Hello everyone i got 2 ssr's from here

(link)

Sorry about the long link. My question is what power supply should i use. I was thinking a 12v 2amp. On a side note do i look at the input or the output when choosing a power supply

Thank you

In the product description it says "DC 12V 8-Channel Relay interface board, and each one needs 15-20mA Driver Current." So 8 times 0.020A is 0.160A per board. I think your 2 amp power supply should work just fine.


How to power my Arduino mini using wall socket? I am trying to power my Arduino Mini (which is connected to IR receiver and a relay board). The idea is to hide the entire setup behind the electrical board including the power supply. I have hacked more than a few power adapters (ranging from Mobile chargers 5-7V to 12 V adapters)

This is what I understand from what I have read so far about Arduino Mini power supply.

I can power directly using Vcc pin if I supply 5V DC regulated. (not recommended)
I can power Raw pin by using 5-12V DC and the onboard regulator will take care of converting it. 12V is the maximum, I should not use 12V it can fry the regular if used for a long period as the on-board regulator is a linear one, so a lot of heat.

This is what I understand from what I have tried so far about Arduino Mini power supply:

Don't connect power supply EVER to Vcc, it will harm the board. ALWAYS use Raw.
12 V supply = puff. instantaneously. No more on-board regulator. Now that Arduino Mini only works if I connect it using Vcc. (the charger was rated 12V 500mA)
Connecting 5V DC (300mA) is heating the regulator alot.

I have connected the Relay and IR receiver directly to the Arduino mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

The mini works with these 5V mobile chargers but the amount it heats up scares me.  Any suggestions on what I should do?

Also how much current consumption would be needed. I have tried using a 5V 300mA charger and 5V 700mA charger. Both work almost the same. Why?

I am a computer engineer and very new to Arduino.

Linking a similar question: Most compact method of powering Arduino from wall socket

I have connected the Relay and IR receiver directly to the Arduino
  mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

I hope you don't mean that you have connected the coils of the relays directly to the Arduino pins. If that's the case, the surprise won't be the regulator blowing up, but the MCU surviving. Please edit the post and add complete schematics and/or photos of your prototype.

  The mini works with these 5V mobile chargers but the amount it heats
  up scares me. Any suggestions on what I should do.?

Use a small heatsink if you're concerned about the regulator heating up. But it really shouldn't be a problem unless you're driving too much current from it. Have you actually measured the temperature it reaches?

Also, don't feed the coil through the regulator, but directly from the 5V adapter (presuming your relays are 5V). This will save a lot of dissipation in the regulator. NOTE: don't do this if you use a higher (> 5) voltage adapter!!

  Also how much current consumption would be needed. I have tried using
  a 5V 300mA charger and 5V 700mA charger. Both work almost the same.
  Why?

Those current ratings are maximum values, not constant values. So, if your circuit draws let's say 290 mA, both adapters will be able to do the job.

EDIT: additional information

To safely and properly use relays with arduino, you need some interfacing electronics like this:

Full article from the source, here. Flyback diode: 1N4148. You can use almost any "logic-level" N-channel MOSFET.

If you're using instead a relay module similar to the shown below, all the required interfacing electronics are already built into it and your digital pins won't suffer any overcurrent condition.

However, the regulator will (probably) still suffer from excessive current through it. In some of these relay modules you can optionally use a different power line (JD-VCC, see below) for the relay coil. If you own one of these, feed it directly from the 5V adapter, skipping the regulator.

If the relay module doesn't have a separate power line, it may still work when connected to the 5V adapter if the dropout in the regulator is not too big (i.e., the "high" level from the digital pins is not too far away from the adapter voltage).


millis() function with a button press I am trying to use the millis() function to turn on a pin for a specified interval then turn off and turn on a second pin. It is intended to power a relay and offer a visual cue to when the cycle is over. Several of these need to eventually be running, most likely three, so using delay() won't work. I plan to add additional "button pins" for each input. The LED lights up but gets stuck in the loop and doesn't cycle out. It seemed like a simple program but I can't crack it for some reason.

Is there a much better method to do this? There will be two optical sensors and one pushbutton switch attached to an air driven crushing machine. The two optical sensors will be used only as time indicators with LEDs and the pushbutton will power the relay. Forgive my shortcomings as a programmer, I am learning the programming language still.

const int ledPin =  2;      // the number of the LED pin
const int buttonPin = 3;    // Button pin number
// Variables will change:
long previousMillis = 0;        // will store last time LED was updated
int buttonState = 0;            // Checks if button is pushed
int buttonPush = 0;             // Toggles between 0 to hold state
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
// set the digital pin as output:
   pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
}
void loop()
{
   unsigned long currentMillis = millis();
   buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH) {
      buttonPush = 1;
      if (buttonPush == 1){
         if(currentMillis - previousMillis > interval) {
            previousMillis = millis();
            digitalWrite(ledPin, HIGH);
         }
         else {
            buttonPush = 0;
         }
      }
      else {
         digitalWrite(ledPin, LOW);
      }
   }
}

Edit: Thank you for looking over the code, you guys are awesome. There were a couple questions regarding clarity of the final application so I will elaborate. I am going to attempt to clean it up. I had a feeling something was wrong with:

if (buttonState == HIGH) {
   buttonPush = 1;

but I couldn't put my finger on it.

Eventually the system will function with two heating elements to soften plastic, which I will either add an optical sensor to since it will probably get triggered a few hundred times a day, or just a pushbutton to start a timer so the plastic isn't left in too long. A green LED will be illuminated to indicate the system is on. When the plastic object is placed in the heating element it triggers the optical sensor (or the operator pushes a pushbutton to start the timer) that will then illuminate a red LED to indicate heating. When the specified time interval has expired, the LED will revert back to green to show the cycle is complete. The plastic object is then removed and placed in a pneumatic crushing device with a green system on LED. The operator then pushes a pushbutton which turns on a red indicator LED and a relay to power the solenoid on the pneumatic press for a specified amount of time to allow the plastic to cool and crystallise. When that interval has expired, the system will revert back to illuminating the green LED and will end power to the relay allowing the press to release.

The pneumatic press and the heating system works awesome, I just need better control of the time intervals used. The end result needs to be consistent.

I am going to try all suggestions and will post what ended up working if I reach that point or find an answer that functions.

Some code is shown below to illustrate a method for treating three events independently.
This code might not be completely applicable as-is, because the problem description isn't clear about what should happen when a button is pressed and about whether other events to be added to the code are like the one shown there now.  However, if you understand how it works you probably can adjust it to meet any special requirements of your application.
During each pass through the loop() routine, the code does the following for each type of event:

If the event is not currently active (as denoted by states[i] < debounced), the code checks whether the event's button has been pressed (or, if its sensor has turned on).  If so, the code increments a debounce counter.  If the event's counter gets up to debounced, then the output for the event is turned on, and the event's end-time is stored in an array entry.
If the event is currently active (as denoted by states[i] >= debounced), the code tests if the event's end-time has arrived; if so, it turns off the event's output bit and resets its state to 0.

The last statement in loop() busy-waits until milliseconds() returns a different value than before.  This is done so that switch-debouncing samples are taken at least a millisecond apart.  If your inputs don't need debouncing, you can remove debounce code .
/* Process three asynchronous activities: Upon a given input going
true, activate its associated output(s) for specified lengths of time.
*/

enum { nkinds=3, debounced=5 }; // # of activity kinds;  debounce-criterion
const byte outPins[nkinds] = {2, 4, 6}; // Output pin numbers
const byte inPins[nkinds]  = {3, 5, 7}; // Input pin numbers
const unsigned int actLens[nkinds] = {345, 678, 323}; // Activity lengths, ms
byte states[nkinds] = {0, 0, 0};
unsigned long actEnds[nkinds] = {0, 0, 0};

void setup() {
// Set input/output modes of pins
  for (byte i=0; i<nkinds; ++i) {
    pinMode(outPins[i], OUTPUT);
    pinMode(inPins[i], INPUT);
  }
}

// Once per millisecond, for each kind of activity
// check for new beginning or deal with ongoing action
void loop() {
  unsigned long now = millis();
  for (byte i=0; i<nkinds; ++i) {
    if (states[i] < debounced) {  // Is activity off?
      // It's off, look for a turnon
      if (digitalRead(inPins[i])) {
        ++states[i];        // Button is closed at the moment
        // See if button has been debounced
        if (states[i] >= debounced) { // If so, start its action
          digitalWrite(outPins[i], HIGH);
          actEnds[i] = now + actLens[i];
        }
      }
      else {
        states[i] = 0;      // Button is not closed at moment
      }
    }
    else { // It's on, see if end-time has arrived
      if (now >= actEnds[i]) {
        digitalWrite(outPins[i], LOW); // Clear output when done
        states[i] = 0;        // Return to button-seeking state
      }
    }
  }
  while (now == millis()) {};       // Finish current millisecond
}

The code above compiles ok in the Arduino IDE but I haven't tested it on an Arduino device.
Note, larger systems with numerous events will use priority queues to implement lower-overhead versions of the same ideas.


Arduino with wifi shield and 5AA batteries current draw Arduino uno with official Wifi Shield take 5 Volts.
Arduino lights up as it should when powered but the WiFi shield is dead the l9 doesn't light up but works fine when arduino is connected to usb cable.

I use 5 battery holder 5x1.5V = 7.5 V ; 2000 mAH

50 mA - Arduino
300 mA - WiFi shield

350 mA * 5h = 1750 mAh

5xAA = 7.5V ; 2000 mAh

Am I missing here something? It should last in the worst case scenario 5 hours with new batteries at 2000 mAH (which I think they have more but I do not have them on me right now).

As a general answer, yes. AA alkaline should be more around 2500~3000 mAh depending on quality. 5x AA in series would result in 7.5 Volts and 2500 mAh.

But that's only for almost fully charged batteries. AA batteries can range from 1.6V to 0.8V "dead for most purposes". As they drain, the voltage drops.

What may be happening is that you are powering the Arduino through its power jack, which goes through a diode, causing a 0.7V drop. Then it goes to the linear regulator which has a very high drop out voltage. Or even via the VIN pin, bypassing the diode. But as the battery drains, the voltage drops below the regulator ' s limit.

The Arduino microcontroller can easily work below 5V. The shield might not.


Sublime Text 2 with stino, compilation gives "filename ... is incorrect" Arduino IDE 1.7.8 I can't compile a simple blink sketch.

Error is:

[Stino - Start building "t5"...]
[  3%] Creating C:\Users\lov\AppData\Local\Temp\Stino_build\t5\t5.ino.cpp.o...
The filename, directory name, or volume label syntax is incorrect.

See also see similar question, that answer not working here.

Path to IDE app is C:\Program Files (x86)\added\Arduino.

Sorry but this is too big for a comment.

Firstly please can you check the obvious, in Windows Explorer paste the path C:\Users\lov\AppData\Local\Temp\Stino_build\t5 into the address bar and does the directory exist. (I have fallen for that so many times)

Secondly do you have permission to create a file there?

Have you updated the IDE? Does blink compile?

Have you tried running the IDE as admin?

Hopefully one of those will fix it.


does EEPROM reset itself when a new code is uploaded? I have a Nodemcu with which i'm doing a project. So whenever there is a power loss i want values of some of the variables to not be reset, because of that im trying to store the values in EEPROM of the nodemcu. But the problem is i want to know if the EEPROM will get reset when a new code is uploaded and also since the nodemcu stores wifi credentials in the EEPROM i dont want to accedentally select an EEPROM address in which the wifi credentials are stored and cause a problem. Can anyone tell me the safe EEPROM addresses to use and also if EEPROM will get rest if  a new code is uploaded?

The esp family chips do not have EEPROM. Instead they just dedicate a small section of flash to pretend to be EEPROM.
That flash section, depending on the core version, is either a dedicated EEPROM partition, or a dedicated key in the nvram partition. Either way it's separate to the wi-fi credentials, which are stored in their own key in the nvram partition.
EEPROM can be erased when you upload code if the partition layout changes. It's less likely to be erased if it's a newer version of the core where it's stored in the nvram.
For safety, don't change the partition size, and ideally use ArduinoOTA which will never change the partitions or erase the nvram.


Getting "Undefined reference to vtable for {classname} I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:

CommandPattern3.cpp.o:In function `DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
collect2.exe*:error: ld returned 1 exit status

Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

I have been through the code with a fine toothed comb, but cannot see what references are undefined.

Is there some Windows 10 utility that can examine the vTables and help me find what is missing?

The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.

I don't have the header file for DualMotorRomeo, but the linker is saying that a destructor has been declared (~DualMotorRomeo()) in the class header, but no destructor has been defined. If you didn't write DualMotorRomeo then the library needs to be updated.

Until then, simply add the following to one of your source files:

DualMotorRomeo::~DualMotorRomeo() {
} // DualMotorRomeo::~DualMotorRomeo()

That will also fix the vtable linker errors - the vtable will be included in the compiled file with this declared in it.


XBee using Serial rather than SoftwareSerial--how to fix So I have a couple of XBee S2Cs, and I have configured them properly--they can in fact communicate with each other. I am using them with Arduino Unos and this shield: https://store.arduino.cc/usa/shield-xbee-without-rf. I am attempting to interface with the XBees with SoftwareSerial, but for whatever reason, they are instead using just regular Serial. Anything I put on the SoftwareSerial appears to be ignored entirely, while anything I put on Serial appears in my serial monitor and also is transmitted to the other XBee. I have this code for transmitting:

#include <SoftwareSerial.h>
SoftwareSerial xbee (2, 3);
void setup() {
    Serial.begin(9600);
    xbee.begin(9600);
}

void loop() {
    xbee.println("hello");
    Serial.println("world");
    delay(5000);
}

And this code for receiving:

#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3);

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

void loop() {
    if (xbee.available() > 0) {
        Serial.println("xbee: " + xbee.readString());
    }
    else {
        Serial.println("no xbee data");
    }

    if (Serial.available() > 0) {
        Serial.println("serial: " + Serial.readString());
    }
    else {
        Serial.println("no serial data");
    }
    delay(5000);
}

Every 5 seconds, I get this output through the serial monitor on the transmitting side:

world

and this on the receiving side:

no xbee data
serial: world

I also get the string world when I connect a third XBee to my XCTU console.

So I have a couple of questions:

First off--how is this happening? I'm no Arduino expert, but as far as I can tell from what I've read, if the XBee is capturing my serial output, then I shouldn't also be able to see it in the serial monitor.

Second off--how can I get the SoftwareSerial to work? I could theoretically just use Serial forever, but that would make debugging way more trouble, and would probably create a code-maintenance headache later. If I had to guess, I might need to use different pins for my shield, but I have no idea how to find out what pins are the right ones to use.

Update: Based on what I've seen and read, it looks like the particular combination of the Uno with this shield leaves me with no options but to use the hardware serial. A different shield or Arduino board would grant me options to separate my serial output from my xbee output, but that does not appear to be an option here.

You will need an xbee breakout board Xbee breakout board or this one from Sparkfun to do that...

Make sure you check if the board comes with headers as they are not always included. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the 2mm headers required for xbee and regular 0.1" headers required for connection to a breadboard or jumper wires etc.

Actually, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, but it is not connected to pins 0 and 1.

The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.

So on Leonardo, you can do Serial.println("Debug msgs"); and Serial1.println("xbee messages"); (note the digit 1 in Serial1). Of course other platforms such as Mega also can be used in the same way.

I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.

FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.

As soon as i moved to leonardo, it worked like a charm.


Allocation, initialization and scope I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?

Given these possible variations:

 const int c1 = 2, c2 = 7, c3 = 9;

 void functy();

 int foo[3] = {c1 | c2, c3, c2 | c3};

 static int foo[3] = {c1 | c2, c3, c2 | c3};

 const int foo[3] = {c1 | c2, c3, c2 | c3};

  ....

In case 1, foo is both allocated and initialized each call.

In case 2, foo is allocated only once, but is it initialized on each call?

In case 3 I assume that allocation and initialization are done only once? Is that true?

Here's a pretty definitive list for you:

// Allocated once in the global area and assigned during
// program startup
int foo = 1;

// May not even be allocated - the compiler will most likely
// optimise it out.
const int foo = 1;

// Allocated once and assigned during program startup. Cannot be
// accessed from outside the file.
static int foo = 1;

// The static here has no real effect.
static const int foo = 1;

void function() {
    // Allocated in the stack each call and initialised each call.
    // Only accessible from inside this function.
    int foo = 1;

    // Allocated in the global area and initialized on the first call
    // of the function. Only accessible from inside this function.
    static int foo = 1;

    // May not be allocated at all. Only accessible from inside
    // this function.
    const int foo = 1;
}

Note that non-simple const values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See PROGMEM in the Arduino Reference Manual for more information.


USB DEVICES WITH THE 32U4? I have an Arduino Pro micro and I need to know if it is possible to use an USB device like a camera or things like that Since the processor is a 32U4. the USB Shield is for the Arduino Uno and I don't want to buy more stuff.

Some important facts:

The 32U4 cannot act as a USB master, only a USB device (it doesn't have a USB OTG interface).
The USB shield is an SPI based device. It can communicate with any host MCU that can use SPI, as long as you can wire it in properly.
The Arduino doesn't have the processing power or memory to deal with the sheer onslaught of data a USB camera sends.

So yes, you could use the USB shield with a 32U4 based board if you can work out the right wiring. However you will not be able to use things like cameras with it since you lack the processing power to do it.

For camera work you need something more like a Raspberry Pi.


Using PWM pins on the UNO to generate Stereo Sound I am trying to generate stereo sound using an Arduino UNO. Instead of using a separate DAC chip (as shown here), can I use the PWM pins on the UNO along with a low-pass filter?
Also, would I need any additional circuitry if I go this path?

You can generate "stereo sound", but I don't think you'll like it.  The PWM frequency is only 490 or 980 Hz, which is going to be plainly audible unless you filter the output very severely.  So you'll only be able to produce low frequency sounds, about like what comes out of the woofer speakers in your home stereo.  In other words, nothing like music.  Might be OK for certain experiments, but nothing you'd want to listen to for pleasure.
As far as additional circuitry, you'll need to convert the DC outputs of your two low-pass filters to AC before you try to drive headphones.  This requires a big decoupling capacitor for each channel. If you are going to drive a separate amp, you might be able to skip the capacitors since most amps have them built into the inputs.


Arduino code not working properly (Please Help) I am having some trouble getting my board to perform the function I want it to perform. This is a project I have due in a few days, and I have hit a wall I just can't seem to get past. Now, I will say the issue is definitely in the way I coded the program, but I don't really know enough about Arduino (and coding) to understand why it is not working. My board is properly hooked up to use 3LEDs, a speaker, a photoresistor, and an ultrasonic sensor (detects distances). My Arduino program takes serial input from a GUI that I created in MATLAB. I have verified the MATLAB code is good, and the serial port is communicating properly. I have made an alarm that goes off when light or motion is detected. It has 3 basic functions:

Set the alarm
Turn off the alarm
"snooze" which just delays for 5 minutes and then the alarm goes off

The snooze and turn off alarm parts of my code are working great, but the set alarm is where I am having trouble. The snooze option sets off the yellow LED to verify it is on "snooze". The red LED comes on when the alarm is currently going off. The green LED comes on when the alarm is set. When I try to activate the "Set Alarm" function, which is case 'O' in a switch case, the light does come on, but the sensors are not picking up any input as far as I can tell. Again I have verified the pins and everything are set up correctly as I have isolated those and verified they work. I have a suspicion that the problem is because I have the sensors initialed within the switch case of the "Set Alarm" (case 'O', not 0). I don't really know how to get the sensors to run continually within that switch case until the "turn alarm off" case is activated. I need the sensors to be activated/reset by "Set Alarm" case.
**I am also new to this forum so please let me know if I am missing anything!
here is my code:

void setup()
{
  Serial.begin(115200);
  pinMode(12,OUTPUT); //RED
  pinMode(13,OUTPUT); //GREEN
  pinMode(14,OUTPUT); //YELLOW
  pinMode(16,OUTPUT); //SPEAKER
  pinMode(4,INPUT); //Echo
  pinMode(2,OUTPUT); //Trig
}

void loop()
{
 if(Serial.available() >0)
 {
 char b = Serial.read();

  switch(b)
  {
    //Turn Alarm off
    case 'A' :
    {
    digitalWrite(12,LOW);//red off
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    noTone(16);
    delay(500);
    }
    break;

    // Set alarm
    case 'O' :
    {
      int light;
  light = analogRead(0);
  unsigned long distance;
    digitalWrite(2,LOW);
  delayMicroseconds(2);
  digitalWrite(2,HIGH);
  delayMicroseconds(10);
  digitalWrite(2,LOW);
  distance = pulseIn(4,HIGH);
  distance = distance/58; //centimeters
  delay(500);

    digitalWrite(12,LOW); //red off
    digitalWrite(14,LOW); //yellow off
    digitalWrite(13,HIGH); //green on

  if (light < 400)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

  if (distance < 50)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

    }
    break;

    // snooze option
    case 'Z' :
    {
    digitalWrite(14,HIGH); //yellow on
    digitalWrite(12,LOW); //red off
    digitalWrite(13,LOW); // green off
    noTone(16);
    delay(300000UL);
    digitalWrite(12,HIGH); //red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }
    break;
   }

  }
}

Any help would be very much appreciated!

The problem is that, if you enter 'O', you go thorugh the set alarm case only once. If no alarm was triggered, it just falls through the if statements and is then back in the main loop. In that main loop, you only check for your sensors, if something was entered to the serial console. That means if you do not enter anything during a loop, nothing happens.
The solution to this would be to implement a finite state machine.
That means you use a state variable for the switch case. You then update your state based on the state and the external conditions. In your case you can just update the state using user input.
I changed your code a bit for a possible (but bad) implementation. I did not verify or check for errors. I recommend using a more solid implementation, if you plan to build upon this code for more complex behavior.
char state = 'A'; //initialize state in Off state
char b;          // make user input variable global
void setup()
{
  Serial.begin(115200);
  pinMode(12, OUTPUT); //RED
  pinMode(13, OUTPUT); //GREEN
  pinMode(14, OUTPUT); //YELLOW
  pinMode(16, OUTPUT); //SPEAKER
  pinMode(4, INPUT); //Echo
  pinMode(2, OUTPUT); //Trig
}

void loop()
{
  if (Serial.available() > 0)
  {
    b = Serial.read();
  }
  // close user input section

  switch (state) // run switch case every loop
  {
    //Turn Alarm off
    case 'A' :
      {
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        noTone(16);

        delay(500);
      }
      break;

    // Set alarm
    case 'O' :
      {
        int light;
        light = analogRead(0);
        unsigned long distance;
        digitalWrite(2, LOW);
        delayMicroseconds(2);
        digitalWrite(2, HIGH);
        delayMicroseconds(10);
        digitalWrite(2, LOW);
        distance = pulseIn(4, HIGH);
        distance = distance / 58; //centimeters
        delay(500);

        digitalWrite(12, LOW); //red off
        digitalWrite(14, LOW); //yellow off
        digitalWrite(13, HIGH); //green on

        if (light < 400)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

        if (distance < 50)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

      }
      break;

    // snooze option
    case 'Z' :
      {
        digitalWrite(14, HIGH); //yellow on
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        noTone(16);
        delay(300000UL);
        digitalWrite(12, HIGH); //red on
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        tone(16, 832);
        delay(500);
      }
      break;
  }

  state = b; // update state based on input

}


I2C communication between arduino and raspberry pi breaks under stress for unclear reasons. Why? I am having a behavior I cannot explain while using arduino mega as a I2C slave for a raspberry pi master.

I am showing here an idealised program that shows the issue. I experience pretty much the same behavior in the real application (a keyboard firmware). What I am doing is the following:

the arduino issues an interrupt on pin 23 at evert loop to inform the raspi that there's some data to be read.
the raspi sends a request as master to the arduino.
arduino receives the request in the Wire handler, and issues a reply of 32 bytes. I fill these 32 bytes with a uint8 counter just as a check.
the cycle starts again.

This is the code for the raspi

import time
import RPi.GPIO as GPIO
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

bus = smbus.SMBus(1)
address = 0x42

def callback(channel):
    data = bus.read_i2c_block_data(address, 0x00, 32)
    print(data)

GPIO.add_event_detect(4, GPIO.RISING, callback=callback)

while True:
    time.sleep(1)

GPIO.cleanup()

and this is the code of the arduino

#include <Wire.h>

byte IRQ_PIN = 23;

volatile unsigned int counter;

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

    pinMode(IRQ_PIN, OUTPUT);
    digitalWrite(IRQ_PIN, LOW);
    Wire.begin(0x42);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveData);

}

void signalMaster() {
  noInterrupts();
  irq();
  interrupts();
}

void irq() {
  digitalWrite(IRQ_PIN, HIGH);
  digitalWrite(IRQ_PIN, LOW);
}

void requestEvent() {
  byte buf[32];
  counter++;
  memset(buf, counter, 32*sizeof(byte));
  Wire.write(buf, 32);
}

void receiveData(int byteCount){
  while(Wire.available()) {
    Wire.read();
  }
}

void loop() {
  signalMaster();
  delay(1);
}

As you can see, the point is that I am banging the I2C really, really fast, and the loop is very tight and fast. This is the point of the exercise and the problem to solve arises from this.

Now, once in a while I get an occasional IO error with the raspi python code. This code occasionally fails once, and then everything resumes to normal, but once in a while, it completely breaks down and never recover.

I attached a logic analyser to it, and this is what I found. D3 is the interrupt pin. The others the I2C bus. In a normal transaction, I can see everything working properly (disregard the different content of the response, it was an earlier run)

and a zoom in to the master request and the reply:

When I have a permanent failure, however, the picture is very different

Zoom in:

This makes little sense to me. Why would it perform a data write, and who is writing 0x85FF... in my buffer?

Thanks

Use a logic level conversion IC.

picture source http://msx-elektronika.pl/en/logic-level-converter


options for wireless data broadcasting to hundreds of nodes I would like to build approx 100 arduino devices that can talk to each other, I have a set of constraints that I'm looking to get some insight on :

all devices would operate within a 300 meter proximity of each other
the devices each need to broadcast some data (their speed and
orientation from a gyro) to the rest of the devices in the group for
storage
They need to update each other roughly every 500ms/1s
Some of the devices need to be added and removed from the pool regularly
The devices need to start broadcasting their data to the rest of the
devices in the pool immediately when added (<1s delay)
The spectrum needs to be public & unlicensed

Which method of communication would you recommend? For the range, it seems like a 433hz RF transceiver and receiver would be appropriate or wifi could work but I have concerns about overloading the channels. Bluetooth seems like it has too long a handshake period and the range is too low.

Are there any other options I'm missing? What would be the best way to implement this?

Many thanks for you answers

Update : Data estimation

So the data payload I estimate consists of :

Speed (km/ph) : ok so this will be max 3 decimal numbers, so one short int should be enough here (2 bytes)

bearing : so this will be a standard bearing, let's assume between 0-360 so another short int should be fine (2 bytes)

Velocity : ok, so also a short (2 bytes)

Long : well this needs to be a 32 bit float so it's going to take 4 bytes

Lat : same as above 4 bytes

It's possible with some hackery I could combine speed, volcity and bearing into one short to only take 2 bytes. But let's assume I'm probably going to need 14 bytes, in best case 9.

In terms of Radio, the RFM69 is a good option for range, speed and reliability at low cost. A board like this one https://talk2.wisen.com.au/product-talk2-whisper-node-avr/ would have all ready to go, just add your sensors.

The link can run on 433MHz, 868MHz or 915MHz band, which cover 99% of unlicensed/open frequencies worldwide.

For the protocol/software you need to reduce the message as much as possible. As you mentioned, you could have 9 bytes for the payload if you "share" some bytes, which is the correct approach in this tight network. Add some 2 extra bytes for "operation/command", "sender" and "receiver". Additional to that, you need to consider the bytes added by the radio itself, like Preamble, Sync-word, Network ID, Length, CRC, etc.

The biggest challenge in my opinion would be to not have the RF network flooded with messages, causing multiple radios to transmit at the same time and messages being lost.

Let's suppose you have a total of 20 bytes for all headers+payload per message. If your network is running at 80Kbits/sec (or 10KBytes/s), that would allow a maximum of 500 message/second (2ms per message) in a perfect scenario, without considering any kind of delay between messages.

Bring down to the real-world a 1/3 link utilization is a bit more realistic, giving you a bit over 150 messages of 20 bytes per second. In other words, if the network had an evenly message distribution a node would transmit a 2ms message followed by 6ms of silence.

Now, you can't count that 100 nodes would have perfect synchronization to send a 2ms message and stay quiet for exactly 998ms before sending a message again. There are so many variables which require you to have some sort of control.

One way of doing that is by using a pooling mechanism, where you have a "tick" or "clock" node, which is the only one allowed to talk without being asked. This node will be sending "pooling" requests, a small message with 1 or 2 bytes, containing a command and the destination address, for example: 0x99 0x0A, where 0x99 is the address of the node being polled and 0x0A is the command, like "send me the instrumentation readings, you have 2ms".

Now, instead of the node 0x99 start reading the sensors, it already have it all stored in memory and ready to go, sending the broadcast message to everyone interested. The node 0x99 will also start collecting the new sensor data and preparing the message, so as soon it'll be asked it's ready to go again.

This way you can control how noise the network is and also implement other commands to capture additional information if necessary, etc.

Another implementation would be similar to the old "Token-Ring", but I believe having a master would be more beneficial in this case.

Notes:

The RFM69 can go over 200Kbp/s, but only tests would tell the maximum reliable speed. I use 80Kbp/s to make maths easier.
Design your system so it would survive if a message is lost, like UDP packages, send it and "pray". Adding Ack and re-transmission is probably worst as it would slow down the whole cycle.
The radio also offers encryption, but it might take a few uS extra
If one node will be expected to receive every single message, bear in mind that it would have only a few milliseconds available to process the message and do whatever it needs to do before another message arrive. If you need to perform lots of processing/logs/control actuators you might need to delegate this task to other MCU(s)

Cheers,