Controlling buzzer with assembly I want to make a piezo buffer beeping with assembly code, but i haven't managed to yet. I have an Arduino UNO board (ATMega328p) and using avra and avrdude to build and load. The buzzer just stay silent. Here's my code:

.nolist
.include "m328pdef.inc"
.list

.equ _a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

.cseg
  ;wgm02..0 = 7 (fast pwm, top = ocr0a)
  ;cs02..0 = 4 (N=256)
  ;com0b1..0 = 2 (clear on compare match, set at bottom)
  ldi r16, 0b00100011
  sts tccr0a, r16 ;need out!
  ldi r16, 0b00001100
  sts tccr0b, r16 ;need out!
  ;ocr0a = _a to obtain 440Hz
  ldi r16, 141
  out ocr0a, r16
  ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
  ldi r16, 71
  out ocr0b, r16
  ;enable output at D5 aka oc0b aka Arduino pin 5
  sbi ddrd, 5
  loop:
  rjmp loop

Wiring is good and the buzzer too, since it works with a C sketch

EDIT: I found my answer by myself (with the help of answerers). I was accessing IO ports (tccr0a and tccr0b) with sts, while i had to use out. (tccr0a and tccr0b are IO ports defined in "m328pdef.inc" as IO addresses, not as memory addresses)

I translated you program to GNU as syntax, and it works as expected: I
get a 440 Hz square wave on digital pin 5. Here is the
translated program:

#include <avr/io.h>

; I'm too lazy to always type the full name of these macros
#define io(reg) _SFR_IO_ADDR(reg)
#define mem(reg) _SFR_MEM_ADDR(reg)

_a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

  ;wgm02..0 = 7 (fast pwm, top = ocr0a)
  ;cs02..0 = 4 (N=256)
  ;com0b1..0 = 2 (clear on compare match, set at bottom)
  ldi r16, 0b00100011
  sts mem(TCCR0A), r16
  ldi r16, 0b00001100
  sts mem(TCCR0B), r16
  ;ocr0a = _a to obtain 440Hz
  ldi r16, 141
  out io(OCR0A), r16
  ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
  ldi r16, 71
  out io(OCR0B), r16
  ;enable output at D5 aka oc0b aka Arduino pin 5
  sbi io(DDRD), 5
  loop:
  rjmp loop

As shown in my comment to your question, I suspect the problem is a
misunderstanding of the meaning of things like tccr0a and ocr0a.
In the translated version above, I admit I do not know what TCCR0A
and co. mean. And I need not to: I can treat these as opaque
identifiers, as the avr-libc recommends to always use them with the
macros _SFR_IO_ADDR() and _SFR_MEM_ADDR(), which provide the I/O
address and the data address of the register respectively.

I do not know how to use avra, so I cannot tell you how the get the I/O
or data address of a register. But there certainly must be a way. You
should always use the data address with sts and the I/O address with
out and sti.


What makes a board "Arduino Compatible"? There are all sorts of Arduino and Arduino-compatible boards out there. They come in all form factors and they come with all sorts of different I/O. They even come with memory specs and different kinds of microcontrollers, from the ATmega328P to Intel-based.

So what is it that imbues a board to become "Arduino Compatible" ? Must it be pin-compatible? Must it be possible to compile Arduino source code for the board? Or must the board be binary-compatible? Must it emulate some specific processor instruction set?

Very curious. Please reference specifications if possible. Thank you.

The problem here is that "compatible" can mean so many things in different contexts and to different people.  For instance, it may mean any of the following:

Can be used with the Arduino IDE without any need for additional board installation of other modifications
Can be used with the Arduino IDE after modification (boards installed)
Uses the same (or very similar) API to the Arduino system
Has the same footprint as an existing official Arduino board
Is a device which will work with an Arduino board and has software available to operate it

All very different meanings.

Point 1 could be a board that is based on the design of an existing Arduino board (say the Uno) but built into a new form factor, maybe with additional hardware and peripherals added.  It is still treated as if it was the board the design was based on though.

Point 2 would be a board that is similar, though not the same, as an existing board.  A different board definition may be required to map the IO pins properly, for instance.  It could use a slightly different chip in the same supported family. You still use it as an Arduino, but it's not the same as an existing Arduino board.

Point 3 may mean it's based on a completely different chip.  The programming environment may be almost the same, but it's hard to get 100% API compatibility.  Arduino sketches and libraries may work out of the box, or may not.

Point 4 could be a board that, internally, is completely different to the Arduino, uses a different programming language, IDE, etc, yet the layout of the board is the same as, say, an Arduino Uno.  A good example is the Mecanique Firewing - an Uno footprint, but a PIC32 chip instead of an Atmel, and Basic instead of C++.  Most Arduino shields would just plug in and work though, software permitting.

Point 5 is from the completely opposite direction.  This is a device which "is compatible with" in that "it will work with" and Arduino.  That could be on an electrical level (it's a 5V device and will connect to the Arduino) or that it has full software support ("Download our Arduino library...").  It has nothing to do with how the device works or what it is though.

I prefer to use specific terms, respectively:

Based on the Ardino UNO
Programmable with the Arduino IDE
Compatible with the Arduino API
Footprint compatible with the Arduino UNO
Suitable for use with Arduino boards

That way it states exactly in what way this device relates to the official Arduino boards.


Driving conveyor belts using Arduino Unos We are planning to drive conveyor belts with Arduino Unos using stepper motors. We are planning to use easy drivers, so that we control at least 3 motors with one Uno. Currently we are still at an initial stage, we are designing and planning the setup of conveyor belts. But what I wanted to ask was, regarding the coding.

How would I code so that say the belt moves forward for x seconds, and then after time it moves backwards for y seconds. Any basic idea on the code would be great thank you. I could do the basic code, but I just need help with timers part.

In regards to time control use the mills() function.  You start by creating an:

unsigned long lastTime = millis();

Then later in the program create another variable:

unsigned long currentTime = millis();

Next Compare the two:

unsigned long elapsedTime = currentTime - lastTime;

For the most part I normally just shorten the last two lines into one:

unsigned long elapsedTime = millis() - lastTime;

Stepper motors are not needed if you are just doing timed control, but the advantage of stepper motors are you can move them with pin point accuracy based on the number of steps per rotation.  If there are 60 steps per rotation then 360 degrees per rotation/ 60 steps per rotation and you get that each step is 6 degrees.  So in order to turn the motor 6 degrees you would turn it 6 steps.  This also allows you to keep track of angular velocity.

When I control motors I normally create an array of the different parts of the cycle then loop through the array.


Nokia32/RCMM IR decoding issues I am trying to decode the IR signals from a remote. I'm using an Arduino Pro Micro, and a TSOP38238 IR receiver.

I found out that the remote uses the Nokia32(RCMM) protocol, and I have been able to partially decode it using cyborg5/IRLib (specifically this one: rcmm.ino). I tweaked the values of the example using the LIRC file corresponding to my remote, mainly the absolute error tolerance (Freebox_V5.lircd.conf).

Compared to other remotes I tried (with different protocols) the RCMM algorithm doesn't manage to decode the signal every time. Around 40% of the time when I press a button I got an "Unknown type received" output from the decoder.

The following is three outputs (for the same button) of the algorithm for a successful decoding and below two other outputs corresponding to two failures. Could anyone tell me what could be done to increase the success of the decoding algorithm?

Successful

Decoded RCMM: Value:2400A601 (32 bits)
Raw samples(36): Gap:63264
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m210 s240    7:m210 s240
8:m210 s540 9:m210 s590      10:m210 s390   11:m210 s590
12:m160 s290    13:m160 s290         14:m160 s240   15:m210 s440

16:m160
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

Failure 1

Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(36): Gap:3148
  Head: m410  s290
0:m160 s240 1:m210 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m160 s290    7:m160 s290
8:m160 s590 9:m210 s590      10:m160 s440   11:m210 s590
12:m160 s240    13:m210 s240         14:m210 s240   15:m210 s390

16:m210
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

Failure 2

Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(32): Gap:27904
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m160 s490    3:m160 s240
4:m210 s240 5:m160 s290      6:m160 s290    7:m160 s290
8:m160 s290 9:m160 s590      10:m160 s490   11:m160 s590
12:m160 s1190   13:m160 s440         14:m160
Extent=9460
Mark  min:160    max:210
Space min:240    max:1190

I'm unable to provide a complete answer yet but my research so far into a similar quest to use a similar remote can at least answer why you are getting two values for the same button on the remote. This is by design: the Nokia-32 RCMM protocol of this remote uses toggling codes that flip between one value and another on alternating presses of the same button.

My quest and the challenges of decoding this remote are documented in this thread: https://github.com/bengtmartensson/harctoolboxbundle/issues/97 where I discover that my IR remote uses Nokia 32 protocol but with mark and space timings slightly different from what most Arduino libraries are programmed for requiring a tweak to the signal in order to enable other libraries to decode it successfully.

Further information here: http://www.avsforum.com/forum/93-remote-control-area/1517341-theater-master-mx-500-remote-won-t-learn-bell-fibe-remote-any-help.html#post24345872 where we learn:

  it is different from most IR signals, because it has 4 different off durations, denoting zero, one, two , or three, while traditionally IR protocols have used just two off durations signifying zero or one.


In Linux, how do I get this Arduino library to work In Linux Fedora 20 Arduino I want to use the Timer library from here, from which  I have downloaded the folder Timer-master.zip, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to Timermaster.zip and importing that instead, but still got exactly the same failure message.

Please, how do I get out of this impasse?

What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to timer instead of timer-master. I just imported it on Fedora 20.


Routing Matrix with a large number of I/O Lets say that i would like to make a 128x128 routing matrix with an arduino uno,

Since i am unexperienced i think of using two 4051’s for 8x8 patching and because i want to persist the patch, controlling them with two quad d type flip flops, then repeat the circuit to reach 128x128 patching capibility. Then my output count would be sufficent in arduino uno.

I think this would work but sounds unelegant to me.
Do you have another advice for me to achieve this task?

Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.

Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html

They are more expensive but cost should not be the primary factor. Getting a design to work is more important.

Do a search for "Crosspoint Switch Array" for more chips like this.


Arduino Serial data communication with NodeJS I am using an Arduino Uno and a DTH11 temperature sensor to read temperature and then send that value to a computer via the serial port.

A NodeJS application is running on the computer and captures that value and writes to a log file.

When I try to get values from my NodeJS application, sometimes the value is broken into two values. Eg: 25 -> 2 and 5

This is my Arduino code:

dht DHT;

#define DHT11_PIN 7
float tem [4];

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

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int val = (int)(DHT.temperature);
  Serial.println(val);
  delay(600000);
}

This is my NodeJS program.

var fs = require('fs')
var logger = fs.createWriteStream('/data/Temperature/temperature.csv', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudRate: 9600,
});

serialPort.on("open", function () {
  serialPort.on('data', function(data) {
    var moment = require('moment');
    var dayTime = moment().format('YYYY-MM-DD,hh:mm');
    var val1 = data.toString();
    var val = val1.trim();
    if (val == '') {
      console.log('no data');
    else {
      console.log(val);
      logger.write(dayTime + ',' + val + '\n');
    }
  });
});

Is it a problem with my code?

Thanks in advance.

As Look Alterno wrote in a comment, you need to parse the incoming data on the receiving side. In this instance, you have to look for the line terminators. The Node.js serialport module provides a parser for this called Readline. Read that doc and use it.


digitalPinToInterrupt() doesn't work I am working on a protection circuit with 2 raindrop sensors which would be hooked onto the arduinos 2 interrupt pins and as soon as they detect water they shut some relays off, turn a red led on and exit() the main program.

These sensors I have order are working fine as regular input pins with the following code:

// lowest and highest sensor readings:
const int sensorMin = 0;     // sensor minimum
const int sensorMax = 1024;  // sensor maximum

void setup() {
  // initialize serial communication @ 9600 baud:
  Serial.begin(9600);
}
void loop() {
  // read the sensor on analog A0:
    int sensorReading = analogRead(A0);
  // map the sensor range (four options):
  // ex: 'long int map(long int, long int, long int, long int, long int)'
    int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // range value:
  switch (range) {
 case 0:    // Sensor getting wet
    Serial.println("Flood");
    break;
 case 1:    // Sensor getting wet
    Serial.println("Rain Warning");
    break;
 case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
    Serial.println("Not Raining");
    break;
  }
  delay(1);  // delay between reads
}

I will use the digital output not the analog but this doesn't change much. For the digital the pin is up at 5V at start and will be put to LOW once water is detected by the sensor.

I using the mega right now for breadbording but micro will be the final board.

Both the mega+micro should have 2,3 as interrupt pins:

Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based   0, 1, 2, 3, 7

I have modified the following code and tried all conditions:

LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.

It doesn't respond to any (the same time as I said the pin works fine as regular input).

Here in the setup I know that I am not using

attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);

but

attachInterrupt(interruptPin, myISR, FALLING);

that is because the IDE doesn't recognize this function. Is there any problem with the code? If I understand interrupts correctly I don't even need to check for that if ( ISRRan ) to break off the while loop, once the interrupt comes in the ardu SHOULD be running my interrupt function and immediately run the protection code then abort.

byte interruptPin = 0;  // your interrupt pin
volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
byte C = 0;  // this is just the counter var for the while loop

void setup() {
 attachInterrupt(interruptPin, myISR, FALLING);
}

void myISR() {
 ISRRan = 1;
 // do other things in the ISR
}

void loop() {
 while ( C < 10 ) {
   if ( ISRRan ) {
     break;
   }
   //doing something inside the while loop
 C++;
 }
 // do other things outside of the while loop
 ISRRan = 0;  // Reset for whatever reason
}

I have solved this.

The problem was with the pinout indeed.

attachInterrupt(0, myISR, FALLING);

will use the DIGITAL PIN 2

I was using attachInterrupt 2, that's all.


Is it dangerous to connect two output pins together? If I have two output pins, one set high and the other set low with digital or analog write like this

digitalWrite(PIN1, LOW);
digtialWrite(PIN2, HIGH);

and then I short them together using a wire, will current flow through the wire?

You can connect but requires resistor between two pins to limit the current.


How to determine Flash size? I need to determine the flash size of my ESP8266 on my NodeMCU module in order to flash the AT firmware onto the board. Apparently different boards come with differently-sized flash memories. Can anyone tell me the easiest way to find the flash size?

Arduino's ESP8266 support includes an example sketch called CheckFlashConfig. This probes the board, and prints the flash memory size.


No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor I have a Wemos d1 mini, and when I upload nothing or anything to it, the built-in LED always lights up and the serial monitor gets a lot of garbage at every baudrate.  I have supplied it with 4 AA batteries and the board has a built in voltage regulator of 3.3V at the 5V pin.

The Wemos d1 mini contains the esp8266 chip.

Please help me!  I have searched everywhere.  This just happened all of a sudden, the board was working perfectly fine before too.

Three words.  "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked.  I've been there and found out that you should never use these devices on breadboards and with funky power sources.  There is this chip within the module called eFuse,  which is basically an electronic fuse that's really easy to destroy.  Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.

I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor.  In that case, your module's death sentence is officially sealed.

Congrats. :(


Float arithmetic vs. int arithmetic - is there any power penalty? It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.

My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using float?

Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.

UPDATE:   What will my application do meanwhile?

The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger. So the loop in pseudo-code would be:

Read all inputs (digitalRead or direct port access);
Filter the readings and decide if a button action has been detected;
Set some control flags that determine which part of the cycle the lights are in;
Check for elapsed time to actually turn blinkers on and off.

So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?

It depends on what your processor is doing while it has no real work to do:

If you put it to sleep, then yes, using floats will keep the CPU awake for a longer time and burn more energy.
If you are instead doing busy-waits (e.g. with delay()) it should make no difference, since the CPU is busy 100% of the time anyway.

Update: According to your update, it seems your program never
sleeps. Then I would expect no substantial difference in power
consumption between using floats or ints. As Majenko said, there can
theoretically be some small difference depending on the number of
transistor transitions involved in each instruction (and, I would add,
the capacitive loading of the involved transistors), but I do not expect
this to be very significant.

If you are really concerned about the consumption of your Arduino, I
would suggest you use it only for prototyping, then move your code to a
bare ATmega (or maybe even an ATtiny) chip. Also, add at least one call
to sleep_mode() inside your main loop. Each such call will put your
CPU to sleep until the next timer interrupt, which typically happens
every 1024 µs. There is a lot more to say about power savings, see
for example this excellent writeup by Nick
Gammon.

Edit: When trying to minimize power consumption, one of the very
first things to do is figure out how much work has to be done, and make
sure your program never does more work than required. In your case, this
means you have to know how often your main loop should execute, and
prevent it from running more often than needed. For example:

#include <avr/sleep.h>

const unsigned long loop_period = 5;  // run the loop every 5 ms.

void loop() {

    /* Sleep while waiting for the next time slot. */
    static unsigned long last_time;
    while (millis() - last_time < loop_period)
        sleep_mode();
    last_time += loop_period;

    /* Actual work goes here... */
}

If the actual loop work takes significantly less time than the loop
period, your CPU will sleep most of the time, leading to significant
power savings. Then you can start digging into more advanced
power-saving techniques like those mentioned in the article linked
above.


Ethernet Shield: Maximum speed Looking at this shield here: https://store.arduino.cc/arduino-ethernet-shield-2

It states that "Connection speed: 10/100Mb". However from looking at various forums it appears that no one can get much more than 300Kb/sec with this device?

Can anyone explain what causes this limitation and how to overcome it? If its SPI that is the bottleneck is there some alternative? I am looking to get speeds of 6 mega bytes per second or more using a TCP connection.

I am extremely new to all this so apologies if I've missed something extremely obvious here. I also had a look at bluetooth/wifi shields but it appears they seem to also have some similar throughput issues. USB looked like it could work but is extremely complex for a newbie.

It's not just the SPI what limits overall speed. You also need some proccessing power, and AVR based Arduinos lacks of it. It all depens what do you want to do with data.

If you need some serious processing power, it might be better to use something much more powerfull, like raspberry PI with real operating system. You can even run some web server at the speeds you can't even imagine with Arduino with the ethernet shield


Which of the clock sources are actually internal to the ATmega328P? I am trying to determine exactly what all of the fuse settings correspond to on the ATmega328P. The options for the CKSEL bits are:

1111-1000: Low Power Crystal Oscillator
0111-0110: Full Swing Crystal Oscillator
0101-0100: Low Frequency Crystal Oscillator
0011: Internal 128kHz RC Oscillator
0010: Calibrated Internal RC Oscillator
0000: External Clock

Clearly, the clocks labeled "internal" are part of the "guts" of the microcontroller. No external components are required to use those clock sources. The external clock is clearly an external source.

My question is this: are the low power, full swing, and low frequency sources built in to the microcontroller itself, or do they require an external crystal oscillator to be purchased and connected to the clock pins? This is not 100% clear from reading the data sheet. (Although I am under the impression that they are not internal to the device.)

If it requires a crystal, as the ones in question clearly state, then obviously you need to connect a crystal (and load capacitors).  Or use a ceramic resonator.

Only those labelled as internal are internal. Everything else is external.


arduino ethernet run php from sd card I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.
does anyone know of a library that would let me do this?

Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.

I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.

However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.

If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.


MQTT bridging with Arduino and ESP8266 - What software should I use? Sorry for the vagueness in my question, I am just looking for ideas to point me in the correct direction please...

I wish to connect many (read: 20+) different sensors to a local wifi network and have them all datalogged and controlled by a single server on the network. Pretty standard stuff for the home automation people etc. Some sensors are connected to esp8266 boards directly, others communicate via serial and will employ an 8266 to provide wifi.

I am having trouble deciding which direction to go or which software / firmware to combine since its changing rapidly and a fair number of tutorials are around but all have different approaches and end goals.

This must be entirely contained offline - I have a raspberry pi, a wireless router, and the various sensors (mostly arduino based).

Now from research it would seem I need to setup a serial to MQTT 'bridge' - and have the esps 'talk' to the pi by MQTT. And that the pi should be running 'mosquitto' if I wish the MQTT to be bi-directional (i.e. I can receive serial data AND send serial commands. I have never dealt with MQTT so I am trying to learn as I go.

I have been working for a time with 'ESP-Link' software and had success using it as a simple serial to tcp-ip bridge and using virtual serial ports to communicate with the attached device. However using virtual serial ports on the server is clunky, unreliable and not what I wish to do - does anyone know if it can be setup so I can send 'raw' serial messages over TCP to the server for use? And from the server to control the connected devices? Or if there is an easier way? I cannot modify all of the serial devices I wish to connect, so just want to get the data out/in and have it manipulated by the server where necessary.

In essence I wish to end up with several sensors all connected to the router, and logged / controlled through a web interface hosted on the PI, all 'offline' and contained. Eventually I would like the server to be able to recognize what devices it can 'see' automatically, however at this moment I simply wish to gain insight into how I can most easily achieve this? Or even if I am completely mistaken in my approach?

Thanks

MQTT is perfectly suited to this application. Here is an overview of a possible configuration. You should be able to find tutorials about each piece of the system.

On the Raspberry Pi:

Setup a Mosquitto server that can receive messages published by the ESP devices.
Write and run a MQTT client on the RPi that subscribes to the messages published by the ESP devices. This client would then store the data in some sort of permanent data store (database, flat files, whatever).
Write and run on the RPi a web app that reads and presents the data from the data store.

On the ESP devices:

Connect to the same wireless network as the RPi (or set up the RPi as an access point and have the devices connect to it)
Read data from the sensors and publish it to the MQTT server on the RPi.

If you want to push data to the ESP devices -- have them subscribe to certain messages (topics) on the MQTT server and then publish messages in those topics on the server.  Your web app could do this.

All of this can be done on an isolated network.


Can we control an Arduino with voice commands? I'm looking for some method to control an Arduino with voice commands.

Could this work on this platform?

Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.

You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.

FYI: https://www.sparkfun.com/products/13316


Arduino Uno as USB to Serial converter (bypass 328p) I'm trying out computer to computer serial communication using 2 Arduino Unos (both connected to different computers).
Right now, I use the Software Serial library, which redirects data from the SoftwareSerial ports to the hardware Serial (over USB to the PC).

Is there any way to bypass the 328p chip, and only use the 16U2, which works as a USB to Serial converter?
Will the circuit in the diagram work? By connecting the GND to RST on both the Unos, the 328p gets disabled, which in theory should all me to directly tap into the serial line of the 16U2.

As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.

(This answer summarized from the comments above in order to take it off the "unanswered" list.)


Uploading Lua code to Arduino I have Arduino UNO board. Can I upload programs written in Lua?
I wrote a code for simple home automation using relays to control lights and tried to upload it to my Arduino board, I get error code of "Error compiling for board Arduino/Genuino Uno"? What does this mean?

This is the code I used:

var("Switch", "ME.BI21")
var("Relay", "ME.BO21")
var("RelayState", "ME.BO41")

RelayState = 1

Relay = Switch

if (Relay == 1 then){
  print("The Relay is ON")
}
else{
  print("The Relay is OFF")
}
end

The Uno can’t run Lua code. The ESP8266 modules like the Wemos D1 or NodeMCU can, with the right firmware.


Why can't I read anything but Pin 0 of PORTC? So I am working on this lab for my Embedded Systems class, but I can't seem to read anything but the first bit of PORTC.  What's even weirder is that if any of the pins go low the first bit will go to 0, while all the others stay at 0 no matter what.

Here is my code:

 /*
 * Lab_4A.c
 *
 *  Reads the value of one distance sensor
 *  and reports if light/dark to the LCD.
 *
 *  Created on: Sep 24, 2014
 *  Author: Austin R. Bartz
 *
 *  LCD Connections:
 *  E   - PB4 (Digital 12)
 *  RS  - PB5 (Digital 13)
 *  R/W - GND
 *  Data 4,5,6,7 - PD4,5,6,7 (Digital 4,5,6,7)
 *
 *  Sensor Connections:
 *  Sensor 8 - PC0 (Analog A0)
 *  Sensor 7 - PC1 (Analog A1)
 *  Sensor 6 - PC2 (Analog A2)
 *  Sensor 5 - PC3 (Analog A3)
 */

#include <avr/io.h>
#include <inttypes.h>
#include <MSOE/delay.c>
#include <MSOE/bit.c>
#include <MSOE/lcd.c>
#include <user/initPorts.c>
#include <user/readPorts.c>
#include <user/writePorts.c>

void printBinaryLCD(uint8_t);
uint8_t readSensors();

int main(void)
{
    lcd_init();
    lcd_clear();
    while(1)
    {
        uint8_t val = readSensors();
        printBinaryLCD(val);
    }
}

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = ((PINC & (1<<3)) == (1<<3));
    lcd_print_uint8(A);
    lcd_goto_xy(1,0);
    uint8_t B = ((PINC & (1<<2)) == (1<<2));
    lcd_print_uint8(B);
    lcd_goto_xy(2,0);
    uint8_t C = ((PINC & (1<<1)) == (1<<1));
    lcd_print_uint8(C);
    lcd_goto_xy(3,0);
    uint8_t D = ((PINC & (1<<0)) == (1<<0));
    lcd_print_uint8(D);
}

uint8_t readSensors()
{
    DDRC = 1;
    PORTC = 1;
    delay_us(10);
    DDRC = 0;
    PORTC = 0;
    delay_ms(1);
    return PINC;
}

Any help would be much appreciated!

Judging from your readSensors() function, these seem to be capacitive
sensors:

you charge them to Vcc (DDRC = 1; PORTC = 1;)
you wait until they are fully charged (delay_us(10);)
you tri-state the pin (DDRC = 0; PORTC = 0)
you wait for them to partially self-discharge (delay_ms(1);)
you read the pin (return PINC;)

If my assumption is correct, and if all of those sensors are similar,
then here is your first bug: you are only charging the sensor on PC0. If
you want to charge the four sensors, you need to set bits 0 to 3 of the
port to active high. Thus, the first two statements in readSensors()
should be:

DDRC = 0x0f;   // bits 0 to 3...
PORTC = 0x0f;  // ...set to active high

Your second bug is in printBinaryLCD(). The function name, and the way
you call it, implies it is meant to print on the LCD the value passed as
a parameter. Instead, it is completely ignoring its parameter, and
reading PORTC itself. This is bad because the reading of the
capacitive sensors is time sensitive, so you should let readSensors()
do the work. You should then change printBinaryLCD() so that it
examines val instead of PORTC:

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = (val & (1<<3)) != 0;
    ...etc...


Power MPU 6050 module through pin AD0 TL;DR: is it safe to power a MPU 6050 module through its AD0 pin instead of VCC?

We managed to have two MPU 6050 modules on the same I2C buffer by changing the address of one of them by connecting its AD0 pin to the same current origin used for VCC.

We found out that we can get the same result if we just switch the power cable which goes to the VCC pin to the AD0 pin: the module changes its address and we are able to read its data normally.

This would be a better configuration for us because, if the AD0 cable ever got disconnected, we wouldn't get anything from the second module but we would still get uncorrupted data from the first one. In the other case (cable to both VCC and AD0), if the AD0 cable got disconnected, we would get corrupted data.

So the final configuration would be: GND, SCL, SDA pins connected normally, power to AD0, pin VCC left unconnected.

The question is: is this a safe configuration or is it better to just leave the VCC pin connected normally and get another cable to the AD0?

From empirical tests it looks like it works fine, but we couldn't find any confirmation and are not experts on the matter.

Theoretically that should be OK.

According to the datasheet the MPU6050 consumes no more than 3.9mA with all the internal options turned on. That is below the limit of 25mA sustained current from a single IO pin for the ATMega chips. Just be aware of the total limit of the ATMega's power pins of 200mA, but it would take a lot of modules to reach that limit.

Since the MPU6050 is a 3.3V device your modules most likely have a voltage regulator on them to allow powering from 5V. That should mitigate any voltage droop caused by the higher impedance of using an IO pin as a voltage source.


Any way to not explicitly include dependent libraries? When I am including the Adafruit_BMP280 library, Arduino IDE 1.7.10 complains that it wants all dependent libraries included:

Adafruit_Sensors.h
Wire.h
SPI.h

Isn't it possible to circumvent that? This question says to include the first library like

#include "Adafruit_BMP280"

but also with the full path, this doesn't work and just returns the same error.

No, it is not possible. The IDE needs to know which libraries you are using so that it can compile the source code for them.

Other IDEs have got around the problem by recursively scanning the libraries themselves and building up a list of dependencies (such as UECIDE) but this is not something that the Arduino IDE has been programmed to do.

The only other possible option might be to create a single massive library that contains everything that the "main" library relies on, however this may cause problems with other libraries also wanting the same things and you ending up with massive conflicts.


De-Auth "attacks" using Arduino? I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3  d).

If you need me to clarify anything, please just ask.

Thanks in advance!

If you can transmit raw 802.11, take a look at the code for aircrack-ng, specifically aireplay-ng.c - this software is known to work on arm boards.


Exiting from one loop and get ready for another I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.

What I am trying to accomplish is to set two passwords, namely pass1 and pass 2.

The condition is that this circuit is attached to a gate, if user 1 lets say knows pass1, after entering the pass the gate will unlock for 10 seconds and the pass1 becomes invalid i.e. can not be used in future. However if user 2 comes and knows pass2, after entering the pass2, the gate will open for 10 seconds and then pass2 becomes invalid; so each password can be used only once. I am attaching the code I already have below.

The problem with this code is that when pass1 is executed, the system does not take pass2 until unless the system is reset.

Kindly tell me a solution to fix this.

#include <Password.h>
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
Password password1 = Password("1234");
Password password2 = Password("4567");
int ledpin = A5;
int a = 0;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columns

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = { 8,  9, 10, 11};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
    lcd.begin(16, 2);
    keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop() {
    keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
    switch (keypad.getState()) {
        case PRESSED:
            lcd.println(eKey);
            switch (eKey) {
                case '*':
                    checkPassword();
                    break;
                case '#':
                    password1.reset();
                    password2.reset();
                    break;
                default:
                    password1.append(eKey);
                    password2.append(eKey);
            }
            return;
    }
}

void checkPassword() {
    if (password1.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code1 OK");
        delay(2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password1.append('1');
        lcd.clear();
        return;
    } else if (password2.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code2 OK");
        delay (2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password2.append('2');
        lcd.clear();
        return;
    } else {
        lcd.setCursor(0, 1);
        lcd.println("Wrong");
        delay(2000);
        lcd.clear();
        lcd.print("Wait for 5 Sec");
        delay(5000);
        lcd.clear();
        return;
    }
    return;
}

Regards
Fawad

You are never really invalidating the passwords. The statement

password1.append('1');

adds '1' to the guess, it does not change the password itself.
If you really want to invalidate the password, you should change it to
something that cannot be typed on the keypad. For example

password1.set("X");  // untypable password

Whether or not you do invalidate the previously used passwords, you
should reset the guesses once a password has been checked. This can be
done in checkPassword(), or in keypadEvent() as follows:

switch (eKey) {
    case '*':
        checkPassword();
        password1.reset();
        password2.reset();
        break;
    ...
}

BTW, all your return statements are useless, and the first
switch/case in keypadEvent can be replaced by

    if (keypad.getState() == PRESSED)

which would be easier to read.


If-statement matches but doesn't give a result I just started two weeks ago with Arduino and I'm hooked!

I got off to a good start and went through some online tutorials quite easily. Then came the RGB LED, which I couldn't get to work all of a sudden (it required putting in a color through the serial monitor, which would then be given by the RGB).

And the strange thing is, I can't get anything to work anymore that requires input through the serial monitor, where I used to get it working immediately...

I presume it's something with the if-statement, because if I remove it and just say digitalwrite HIGH to a certain pin, it works fine....

Checks I did:

Full re-install of Arduino (didn't solve it).
Check the LEDs by hooking them up to 5V directly (they all work).
Reconnecting the Arduino (didn't solve it).
Use a multimeter to measure current (there isn't, although the if-statement matches...

Here's my code. Does anybody see it? Because I don't...

Regards,

nannev (using Mac and Arduino Uno)

int yellowPin=8;
int redPin=9;
int greenPin=10;
String myLED;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
}

void loop() {
  Serial.println("Your color?");
  while (Serial.available()==0) {
  }

  myLED=Serial.readString();
  Serial.print(myLED); //check if the input came through correctly, which it did
  delay(1000);
  if(myLED == "yellow"){ .    //nothing happens at yellow....
    digitalWrite(yellowPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "red"){             //nothing happens at red....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "green"){       //nothing happens at green....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
  }
}

The Arduino IDE uses the C and C++ programming languages.

Some string comparison basics using C:

In the C programming language, a string can be thought of as an array of 8 bit values.  One way to compare two strings is to compare each 8 bit value and consider the strings different (not equal) upon finding the first not-matching 8 bit value.  Here is an example from programmingsimplified.com:

int compare_strings(char a[], char b[])
{
   int c = 0;

   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }

   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

There is a common function called strcmp() which can be used instead.  Here is another example from the same web page which uses strcmp():

#include <stdio.h>
#include <string.h>

int main()
{
   char a[100], b[100];

   printf("Enter a string\n");
   gets(a);

   printf("Enter a string\n");
   gets(b);

   if (strcmp(a,b) == 0)
      printf("The strings are equal.\n");
   else
      printf("The strings are not equal.\n");

   return 0;
}

Note that in both cases the array of strings is assumed to end with a NULL or zero value byte.  If you do not wish to follow this format you can use an alternate version of the function called strncmp() where the number of characters to be compared is passed along with pointers to the 2 strings.

Some string comparison options using C++:

There are C++ ways to compare 2 strings which make coding Arduino Sketches easier.  But C++ string manipulation usually requires more RAM.  And RAM is usually in short supply on inexpensive embedded processors.

As the code in the question is written using type String we can explore that approach. And, as there is some concern the strings may have unexpected trailing characters, we will continue to check only the necessary number of characters. In this slightly modified code example from geeksforgeeks.org string s1 is compared with string s2.  But only the first 6 characters are compared:

void compareOperation(string s1, string s2)
{
    // Compares 5 characters from index number 3 of s2 with s1
    if((s2.compare(0, 6, s1)) == 0)
        cout << "Here, "<< s1 << " are " << s2;

    else
        cout << "Strings didn't match ";
}

The number 6 was chosen because "yellow" contains 6 printable characters.  In this way, we can avoid the uncertainty of what character(s) follow the characters that make up "yellow" as received from the serial port.


Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p I am trying to write a code to read the current position of a flex sensor when a button is pushed and use that data to pulse a piezo. I set it up to read the flex sensor and to alarm when it gets 100 or below, that works! So what I want to do is integrate a button where you push it to set the current state of the flex sensor and then when its moved and is less than the number logged when the button was pressed then it alarms. I used to write in Basic and quick basic and am now (many years later in life) trying to learn C and am struggling. I'm using a NANO ATmega328p - here is my code so far:

int flexSensorPin = A0;//analog pin 7= tiny2=A1
const int Piezo = 3; //digital pin 3 = tiny0
const int inPin = 2; // Push Button to set current Bend Status
void setup() {
  pinMode (Piezo, OUTPUT);
  pinMode(inPin, INPUT);    // declare pushbutton as input
  Serial.begin(9600);
}
void loop() {
  int val = 0;
  val = digitalRead(inPin);
  int flexSensorReading = analogRead(flexSensorPin);
  Serial.println(flexSensorReading);
  if (flexSensorReading < 100) {
    Serial.println("Alarm! Set Angle Exceeded");
    digitalWrite(Piezo, HIGH);
    delay(100);
    digitalWrite(Piezo, LOW);

  }
  delay(250);
}

You will need to add this at the start of your code.

int LoggedPosition=100;

Change this line

if (flexSensorReading < 100) {

To this

if (flexSensorReading < LoggedPosition) {

and add this at just before the delay, at the end of the loop() function

if(digitalRead(inPin)){
    LoggedPosition=flexSensorReading;
}


how to use capacitive touch keypad without using CapacitiveSensor.h Library i want to use multiple capacitive touch keypads with arduino uno but number of IO ports are not enough. So I decided to use MSP23S17 port extender. Now i have to find some methods to sense the touch keypad without using its library. Can anyone tell me if there is any way to do the task.

Here's one: Microchip mtch6102, though it might be a little more complex than you're looking for.  All the others I found with a quick search were surface mount or single button controllers.  You might be able to multiplex a single button controller like the Atmel AT42QT1011, but I don't know what the settling or reset times are.  It may take to long to change pads, reset the chip, then wait for settling/calibration time (if any).


Problem importing a library in .h file I have following code:

MyApp.ino:

#include "DfRobotLcdShield.h"

void setup() {
}

void loop() {
}

DfRobotLcdShield.h:

#include <LiquidCrystal.h>

When I try to compile, I'm getting the error:

In file included from MyApp.ino:1:0:
c:\temp\build5856181074637812172.tmp\DfRobotLcdShield.h:4:27: fatal error: LiquidCrystal.h: No such file or directory
 #include <LiquidCrystal.h>
                           ^
compilation terminated.
Error compiling.

When I add

#include <LiquidCrystal.h>

directly to the .ino file, it works. I'm using the latest Arduino-IDE 1.6.3.

This seems to be a general problem of the Arduino IDE: It only recognizes libraries that are included in the (primary) .ino file.
If you look at the invocation of the compiler, the path to any given library is only added if this library's header file is included in the .ino file.
I tested this with the EEPROM library. If this library is included in the .ino file, the compiler is called with
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs -I/usr/share/arduino/libraries/EEPROM /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where the important part is the -I/usr/share/arduino/libraries/EEPROM.
If I now remove #include <EEPROM.h> (but still have it in another header file which in turn is included in the .ino as in your case), the compiler call changes to
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where now the include path to the library is missing.
TL;DR
If you need to use a library, just (also) add an include to the .ino file. It doesn't cost you anything and will solve your problem ;)

#include <file> vs. #include "file"
From the gcc documentation:

#include <file> is used for system header files. It searches for a file named file in a standard list of system directories. [...]
#include "file" is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. [...]


How to input keyboard commands using Arduino Mega 2560? I have an Arduino Mega 2560 connected to a Windows 8 laptop. I want to program it to send keystrokes to the attached computer (when a pin's digital read goes from HIGH to LOW.)

The trouble is, I cannot find any way to program my Arduino Mega to send keystrokes.

The supposedly "core" Keyboard and Mouse libraries only support 32u4 boards, and other libraries that give the Arduino keystroke functionality are out of sight. When I googled the issue, I found no question or explanation of how to send keystrokes on the Arduino Mega. When I searched further, I thought the V-USB library would be a potential workaround, but the library throws numerous errors when imported into an Arduino sketch (even on the 1.0.0 IDE it was designed for.)

After hours of searching, two final workarounds seem to have popped up:

Some method to run a Python code to send keystrokes to the PC, and then connect the Arduino code to Python. (I don't know Python...)
Use some program called Gobetwino, which runs between the Arduino and PC, to   convert Serial commands into keystrokes somehow. (Pressing and releasing a key can't be simulated very well by repeatedly sending Serial commands, I think.)

Both are very unideal, very tedious, and are equally likely to just not work. I have spent hours on this.

Does anyone have any suggestions to get me out of this hell? Libraries, workarounds, anything?

(Feel free to PM me questions for clarification.)

You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.

Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.

The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.

Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.

It all depends on what your project requires.


Arduino Mega + SIM808 GSM + GPS Module + Program Switch ON without pressing Push Button? I am new to IOT and tried out integration and a small test code with an Arduino Mega + SIM808 + GSM + GPS Module. It works fine with the SIM808 Library.

My requirement is to put it in an enclosure, but when the power restarts, for some reason we have to manually start the SIM 808 + GPS + GSM Module. Can we control it from code? Can we do a software trigger from Arduino code?

Maybe if we have some pins to connect and trigger the power on. Kindly provide inputs/suggestion for this module.

If you are aware of some module that can be started through code kindly suggest.

Here's one reference I found for a different module with Software Trigger.

There is a simple way of power the module without pressing the button. There is pin call D9 at the bottom right corner of the module. Just power the pin by Arduino digital pin or 5v pin around 3, 4 seconds. Then it will power the whole module. No need to press the press switch. Make sure you connect power(9V-12V) to the board and provide 5V and GND to the sim808 module. below figure shows the pin D9


Remote Wireless Tripwire I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.

This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.

Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.

Is this even possible?

This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".

The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.


3.3v inductive proximity sensors I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?

I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.

I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V article at hackaday.com for a circuit explanation.  See gearbest.com and sparkfun.com and Adafruit for inexpensive modules.

Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.


Which Arduinos support ATOMIC_BLOCK? Is there a definitive list of which Arduino architectures support the ATOMIC_BLOCK() macro, and a list of #defines for each architecture?
I've tried searching through the Arduino cores on GitHub to see where ATOMIC_BLOCK is used. If it's not used in a core, I've assumed it's not supported. I generated this list based upon that assumption, but how accurate is it?
ArduinoCore         Supported       Archived    #define
-------------------------------------------------------
  samd
  avr                  Yes                      __AVR__
  arc32
  sam                  Yes
  primo                               Yes
  megaavr              Yes
  API
  nRF528x-mbedos
  mbed

I would like to write some code, something like this (edited in response to comments):
#define ATOMIC_BLOCK_SUPPORTED (__AVR__ || __MEGAAVR__ || __SAM__)
.
.
.
#if ATOMIC_BLOCK_SUPPORTED
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#if ATOMIC_BLOCK_SUPPORTED
    }
#endif

For architectures that don't support ATOMIC_BLOCK, I would like to write my own code to save, disable and restore the global interrupt flag, something like this.
    asm
    {
        // Save interrupt flag.
    }
    // Clear interrupt flag.
    // Do not disturb.
    // Restore interrupt flag.

Potential Solution?
#ifdef __AVR__
#include <util/atomic.h>
#elif defined(__ARCH2__)
#define ATOMIC_BLOCK(/* for architecture 2 */)
#elif defined(__ARCH3__)
#define ATOMIC_BLOCK(/* for architecture 3 */)
// etc
#endif
.
.
.
#ifdef ATOMIC_BLOCK
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#ifdef ATOMIC_BLOCK
    }
#endif

Is there a definitive list of code that saves, disables and restores the global interrupt flag for every Arduino architecture that could be dropped into each #elif branch?

This answer covers: Which Arduinos support ATOMIC_BLOCK? And how can I duplicate this concept in C with __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) and in C++ with class constructors and destructors?.
Which Arduino's support the ATOMIC_BLOCK macros?

Which Arduinos support ATOMIC_BLOCK?

Only AVR (ATmel AVR architecture) microcontrollers support the ATOMIC_BLOCK macros, because these macros are part of the avr-libc library, which, you guessed it!, supports only AVR microcontrollers.
AVR-based Arduinos include those based on the ATmega328 microcontroller (Arduino Uno, Nano, Mini, etc.), ATmega2560 (Arduino Mega 2560), ATmega32U4 (Arduino Leonardo, Pro Micro), etc.
How are the ATOMIC_BLOCK macros implemented in C with the gcc compiler, and where can I see their source code?
avr-libc is available for download here: https://www.nongnu.org/avr-libc/ --> "source code and documentation" link under the "Downloads" section. Ex: here is the tarball for v 2.0.0: http://download.savannah.gnu.org/releases/avr-libc/avr-libc-2.0.0.tar.bz2.
The entire source code for the ATOMIC_BLOCK macros is contained in avr-libc-2.0.0/include/util/atomic.h.
ATOMIC_BLOCK is an ingenious macro written in C and relying upon the gcc "cleanup" attribute C extension which can call a function you define when a variable goes out of scope. Essentially, this is identical to a C++ class destructor which gets called when an instance of a class in C++ goes out of scope. The gcc "cleanup" attribute extension is a way to get C++-like behavior in C.
Here is the official gcc documentation: https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html. It states:

cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.

Its format is like this:
int x __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) = 0;

You use it like this:
RUN A REAL EXAMPLE OF THIS CODE IN C ONLINE HERE.
static __inline__ void cleanup_my_byte(uint8_t *my_byte_p)
{
    Serial.print("my_byte is going out of scope! Its value is ");
    Serial.println(*my_byte_p);
}

void setup()
{
    uint8_t my_byte __attribute__((__cleanup__(cleanup_my_byte))) = 7;
} // The following function call occurs automatically here as `my_byte`
  // exits its scope!:
  //    `cleanup_my_byte(&my_byte);`

Studying the avr-libc-2.0.0/include/util/atomic.h file referenced above, you can see how the ATOMIC_RESTORESTATE macro is implemented, using this attribute. I've put just the relevant pieces from that file here:
#include <avr/io.h>
#include <avr/interrupt.h>

#define ATOMIC_BLOCK(type) for ( type, __ToDo = __iCliRetVal(); \
                           __ToDo ; __ToDo = 0 )

static __inline__ uint8_t __iCliRetVal(void)
{
    cli();
    return 1;
}

#define ATOMIC_RESTORESTATE uint8_t sreg_save \
    __attribute__((__cleanup__(__iRestore))) = SREG

static __inline__ void __iRestore(const  uint8_t *__s)
{
    SREG = *__s;
    __asm__ volatile ("" ::: "memory");
}

Note that cli() clears (turns off) interrupts, and sei() sets (turns on) interrupts.
So, you can see that ATOMIC_RESTORE_STATE gets replaced by uint8_t sreg_save __attribute__((__cleanup__(__iRestore))) = SREG, which backs up the global interrupt state from the AVR SREG 8-bit register into sreg_save, then calls this function call when sreg_save exits its scope: __iRestore(&sreg_save);. That function call to __iRestore() then sets the SREG register back to where it was, restoring the interrupt state (turning it ON if it was ON before, or OFF if it was OFF before).
The official documentation for ATOMIC_BLOCK is here: https://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html. An example usage is this:
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
    my_var_copy = my_var;
}

The ATOMIC_RESTORESTATE part backs up the SREG register and sets up the call for __iRestore(&sreg_save); to occur when sreg_save exits this block scope, as we've already discussed, and the ATOMIC_BLOCK part gets converted into this: for ( ATOMIC_RESTORESTATE, __ToDo = __iCliRetVal(); __ToDo ; __ToDo = 0 ). This means that the entire block is now an ingenious for loop which runs only once! Prior to entering the for loop block, __iCliRetVal() is called once, clearing (turning OFF) interrupts, and __ToDo is set to 1, or true, so the for loop runs at least once, and then at the end of the first run it is set to 0, or false, to stop the for loop after one single run! As we've already gone over, the sreg_save variable now goes out-of-scope at the closing brace and the call to __iRestore(&sreg_save); is made, via the gcc extension, to restore the interrupt state! Ingenious!
How could you implement the ATOMIC_BLOCK functionality in Arduino in C++ (as opposed to avrlibc's gcc C version)?
In C++ (Arduino is C++, so we don't have to be limited to just C plus gcc extensions, as was the constraint in the avrlibc ATOMIC_BLOCK macros), you can get a similar effect using destructors in structs or classes (or, just use the avrlibc pattern shown above if you like, as that gcc C code is also perfectly valid gcc C++ code!).
Option 1: example to create a usage style similar to C++'s std::lock_guard
This, for example, would implement a form of ATOMIC_BLOCK(ATOMIC_FORCEON) {}, using a simple class in C++:
It relies on Arduino's built-in functions interrupts() (same as avrlibc's sei() function) and noInterrupts() (same as avrlibc's cli() function). I wish that Arduino also had built-in saveInterrupts() and restoreInterrupts() functions, but unfortunatley they don't. Someone will have to go file a feature request and request them, or implement them themselves and do a Pull Request (PR) on GitHub to try to get them back into the main Arduino branches.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK_FORCEON AtomicBlockForceOn atomicBlockForceOn_

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }
};

That's it! Now use it like this:
uint16_t my_var_copy;
{
    ATOMIC_BLOCK_FORCEON;
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `atomicBlockForceOn_` object's destructor is called here
  // and interrupts are automatically turned back ON!

Pretty cool!
This, I imagine, is probably exactly how C++'s std::lock_guard is implemented! Its usage is very similar:
void safe_increment()
{
    const std::lock_guard<std::mutex> lock(g_i_mutex);
    ++g_i;

    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';

    // g_i_mutex is automatically released when lock
    // goes out of scope
}

Option 2: example to create a usage style similar to avrlibc's ATOMIC_BLOCK macros
To obtain a usage style of ATOMIC_BLOCK(ATOMIC_FORCEON) { } in C++ one can definitely use the gcc C style which avrlibc uses, since that is also valid C++, but let's continue with the C++ class style shown just above instead, with just a few tweaks. We will add a couple more helper macros and a couple more functions to the class to make this work. Here it is, with a usage example shown at the end which is identical to how avrlibc's ATOMIC_BLOCK can be used! I think this is pretty cool too.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK(type) for(type; type##_OBJECT_NAME.run(); \
    type##_OBJECT_NAME.stop())
#define ATOMIC_FORCEON_OBJECT_NAME atomicBlockForceOn_
#define ATOMIC_FORCEON AtomicBlockForceOn ATOMIC_FORCEON_OBJECT_NAME

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }

    // Can we run? Returns true to run the `for` loop or
    // `false` to stop it.
    inline bool run()
    {
        return run_now;
    }

    // Tell the `for` loop to stop
    inline void stop()
    {
        run_now = false;
    }

private:
    bool run_now = true;
};

Use it like avrlibc's ATOMIC_BLOCK() { } macro!
Usage example:
uint16_t my_var_copy;
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `ATOMIC_FORCEON_OBJECT_NAME` (`atomicBlockForceOn_`) object's
  // destructor is called here and interrupts are automatically
  // turned back ON!

Further reading:

Nick Gammon's excellent "Interrupts" page, which is how I first got started learning about interrupts in 2012~2014 or so: https://gammon.com.au/interrupts.
Other answer's I've done about interrupts, locks/guards, and things:

global volatile variable not being updated in ISR
My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce "atomic access guards" on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

What's that weird type##_OBJECT_NAME thing I did in the macro anyway? Read more about macro token concatenation using the ## preprocessor operator in the official gcc C++ user manual here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html. Note: this also works in C of course.
gcc inline or __inline__, and static inline or static __inline__ rules:
https://gcc.gnu.org/onlinedocs/gcc/Inline.html


How to switch a low-voltage (1.5V) toy motor with an arduino? I would like to add an Arduino to control a toy with a 1.5V battery and motor in it.  The toy is currently controlled by a SPST switch in series with a single 1.5V AA battery and a cheap motor.

I could put in a transistor like How to switch an external circuit with Arduino? or To connect a simple toy circuit and trigger with an arduino?  but I would think the voltage drop of the transistor would be significant in the 1.5V circuit.

What would you recommend for switching a 1.5V circuit?

You would be better off using a MOSFET which, when on, has quite a low resistance. For example the RFP30N06LE datasheet shows a RDS(on) of 0.047 Ω at 30A and 5V.

Using Ohm's Law we therefore expect a voltage drop of:

V = IR
V = 0.5 x 0.047
V = 0.0235

Thus, only 23 mV drop if you are drawing half an amp. I measured using a toy that drew 200 mA and found a 5 mV drop at 1.5V (compared to the theoretical 9 mV).

I have a page about driving motors that illustrates how you might wire up such a device.

The 12V on that schematic could just as easily be 1.5V.

The diode on the schematic is a snubber diode which protects the transistor from flyback voltages from the motor.

Comparison to transistor

BJT transistors will have a higher voltage drop between collector and emitter. For example the 2N3904 has a 200 mV drop (0.2V) (called VCE(sat)) when conducting 50 mA. This is a somewhat larger drop than the 5 mV drop that I got with the MOSFET, and a somewhat larger percentage of the 1.5V that you are starting with.


TFT screen to change sketches I have an Uno + WiFi 101 thermometer and I'd like to be able to take it places and easily change WiFi network SSIDs and passwords.  Can I use a TFT screen to make these changes to a sktech or am I stuck using a PC and IDE for this kind of thing?

Can someone provide a sample sketch of what this might look like?  I want to know it's something that's possible before I spend the money on a TFT.

It's possible (let's face it, LIKELY) that I fundamentally misunderstand the capabilities and limitations of the TFT screen.  Sorry for the noobish question.

A TFT screen is just a screen. You can't modify SSIDs and passwords with it, any more than you can by poking your PC monitor (unless perhaps you have a touch-screen*). To modify things you would need:

An input device (eg. a keypad)
A method of displaying what you are entering (this is where the screen would be handy)
A method of storing the new information. You could store things like passwords in EEPROM.
Code to make all that work.

* Some distributors sell touch-screen interfaces designed to go on top of screens - this might conceivably be what you are thinking of. However you still need the touch-screen, and code to make the touch-screen, and the TFT screen, work.


What is wrong with my code? RGB potentiometer Arduino programming has been a huge learning curve for me and I am trying to create a project with an rgb that's color is determined by a potentiometer. To where the further I turn it, the further across the rainbow spectrum it goes. I can't figure out how to do all values in between because I am not educated enough but I came up with this basic code...

int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor = 0) {
      setColor(255, 0, 0);  // red
    }
    if (wavecolor > 0 or wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    if (wavecolor > 333 or wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    if (wavecolor > 667 or wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    if (wavecolor = 1023) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

And for some reason, where the light should change colors once the potentiometer goes past a certain number, the light just flickers and only changes colors to white when it is all the way up or down. Also, it has a weird flickery yellow color.
Since I am new to this, can one of you better educated people be willing to assist me?

Equality comparison in C and C++ is expressed by == operator. ==, not =. This

if (wavecolor = 0) {

actually assigns zero to your wavecolor variable, thus destroying the value you just read.
The common sense says that you actually need and in your conditions, not or

if (wavecolor > 0 and wavecolor < 333) {

The or conditions that you curently use are simply always true, which makes them nonsensical.
This is valid syntax

wavecolor > 0 or wavecolor < 333
wavecolor > 0 and wavecolor < 333

but you might want to try using more "canonical" forms

wavecolor > 0 || wavecolor < 333
wavecolor > 0 && wavecolor < 333

or and and are "alternative" forms of || and && operators, introduced a long time ago for reasons that are all but obsolete today.
Assuming that you meant and instead of or, in your conditions you managed to "exclude" such values as 333, 667 and 1022 - they wouldn't match any of and conditions. Changing some strict comparisons to non-strict ones might be in order.
As a side note, in a single-file program all file-scope variables should be either const or static. In your case

const int redpin = 6;
const int greenpin = 3;
const int bluepin = 5;
const int potPin = 0;


ESP8266 Deep Sleep Wake Up I am testing esp8266's deep sleep mode. And i have some questions about that.

1- I want to wakeup esp via timer. I did it. I implemented GPIO16-RST connection and this version done.

2- I want to ake up esp with external button too. It means, I will use timer and button to wake up esp8266 same time.

Is it possible and how can i connect  button to RST pin that while GPIO16 has already connected to RST?

The reset pin of the ESP8266 has internal pull-up. Connecting the pin to ground activates the reset of the ESP.

To create a reset button, wire a momentary push button between reset pin and ground. Pushing the button will connect reset to ground, causing a reset of the esp8266.

The io 16 pin is connected internally to RTC, which in deep sleep counts down the time and then sets the pin LOW. If io 16 is wired to reset pin, this resets the ESP8266 to end the deep sleep.

The only way to end the deep sleep of the esp8266 is a reset. There is no conflict between RTC io 16 and a reset button, both wired to reset pin. Both can activate the reset to end the deep sleep.


Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A I am using Arduino UNO and SIM 900A. Pins 0 and 1 are used as TX and RX. Is it possible to use any other pins?

The best choice for serial communications is obviously the HardwareSerial object, Serial, on pins 0 & 1.  However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter).  There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.

The second best choice would be pins 8 & 9, because AltSoftSerial requires those pins.  It is very efficient and reliable.

After that, any other pins can be used with one of these two software serial libraries:

NeoSWSerial is less efficient than AltSoftSerial, but much more efficient than SoftwareSerial.  It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX.  I maintain this library.

If you must use a different baud rate, SoftwareSerial is the last choice.  It blocks interrupts for long periods of time and can interfere with other libraries.  It cannot transmit and receive at the same time.


Arduino substring not working Hello  I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:

file = SD.open("/classes/basic.txt", FILE_READ);
 Serial.print("Reading, Checking and Compiling \n");
  while(file.available()) {
   character23 = file.read();
   content.concat(character23);
  }
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");
}

if(l1.substring(0) == "print"){
  printlnMethod();
}
file.close();

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");

What am I doing wrong?

Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the start of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use l1.substring(0, 5) to get the characters 0 to 4 inclusive.


How do I sense that the serial monitor is started? When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.

You can't. There is no way of detecting if the serial monitor is open or not.

However, you can disable the automatic reset and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).


Why connect a diode between the reset pin of Arduino and 555 timer? I am trying to create a watchdog timer using 555 IC and I am following this.

I do not understand why a 1N4148 diode is connected between the reset pin of Arduino and the output of the 555 timer.

As far as I understand, the reset pin of the Arduino should be high, and when it is pulled low, the Arduino resets. But why should we add a diode over here? What purpose does it serve?

It's called a "Wired Or" arrangement.

The Arduino's RESET pin has a pullup resistor in it (10KΩ). That keeps the RESET pin normally HIGH. To invoke a reset that pin needs pulling low, and that is done from a number of sources:

The RESET button
The DTR pin (through a 100nF capacitor) of the USB interface chip
The 555 watchdog circuit above

The critical one there is the DTR pin.  That, because it's a brief pulse with quite a high output impedance, needs the reset pin to be easy to pull down. If you connected the output of the 555 directly to RESET it would be constantly trying to pull the RESET pin up to 5V with quite a low output impedance. The DTR circuit would have no chance of overcoming it.

So by adding a diode in there you get Wired Or, using an arrangement direct from the 1950s - DRL - Diode-Resistor Logic.  When the output of the 555 is HIGH the diode is reverse biased (or neutrally biased) and doesn't conduct, so the RESET pin's own resistor pulls the RESET pin up.  However, when the output of the 555 is LOW the diode can then conduct (it's forward biased) and that pulls the RESET pin LOW.


Global variables with C++ in multiple files I'm not a C++ programmer (but I have used regular C code for implementing low-level machine language equivalent SW for some time), and after trying to modify an existing cC+ program to do what I need (and failing), I've decided to rewrite parts of the code in plain C code.

But to be able to use the data, I need to create some variables that have to be accessible to parts of the existing C++ code.

When I declare a global variable (extern int variable name;) outside the main program, the compile fails because the references to the global variable aren't within the scope of the cpp parts of the program.

I don't program with multiple files myself, so I was wondering if I need to globally declare the same variables as part of each cpp program that needs to have access to the variables? Is there a another/better way?

When using multiple source files you need to use header files to share things between them.

myproject.h:

#ifndef __myproject_h__
#define __myproject_h__
extern int aGlobalVariable;
#endif

myNewCode.c

#include "myproject.h"
int aGlobalVariable;

modifiedOldCode.cpp

#include "myproject.h"

This way the header file defines the variable as an extern in all of your c / cpp files so that it is visible to all of them but the variable is only actually declared and memory allocated for it in one place, in the .c file.
Similarly any functions that you want to be visible in both files should be declared in the headerfile (e.g. void myfunction(int x);) but the actual definitions should be somewhere in the .c or .cpp files.
The #ifndef and #define lines in the header as there so that if the header somehow gets included twice you don't get lots of redefinition errors.

There is nothing strange about c++ and globals, a global defined this way is global to everything, it doesn't matter what object you're in or how things are scoped. This can however have some strange effects since there is only ever one copy of a global while you can possibly have multiple instances of the c++ class that uses it. This can cause some consistency related issues if you aren't careful. Whether you need to worry about this or not depends very much on the nature of the code.


US-100 Ultrasound sensor doesn't work on Arduino mega 2560 Im using a Arduino Mega 2560, and I tried to connect a us-100 ultrasonic sensor for distance measurement.

I connected it as shown in the image

The code I used was:

const int trigger=6;
const int echo=7;
float distance;
void setup(){
Serial.begin(9600);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
}
void loop(){
// Trigger US-100 to start measurement
// Set up trigger
digitalWrite(trigger,LOW);
delayMicroseconds(5);
// Start Measurement
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
// Acquire and convert to mtrs
distance=pulseIn(echo,HIGH);
distance=distance*0.0001657;
// send result to UART
Serial.println(distance);
delay(50);
}

But It won't work, as in the only output i get is 0.00 cm as shown in the image

Can someone tell me if I'm doing something wrong(also, i tried putting two probes between the vcc and one of the gnd pins, and a resistance was shown.This should mean the sensor isn't broken.yes?)? this is my first time using arduino and I greatly appreciate help to fix this.

Have you removed the "Serial Data Mode" shunt to put the device in "Pulse Width Mode"?

On the other hand, perhaps the "Serial Data Mode" would actually work better for your application?

Where I work, we have a coding style that strongly encourages
all "magic numbers" to be documented
with a link to the website it came from
or a reference to the book and page it came from.

Would something like this work for you?:

void loop(){
    // Trigger US-100 to start measurement
    // at least 50 us high, then set it low,
    // as recommended by
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    digitalWrite(trigger,HIGH);
    delayMicroseconds(50);
    digitalWrite(trigger,LOW);
    // Acquire
    unsigned long echo_microseconds = pulseIn(echo,HIGH);
    // debugging
    serial.println( echo_microseconds );
    Serial.println(F(" microseconds"));
    // conversion factor from
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    unsigned long distance_mm = echo_microseconds * 34 / 100 / 2;
    Serial.print(distance_mm);
    Serial.println(F(" mm"));
    delay(50);
}

It might be easier to use the Ping library as described at
Arduino-Info: UltraSonic Distance Measurement.

You might find the
Arduino Forum: Measuring Distances with Ultrasonic Sensors
thread educational.


Molex power with USB serial Communication from the same PSU Before I begin I just want to apologize for my mediocre understanding of things electrical and arduino. I know there are a lot of topics similar to this but I'm confused by the term external PSU
Question
Do I need to worry about any sort of issues (loops/grounding) if I use the molex connector to supply power to my arduino uno and continue to use the USB for serial communication at the same time? The source of both would be from the same PSU in my PC.
From what I understand the Uno when powered by DC should not exceed 7.5V for maximum efficiency. So it looks like the 5V from the molex would be more suitable than the 12V and sufficient for my needs of roughly 3.6A (60mA per LED * 60). Since USB can only supply a maximum of 2.0A and Molex appears to supply up to 5.0A from what I've read.
And I would connect it like so 5V molex powered Uno?
Background
Currently I'm using the arduino uno to power a single 5V strip of 30 rgb WS2812B leds, which works great when powered through the USB port, but since I need an additional strip of 30 leds and USB alone cannot supply enough amperage to power both I need a better source of current. I also needed the cleanest solution possible as it's for a PC tower and I don't want to use an external power source.
Edit - Alternative solution
If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

Two important things first:

The Uno 5 V pin and power bus must never be supplied more than 5.5 V or the MCU may die. The DC power input jack (the barrel jack) and the Vin pin, which are connected together, are not directly connected this bus, which is why you can supply higher voltages to that (see below).
You can not simultaneously supply power via both the USB cable and a power supply to the 5V pin/5 V bus because that would directly connect the two power supplies. That's a very bad thing, and probably not just for the Uno. (But there is a trick you can use here to still connect USB data when you are supplying power to 5V; see below.)

Now on to the details.

You can safely connect Vin (the pin or the barrel jack; they are directly connected) and USB at the same time because there's a switch (T1 on the schematic) on the board that will disconnect the USB power line from the Arduino 5V bus if more than 3.3 V is being supplied to Vin.

However, Vin goes through a regulator which, while it has the advantage of safely handling voltages much higher than 5 V, also causes some voltage drop, so you need to supply it with a minimum of 7 V. (6 V might work if there's very little power draw; 5 V almost certainly will not.) The maximum voltage you should supply is 20 V, but it's recommended that you stick to 12 V or less, since higher voltages mean that the regulator can get rather hot.

Unfortunately for you, this doesn't really help with your problem. While you could take the 12 V power off the molex connector, supply it to Vin and run the Arduino itself quite happily with the USB cable also connected, the regulator on Vin is rated for only 1 A, which is considerably less than you need for the entire system.

There are ways to have some parts of the system powered by one power supply and other parts powered by a separate power supply, but they're not trivial (and also beyond my expertise at the moment :-)).

Probably the easiest solution is to connect the 5 V output from the molex connector to your system power bus, which would be supplying both the 5V pin on the Arduino and your external components, and then build a custom USB cable with only the D+ and D- pins connected, dropping the power and ground pins. (You don't need the ground pin because the USB data signal is actually a differential signal: the difference or similarity in the voltage between D+ and D- pins is what determines whether the signal is a 1 or a 0.)

By the way, just to make sure, you do have some separate switching for all those LEDs, right? You're not trying to provide all their power via the Arduino digital outputs? Because, as per section 32.1 of the ATmega328P datasheet, while you are allowed to sink up to 40 mA from any individual data pin, you cannot sink more than 200 mA in total from the chip.


How to do I2C on Arduino with SDA and SCL pin already used i have a Arduino screwshield from sparkfun that I purchased: https://www.sparkfun.com/products/9729 which I used to put between my arduino uno and my 2.8" TFT LCD touch shield so that I am able to use the unused pins. I have to make an I2C connection between 2 Arduino Unos which I understand will require the A4 and A5 pins however the TFT currently uses both pins. also, my tft screen is from here: https://www.sgbotic.com/index.php?dispatch=products.view&product_id=2756

The schematics of my tft are: http://www.sgbotic.com/products/datasheets/development/02756-schematic.jpg .

I am wondering if I can just use the A4 and A5 pins using the screw shield anyway since according to the schematics, the A4 pin is connected to the LCD_RST or is the pin necessary for displaying images taken from the SD card?
If that isn't the way, how should I go about doing it, does anyone know?

No, you can't just use it. While I2C itself may work, the screen will keep resetting itself all the time and will be useless.

You may be able to get some luck with a software bit-banged I2C  on other pins. However I would personally choose to modify the TFT screen's PCB and cut the LCD_RST signal from the A4 pin and connect a 10kΩ resistor to +5V, or re-route it to another pin. That way you can then use I2C.


Arduino nano KiCad symbols Can anyone explain me the difference between the symbols for Arduino nano in KiCad? Is there any important difference at all? All of them seem to have all basic pins.

In short, there aren't any substantial differences.  But it makes sense to use the one that actually matches what you have.
My KICAD symbols are out of date, so I downloaded and unpacked the current archive for MCU Module symbols.  These things are defined in text files, so doing this allows you to employ the usual diff tools to them, if you break the parts of interest out into separate files, which is what I did to produce the below images.
Index Entries
Besides the name, they're different in what datasheet they refer to:

Definitions
In the below, on the left you'll see in dark blue background that both the Nano v2.x and v3.x are actually defined in the same file.  So, they are in fact sharing a definition; so, no differences there at all.  The original Nano boards varied in that some had ATMega168P and some had ATMega328P.  These are practically but not quite the same chip.  The significant difference is sizes of the various memories.  And they had different bootloaders.  Nothing that would make their symbols or footprints significantly different.
On the right is the Nano-Every, which is a fairly different beast from the older Nanos in that it's an ATMega4809, one of the new-series AVR parts, and different significant ways greater than just memory sizes.  But, it was designed to have the same layout as the prior Nano boards.  They even went so far as to make classes and objects to try to "emulate" the more traditional style GPIO ports of the Nano for Nano Every users.
As you can see there's really no differences besides the names of the pins and a few changes in drawn locations between the v2/v3 symbol on left and the "Every" symbol on the right.  Some of the pin names are different, but it's the pin numbers that matter when mating it to a footprint in Kicad, and those are the same between the two.
For whatever reason pin number 29 changed from W (in 2/3) to N (in "Every"), which according to their documentation is a change from power input to not connected.  I suppose this might make a difference between whether or not you need to add a PWR_FLAG symbol somewhere in your design to satisfy electrical rules check (ERC).  In the "Every", for whatever reason when they (slightly) rearranged the pins locations in the symbol, they stuck pin number 29 right on top of pin 4.  So, if you're having a hard time seeing pin 29, that (and the light gray text) are why.


DHT11 not giving correct value if I attaching a servo motor So I am using a servo motor and 2 DHT11s in my Uno, when I attach them separately it works well. But when I try to attach both, servo working correctly but DHT11 giving weird number(DHT11 was side by side, one gives 22oC and another gives 30oC sometimes -999).

I am powering both devices by using 5V and GND from arduino to a breadboard and then DHT11 and Servo power pin to the breadboard. All signal pin are direct from devices to arduino.

Am I power both devices wrong? or is there's a way to solve this?

Thanks

EDIT:
this is the code

#include <Servo.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 7
#define DHT11_PIN2 6
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  int chk = DHT.read11(DHT11_PIN);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  int chk2 = DHT.read11(DHT11_PIN2);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  delay(1000);
}

For the servo, I used GWServo S03N STD.

Your code looks like there is no bug in there.  You might want to look at using a library that lets you assign a pin in the constructor, so you don't need to read from a specific pin.  There might be something internal going on that you don't know (or want to know) about.  As for the movement of the servos do you realise you a rotating 181 degrees int p = 0; p <= 180 is 181 degrees, drop the = if you wanted 180.  Also pos++ is the same as pos += 1 but requires less of those tiring key presses :)

You say that the DHT11s work on their own.  The servo works on its own.  So it not a hardware fault.  I assume its not a wiring fault, but please double check.  That means it has to be something to do with the power.  If you are powering the servo from a digital pin then this is unlikely to work, try powering it from the 5V output pin on the other side of the board.

However if you are powering it from the 5V output pin and it doesn't work then you need to power it from a external source, a mobile phone charger will do (if you have one you can chop the plug off).  The problem with using external PSU is you must tie the grounds together.  Doing this means the Arduino and the external device agree what zero volts is and things work.  This is easily done by taking the gnd of the PSU and putting it in the GND connector of the Arduino and the taking the GND for the servo from the other GND on the Arduino.

I hope that all makes sense, if not tell me what you need clarifying.