Most efficent way to adjust value I am working on a system that starts a process based of a set time value (startHour). The user sets the start hour and can only select values from 00-23. I have been asked to start the same process at 6 hour intervals so that it occurs 4 times during the day.

My initial though is to add three more variable, secondStartHour, thirdStartHour and fourthStartHour. secondStartHour would be assigned a value 6 hours ahead of the startHour, thirdstartHour a value 12 hours ahead of startHour and fourthStartHour would be assigned a value 18 hours ahead of start hour. I could then use any of the startHour variables to trigger the process.

I wrote some code (below) that will work but I'm wondering if there is a better, more efficient way of doing it.

//set up secondStartHour 6 hours ahead of startHour
if (startHour <= 5)
{
    secondStartHour = startHour - 18;
}
else
{
    secondStartHour = startHour + 6;
}

//set up thirdStartHour 12 hours ahead of startHour
if (startHour <= 11)
{
    thirdStartHour = startHour - 12;
}
else
{
    thirdStartHour = startHour + 12;
}

//set up fourthStartHour 18 hours ahead of startHour
if (startHour <= 17)
{
    fourthStartHour = startHour - 6;
}
else
{
    fourthStartHour = startHour + 18;
}

I had to write the code in the way I did above because I am working with a 24 hour clock so in some cases adding time to a startHour will actually reduce the value. By this I mean if startHour is 23 (23:00) and I need to add 6 hours to it to get secondStartHour the result will be 5 (05:00) so I can't simply write code to say secondStartHour = startHour + 6. The code just seems too long winded and messy but I cant think of a better way to write it. I could use a switch case statement but then I would have 24 cases with assignments for each of the new variables in each case so that seems worse, any ideas would be appreciated.

Instead of comparing, you can use the modulo operator:

 secondStartHour = (startHour +  6) % 24;

And similar for the others:

 thirdStartHour  = (startHour + 12) % 24;
 fourthStartHour = (startHour + 18) % 24;

While xxxStartHour >= 24, 24 will be removed until it is within range [0, 24).

If you need an offset, you also can add some hours of course after the module (I don't fully understand your example which can have values >= 24.

Also, if you need to do the same task every 6 hours, you can use with one time and 'restart' it every 6 hours (and maybe taking summer/winter time into account).


How to connect Arduino 5v pin with multiple things? I am trying to connect a Bluetooth module and a gas sensor to Arduino.

Bluetooth module: HM-10
Gas sensor: MQ-2

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example.

I would like you to give me a link to an example that uses the 5v pin for multiple modules. It would be nice if the circuit configuration was included.

The simplest way is to just use a breadboard to connect your devices to your Arduino:

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.

The maximum total current you can draw when the device is powered via external power supply is 1A for the Arduino Uno, 800mA for the Due and 500mA for the Nano. Check the specs for your board on the Arduino site.

Arduino-compatible devices may vary - check the specs for the device you're usiing.

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).


Why does a Piezo Buzzer not require a PWM digital pin (Gallileo Gen2)? According to my current (poor) understanding, only the PWM pins (with the ~) among the digital pins (ignoring Analog pins) can be passed to analogWrite().  I understand the servo therefore - since interfaced by a variable voltage signal - must be connected to such a PWM pin.

Why is the humble Piezo Buzzer not bound to this condition?
Why can I connect the buzzer to a digital pin that is not PWM (and so should only be able to output binary LOW, HIGH voltage at some consistent frequency) and still achieve a varying sound by calls to the tone() function?
Surely under the limitations of being digital and non-PWM, the pin could only cause some consistent buzzer frequency?

I'm reading online that the Piezeo Buzzer does indeed require a PWM digital pin, but I can connect it to any digital pin on my Galileo gen2 and have it function seemingly correctly (differing tones produced).

Also, since slightly relevant; what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

Why does a Piezo Buzzer not require a PWM digital pin?

Tone() uses the microcontroller's hardware timers to control the related code function but do not use the hardware PWM features. The timer can be assigned to any pin that has a digital output capability.
Tone() sends a "rail to rail" square wave (50% duty cycle) to the selected pin

Slightly more lower level information here under Ugly details
They say:

The library uses the hardware timers on the microcontroller to generate square-wave tones in the audible range.

You can output the tones on any pin (arbitrary). The number of tones that can be played simultaneously depends on the number of hardware timers (with CTC capability) available on the microcontroller.

ATmega8: 2 (timers 2, and 1)
ATmega168/328: 3 (timers 2, 1, and 0)
ATmega1280: 6 (timers 2, 3, 4, 5, 1, 0)

The timer order given above is the order in which the timers are allocated. Timer 0 is a sensitive timer on the Arduino since it provides millis() and PWM functionality.

  ... what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

There is a misconception there.
Analog pins are capable of Analog INPUT functionality .
"PWM" output is known as "analogWrite" but is actually a purely digital function and is not related to whether a pin has analog read functionality.
PWM out = analogWrite is available on pins which have associated PWM hardware.
The actual signal is a "rail to rail" square wave with a mark:space (on:off)that varies.   Filtering the PWM produces DC at the average DC level. PWM range is 0 to 255 (8 bits)


Arduino Voltage Divider So am doing a project which involves the reading of voltage and current generated by Solar Panel. Now I learnt that Arduino cant Read Voltage directly above 5V. To read above that you need to add a voltage divider circuit in between. But that's the great solution for a solar panel around 20W.
Now what if i want to read voltages of n number of solar panels which are in a farm in which each solar panel generated around 300-400 W .
1)Will adding voltage divider help?
2) What is the limit of Arduino of Voltage Divider?
3) What registers i would have to use for such big voltage divider?

1)Will adding voltage divider help?

You will need n voltage dividers, one for each solar panel.

  2) What is the limit of Arduino of Voltage Divider?

There is a limit on the equivalent Thévenin resistance of the voltage
source connected to the Arduino analog inputs. It should be no larger
that 10 kΩ, otherwise you risk cross-talk between the channels.

If the solar panels have a low output resistance, then the equivalent
Thévenin resistance is the resistance resulting from setting the two
resistors of the divider in parallel. Setting the smallest resistance
to 10 kΩ will ensure you meet the condition while at the same time
keeping the consumed current quite low.

There is also a limit on the number of solar panels that you can
independently monitor: 16, which is the number of analog inputs on the
Mega.

  [...] each solar panel generate[s] around 300-400 W

The power generated is irrelevant: only the voltage is a concern. Your
dividers must output no more than 5 V.


#include  Error with WiFiClientSecureBearSSL.h I am new to the Arduino world and it seems that this simple problem is keeping me at the start line.

I use the Generic ESP8266 Module as Board
In my sketch I just write:

#include < ESP8266WiFi.h >
void setup(){}
void loop(){}

The ERROR is :

BearSSLHelpers.h:148:34: error: 'virtual const unsigned char* BearSSL::HashSHA256::oid()' marked override, but does not override

 virtual const unsigned char *oid() override;

                              ^

How am I going to solve that? Any help is appreciated.

You installed the latest git version of the ESP8266WiFi library into your libraries folder and this version is not compatible with the 2.5.2 version of the esp82666 Arduino core.

The ESP8266WiFi library is part of the esp8266 boards package. It should not be installed separately. Delete the library from your libraries folder.


Problem fetching data from MPU6050 I am new to Arduino. I have an arduino mega board, which I need to interface with MPU6050 accelerometer-gyroscope module.

My connections are

Arduino_SCL->MPU6050_SCL;

Arduino_SDA->MPU6050_SDA;

Arduino_GND->MPU6050_GND;

Arduino_5 V->MPU6050_Vcc;

Arduino_Pin 2->MPU6050_INT;

I have uploaded the following code to the arduino mega.

#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;
double  time;
int i;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();
  time = millis();
  i = 1;
}

void loop()
{
  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // print result
  Serial.print(i);   Serial.print("\n");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\n");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\n");

  i = i + 1;
  delay(1000);
}

My problem is when I observe the reading on serial monitor, it shows every reading as zero. Does this mean my sensor is damaged or there's some problem with my connection? Or is my code for fetching the data incorrect?

Thanks

If you are using the MPU6050 library from jrowberg/i2cdevlib, the library does not have any kind of error handling, so it is unfortunately not easy to guess what went wrong, or even if something went wrong. If the getMotion6 function fails, it will simply copy corrupt data into your return values and it is not possible after the invocation to tell if the function succeeded and you got a valid reading, or if the function failed and you only got garbage back.

One possible problem is that the MPU6050 can be configured to use one of two I²C addresses (0x68 or 0x69) and you are using the default address, as implemented in the MPU6050 library (0x68). It might be worth to try the other address, in case your module is configured that way:

MPU6050 accelgyro(0x69);


creating HTTP persistent connection, to create 'smooth' data over GSM sending Project goals

Send data over GSM to firebase
Fast sampling - need to send 16 bytes every half second to firebase
Send data using GET or POST to server with PHP script, that redirect data to firebase

Problems --
Extremely low data rate!

Using standard GET or POST request from client(arduino) side, is impossible to achieve second (2) project goal.
To send data correctly I need to close connection with server, so next data package unfortunately waits(2-6 seconds) for establishing a new connection.

Is this quite nonsense? I'm using ArduinoHttpClient library.

My actual Nonsense Connection and fully useless, but works

while(1){

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server

//next instruction take over 5 second to establish new connection :(

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server, whyyy?
}

Data are send once per 2 - 6 seconds, this is not even funny. NEED to send data every 0.5 seconds!

So I decided to create super solution, which not works :C

while(1){
    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    delay(xxx);
//no connection closing, no wasting time for establishing new one :)
}

Just tell my why this connection is not "Keep-Alive", also used with

  http.sendHeader("Connection: Keep-Alive"); or
  http.connectionKeepAlive();

//First run
http.post(blabla);// returns value: 0 & data are logged into firebase
//Second run
http.post(blabla);// returns value: -2 & data are not logged in firebase

my test.php file

<?php
require_once 'firebaseLib.php';
$url = 'https://czujniki-aa5ca.firebaseio.com/';
// --- Use your token from Firebase here
$token = ':-CCCCCCCCCCCCCCCCCCCCCCC';

$arduino_data_post = $_POST['data'];
$firebasePath = '/';

$fb = new fireBase($url, $token);
$response = $fb->push($firebasePath, $arduino_data_post);
sleep(2);

The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.

The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.

In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.


Custom arduino board Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:

Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?

In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!

I have a page about a breadboard Arduino which is basically an Atmega328P processor (same as in the Uno, inter alia) on a breadboard.

Also a wire-wrapped Arduino.

You can go pretty minimalistic with a ATtiny85 mounted on a button battery like this:

  Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board?

Ah there you might be asking a bit much. There are hundreds, if not thousands, of shields people have designed for it. Certainly you can make up your own board to meet a specific purpose.


UltraSonic Sensor wirh ESP-01 Standalone I'm trying to build a cheap device to measure water level in a tank using HC-SR04 sensor and ESP-01 which send the data to MQTT topic. I used the same code with ESP-E12 which works just fine. As I'm trying to drive the cost down with ESP-01, I faced a problem with I/O pins. I searched the web and found some contradicting info about which pins could be used in this case.
So here is the schematic of my setup:

Coming to the ESP-01, I used a USB adapter to program it and the code uploaded successfully. Here I'm just showing the Ultrasonic sensor part which I believe I have issues with.

#define echoPin 2 // Echo Pin
#define trigPin 0 // Trigger Pin

long duration, distance; // Duration used to calculate distance

void setup(){
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
  Serial.println(distance);
  delay(200);
}

I read somewhere in the internet that GPIO2 can't be used and must be replaced with Rx = GPIO3. However, I tried that and it didn't work too.
So the question here, am I really using the right pins or is it really possible to do that with esp-01?

There are 2 things here.
Ultrasonic sensor works on 5V while ESP on 3.3V. So your sensor is sending 5V signal to ESP. It might fry your board but I believe it has a safety cut off of everything above 3.3V and that's the reason your application is not working.
Cheap solution would be adding voltage divider to your Echo pin:
https://randomnerdtutorials.com/how-to-level-shift-5v-to-3-3v/
but then you will face the issue mentioned by Juraj above.
You may then overpass that issue manually or look for more sophisticated (expensive) solution.


How to read a 25 kHZ PWM signal from PC fan header? I would like to control a DC motor's speed using the PWM output from my motherboard header.

Here's the standard pinout for a 4-wire PC fan header:

╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝

Since my DC motor doesn't have a PWM input, I thought of using an ATmega328P in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.

However, I'm not sure how I should read the PWM signal from the motherboard.

What is the HIGH voltage level of PWM output?
Do I need a voltage divider resistor for it?

A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.
Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
  Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the documentation for pulseIn() says:

  Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%

What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.

However since you want to

  ... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

  ... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

  A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!


Serial not working with I2C I have been working on a hydroponic garden that is controlled with Arduinos. I have everything working except for the user interface. What I would like to do is have an LCD screen paired with a rotary encoder for use on the garden, and an ESP8266 WiFi module set as a server working with a custom Android app that I am writing.

I have been working on writing the app and the code that will allow the Arduino and the app to talk to each other, but I have been running into a problem. Sometimes the serial data between the ESP266 and the Arduino is not being picked up by the Arduino. I have verified that the data coming out of the WiFi module is correct, but the Arduino seems to be missing characters. This seems to happen almost at random. Sometimes it will work, and other times it will simply get stuck. I used a SoftwareSerial library to add an extra serial port and printed what the Arduino was receiving from the WiFi module, and it just seems to be missing random characters.

Up until now I have had the WiFi module connected and the LCD screen. I was using the LCD screen to display debugging messages. I took the LCD screen off and deleted all the LCD code and now everything seems to work just fine.

The LCD screen uses I2C.

Why does disconnecting the LCD screen solve the issue? Is there a way to make both run at the same time? The LCD uses I2C. I am unaware of anything that would prevent this from working.

Thanks.

Explanation

The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.

So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.

Solution

What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the NewSoftwareSerial library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.


I want to move the mouse pointer with an Arduino and ultrasonic sensor I want to move the mouse pointer with an Arduino and ultrasonic sensor but when I compiled it says

  Mouse.h not found

and I don't know what I can do.

Here is my code;

 #include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

    //mover el cursor
  int direccionx=moverx();
  int direcciony=movery();

  Mouse.move(direccionx, direcciony,0);
  delay(2);

}

int moverx(){
      distanciaCursor=obtener_distanciaCursor();
  if (distanciaCursor >= 1  || distanciaCursor <= 11){
       x--;
     }
   if (distanciaCursor >= 12 || distanciaCursor <= 24){
       x++;
      }
     return x;
}

int movery(){
      distanciaCursor=obtener_distanciaCursor();
     if (distanciaCursor >= 25 || distanciaCursor <= 37){
       y--;
       }
   if (distanciaCursor >= 38 || distanciaCursor <= 50){
       y++;
      }
  return y;
}

long obtener_distanciaCursor(void)
{
  digitalWrite(trigPinCursor, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPinCursor, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPinCursor, LOW);
 duracionCursor = pulseIn(echoPinCursor, HIGH);

 distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

That's because the Uno can't be a mouse.  For that you need the Leonardo or something else with a similar "U" style microcontroller.

If you are adventurous, and you have a genuine Arduino, you can reprogram the USB controller chip with new firmware so it thinks it's a mouse, but programming the main MCU is then a real chore.


error at compiling : 'class TwoWire' has no member named 'setClock' I am a newbie C programmer and I just started with Arduino web editor (Win10-Firefox)to code for a Raspberry Pi (3B) board. RPi is on line via ethernet connection.
I tried to compile an example from Garmin Lidar_lite v3HP for I2C, as available in the library collections for Arduino.
When compiling the example I get after a while this error message:
Using library Wire in folder: /home/builder/.arduino15/packages/arduino/hardware/mraa/1.0.8/libraries/Wire (legacy)
Using library lidar_lite_3_0_3 at version 3.0.3 in folder: /home/builder/opt/libraries/latest/lidar_lite_3_0_3
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino: In function 'void setup()':
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino:51:18: error: 'class TwoWire' has no member named 'setClock'
Wire.setClock(400000UL); // Set I2C frequency to 400kHz (for Arduino Due)
^
exit status 1
Checking the arduino forum I find some similar question, but of many years ago and likely not applicable any longer.
I appreciate your expert inputs on how to resolve in simple terms.
Thanks a lot! Greetz, Ivan

Thanks for the reply. I tried again with the arduino on PC with RasPiDuino librarie and had no further problem. The resulting executable does work on a RPi3 with Buster OS. Apparently the arduino webeditor lacks some libraries to succesfully compile for raspberry . I continue this road. Item can be closed.


Arduino nano IoT antenna broke I have an Arduino Nano 33 IoT and have used it for a good time now. I was using it when the antenna snapped off. Is there any way to fix it by either an external antenna or some other method? I tried to just hold the antenna in place as I tried to connect to wifi but it failed to connect.

The problem that I see in the photo is that the pads from the PCB are pulled off and attached to the antenna. So now there is nothing to solder the antenna back to.
While it's possible to rework this with some solder rework tools, I suspect you don't have those.  There is really not much else you can do but replace the Nano with a new one.  You should still be able to use this one for an application that doesn't need WiFi.
It looks like the two active leads (the two in the upper right-hand side of the green module may be those) are still intact.  If you have a small tip soldering iron and a steady hand you may be able to put a tiny drop of solder on both of them and then resolder the antenna to them.  You could support the antenna with some silicone caulk or other non-conductive adhesive after you get it attached.
Keep in mind, that this is tricky to solder by hand but there is little to lose since that part of the module is not non-functional anyway.


What is the maximum "wattage" can be pushed into an ATMega328 ADC pins? I was doing some Ohm's Law calculations to calculate the voltage output from a 2-resistor voltage divider, the input will be with a maximum of 12 volts, I want the ATMega328 to measure that voltage, so I simply thought of putting two resistors in series with values of 330 ohms and 220 ohms like this:

simulate this circuit – Schematic created using CircuitLab
Theoretically on paper the maximum voltage outputting from the node going to the ATMega328 is ~4.8V, but I want a special safety feature, I want to put in mind that at anytime the ground connection can be hung open (to simulate a lose breadboard connection, bad soldering joint etc...) now based upon my understanding if there is no ground connection, the voltage going to the Arduino will be 12V which is a killer, as after looking on the ATMMega328 datasheet it states that

28.1 Absolute Maximum Ratings. Voltage on any pin except RESET with respect
to ground => VCC + 0.5

The current will be limited by the 330ohm resistor to only 36mA which I think is a lot, I thought of doubling the resistors values to 330000 and 220000 by that the current will be limited to only 36uA. Again based upon my understanding there is still 12V going to the Arduino but wouldn't it directly drop if the ground connection was cut off ? That's why I ask what is the maximum input power to an Arduino?

This is actually a special case that is undocumented, and in fact not as simple as you would at first think.
The input port itself is not actually what is in question here. Instead every IO pin on the Arduino, be it set to INPUT or OUTPUT, has a set of ESD protection diodes on them. These look like this:

simulate this circuit – Schematic created using CircuitLab
The "IO MODULE" when in INPUT mode can pretty much be ignored, since it is a very high impedance. Just like a (roughly) 10MΩ resistor to ground. Very very little current will flow that way.
D2 is also reverse biased so that direction can be ignored.
So the current will want to flow through D1 to the VCC rail (+5V).  The diodes have approximately a 600mV forward voltage (which is where the VCC + 0.5 comes from).
So we can recalculate, given those parameters, what the current flowing through the diode will be to the 5V rail:

Voltage difference = 12V - 5V - 0.5V = 6.5V
Current = V/R = 6.5/330 = 19.7mA

The recommended maximum (from what I can gather) is only 1mA.  You have 20x that.
So you will need at least 20x higher resistances. 10kΩ in the upper half and 6.8kΩ in the bottom half.  That will give you 4.85V on the output at 12V and limit you to 0.65mA in a failure situation.
It also gives you an output impedance of a little over 4kΩ which is below the recommended maximum of 10kΩ for the ADC input.
You can further protect your input by adding a 5V zener diode and small series resistor on the ADC pin so if the voltage goes above 5V it clamps it and protects the pin.

simulate this circuit


How to programme a button per colour for a neopixel strip? I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinke
#endif

#define BUTTON_PIN1  2
#define BUTTON_PIN2  10
#define BUTTON_PIN3  11
#define PIXEL_PIN    6  // Digital pin 6 connected to the NeoPixels.

#define PIXEL_COUNT 13  // Number of NeoPixels

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);

boolean oldState1 = HIGH;
boolean newState1 = HIGH;

boolean toggle1 = LOW;

boolean oldState2 = HIGH;
boolean newState2 = HIGH;

boolean toggle2 = LOW;

boolean oldState3 = HIGH;
boolean newState3 = HIGH;

boolean toggle3 = LOW;

void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show();  // Initialize all pixels to 'off'
}

void loop() {
updateButtonState1();
updateButtonState2();
updateButtonState3();

}

void updateButtonState1() {

 // Get current button state.
 newState1 = digitalRead(BUTTON_PIN1);

 if ((newState1 == LOW) && (oldState1 == HIGH)) {
 delay(50);
 newState1 = digitalRead(BUTTON_PIN1);
 if (newState1 == LOW) {
   toggle1 = !toggle1;
  }
 }
 oldState1 = newState1;

if (toggle1 == HIGH) {
strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}

void updateButtonState2() {

// Get current button state.
 newState2 = digitalRead(BUTTON_PIN2);

if ((newState2 == LOW) && (oldState2 == HIGH)) {
 delay(50);
 newState2 = digitalRead(BUTTON_PIN2);
 if (newState2 == LOW) {
   toggle2 = !toggle2;
   }
  }
 oldState2 = newState2;

  if (toggle2 == HIGH) {
  strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
  } else {
  strip.setPixelColor(2, 0, 0, 0);
  }
 strip.show(); // Update strip with new contents
 }

 void updateButtonState3() {

 // Get current button state.
 newState3 = digitalRead(BUTTON_PIN3);
 if ((newState3 == LOW) && (oldState3 == HIGH)) {
  delay(50);
  newState3 = digitalRead(BUTTON_PIN3);
  if (newState3 == LOW) {
    toggle3 = !toggle3;
  }
 }
 oldState3 = newState3;

 if (toggle3 == HIGH) {
 strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
 } else {
   strip.setPixelColor(2, 0, 0, 0);
  }
  strip.show(); // Update strip with new contents
}

You do not really have to use an array for this, though I do agree that it's the cleanest solution.

Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.

Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.

void setup() {
  //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
  uint32_t magenta = strip.Color(255, 0, 255);
  uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

  //https://www.arduino.cc/reference/en/language/variables/data-types/array/
  uint32_t colors[] = {magenta, greenishwhite};
  unsigned char totalColors = 2;
  unsigned char currentColor = 0;
}

void loop() {
  if (buttonpressed) {
    //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
    currentColor++;
    if (currentColor >= totalColors) {
      currentColor = 0;
    }

    //From the array of colors, pick the one with the index "currentColor" and show it.
    ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
    ledstrip.show();

    buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
  }
}

You should be able to replace the first 3 lines (setting up the array) with a single:

uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

But I had it split up to better show the idea of the array.

Alternatively you could do:

switch(currentColor){
  case 0:
    //Color RED
  break;
  case 1:
    //Color GREEN
  break;
  case 2:
    //Color BLAUW
  break;
}


How many bits can an Arduino uno read? What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.

The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).

Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.

Cheers!


Run 5V/2.3W water pump on Arduino Pro Mini 5V I want to build up my automatic water pump with an arduino pro mini 5v and a 5v usb water pump (2.3 W). As I understand, I cannot power the pump directly through the vcc pins of the board, right?
Would it be possible to place a female USB Port in my system to power the board and the pump through a relay on the board? What would be an appropriate circuit diagram?

Hi Florian you can take power from USB fro both Arduino and the water pump.This is the schematic you have asked for your project. An arduino Pin can give maximum 20mA current that's why we need a limit resister to limit the current below 20mA and also this current should be such a way that it can drive the switching transistor. So the challenging thing is choosing the correct resister
I have taken the value 1K
So the current at Arduino Digital pin is Current I = 5V/1k = 5mA which is below of 20mA and sufficient to drive the Transistor. you can use BC548 transistor also.

simulate this circuit – Schematic created using CircuitLab


SPI communication Problem Arduino I'm trying to set up SPI communication between two Arduinos (UNO and Mega),
I want to read the status of the slave output pin from the master.

I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct.
I used another code I found online.

MASTER code

#include <SPI.h>
const byte btn =8;

void setup(void) {

Serial.begin (9600);
pinMode (btn, INPUT_PULLUP);
digitalWrite (SS, HIGH);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV8);

}

void loop(void) {

byte Mvalsent,Mvalreceived;
digitalWrite (SS, LOW);
for (int jj=0; jj<255; jj++)
  {
      Mvalsent =jj;
      Mvalreceived =SPI.transfer (Mvalsent);
      Serial.print ("Retou d'etat ");
      Serial.print (Mvalsent);
      Serial.print ("\t ,l'etat de la diode est ");
      Serial.println (Mvalreceived);
      delay (400);
  }

  digitalWrite (SS,HIGH);

}

SLAVE Code

#include <SPI.h>
byte state;
const byte led =9;
volatile boolean process_it;
volatile byte Svalreceived, Svalsent;
int jj=0;
void setup (void)
{
  Serial.begin (9600);
pinMode (led,OUTPUT);
//set MISO pin as output
pinMode (MISO, OUTPUT);
//turn on SPI in slave mode
SPCR |= _BV (SPE);
//get ready for an interrupt
process_it = false;
//now turn on interrupts
SPI.attachInterrupt ();
}
ISR (SPI_STC_vect)
{
  Svalreceived = SPDR;
  process_it =true;
}
void loop (void)
{
 if (process_it)
 {

   digitalWrite (led, LOW);
   state =digitalRead(led);
   SPDR = state;
   Serial.print("l'etat de la diode est: ");
    Serial.println (state);
    delay (400);

    process_it =false;
  }
}

Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).

And you still keep the SPI for a microsd card adapter, for example.

Follow this official tutorial:

MASTER ARDUINO 1

// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

SLAVE ARDUINO 2

// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).


I need a good battery reccomendation I have simple project composed of an Arduino Nano, a HC-05 module, and a small toy DC motor controlled using a L293D driver, I want to be able to power this circuit entirely using a battery, here is what I tried:
-The motor/L293D combo works when the Arduino Nano is powered through it's USB jack, except the L293D is drawing power from the Nano, which I know is very bad practice, but I only did it for testing purposes.
-The HC-05 module also works fine when the Nano is powered through it's USB jack, as expected.
-However, the power received through the USB jack is not enough power for both the HC-05 and the L293D & motor simultaneously, if I want to change the PWM through the HC-05, I have to disconnect the motor, send the instruction, then disconnect the HC-05 and re-connect the motor.
-I have tried 3, pretty much new 9V batteries, none of them were enough to power anything, not the Nano board through the Vin pin, not an Uno board through barrel plug, not the motor, nothing, except a LED diode, I've read somewhere that most brands of these kinds of batteries don't actually provide nearly as much power as they claim, so that might explain it. (In case it's relevant, the brands I tried are VARTA, Uniross and Goldmen.)
-Someone gave me the idea of using an old mouse cable to power the Arduino, by taking the VCC and GND wires from the mouse cable and using those to power the Nano board through it's Vin and GND ports, it works, but not any components connected to it, not even the HC-05 module, which I even tried powering directly from the mouse cable, which lit up it's LED, but did not get it to work.
Honestly this isn't that relevant, I just wanted to make sure the Vin pin worked.
-Also, few side notes:
My multimeter mysteriously stopped working when I actually needed it, which is why I couldn't take any measurements.
The L293D datasheet and other pinouts suggest no less than 12V supply voltage, so maybe a 9V battery wasn't the right answer to begin with.
The power coming from the mouse cable is enough to power the DC motor independently, but not through the L293D, it says online the average output for these cables is around 5V, but without measurements I can't be sure.
The battery holder for the toy train that has DC motor inside accepts 1.5V batteries wired in series, and considering there's not much else there aside from the motor itself, it's safe to say that 3V is the minimum required voltage for the motor.
So, what battery do you think would be most suitable for my project?
And if it's not against the rules, what brand would you recommend?

The L293D has about a 2.6V drop on the output pins. That means for a 3V motor you need to provide about 5.6v for it to run at full speed. 5V will work, but it will run slightly slow and underpowered.
9V batteries are useless. Only any good for very low power applications like smoke alarms. They just can't provide the current you need.
Instead you need to be looking at model aircraft / drone suppliers for a "2S" battery (7.4V Li Poly / Li Ion) and a suitable 5V (or 5.6V if you can get it) UBEC (switching regulator).


WiFi connection in loop function What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:

setup(){
    wifi.mode(WIFI_AP_STA);
    setup softAP
    server.on("/",handleroot)
    server.begin()
}
loop(){
    server.handleClient()
    if(credential_submited){
        Wifi.begin(credentials);
        flag_connection_started =true;
        credential_submited = false;
        flag_for_internet_server=true;
    }
    if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
        server.on("/",handleroot)
        server.begin()
        flag_for_internet_server=false;
    }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.

You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().

BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.


Run an Arduino without a PC I would like to use an Arduino to make tasks in my life automatic - maybe to rotate every morning a motor, or to open a door.

So, can I run an Arduino as solo with no pc needed? Can i connect it to the Internet and can I setup software like PHP and Apache on it to control it over the internet? Has it any protocols like SSH like a normal server?

As an example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino would run a function...

Is that possible?

thanks ahead

I will use arduino to make tasks in my life automatic maybe to let rotate every morning a motor or to open the door.

That's the kind of thing it's designed for.

  So i will ask can i run arduino as solo so no pc needed,

Yes, you only need a PC to program it, once programmed it will run without the PC.

  Can I connect it to the internet

Yes, there are Ethernet and WiFi shields available for connecting it to a network.

  and can I setup PHP and Apache on it to control it over it; has it any protocols like SSH like an normal server ?

No.  The Arduino isn't powerful enough to run software like that.  You would normally connect it via the network / internet to a server to process data.  It would just receive simple instructions or send data to the server for processing.

  as example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino is running a function...

I assume by "a certification" you want to run SSL on the Arduino. That's not going to happen since it's way too underpowered for that.  As I mentioned earlier, the Arduino would connect to a server on the internet to receive its instructions, or you could interface to it directly within your local network (say from a smart phone) through a simple web server interface (very simplistic due to lack of memory - a few buttons and text, that sort of thing).


I can't upload my program to Arduino Uno I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

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

I reset immediately after uploading but it doesn't work.What else should I do?
I'm using Ubuntu and the Arduino IDE.

Checks:

Check if the board has power (probably it will).
Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
Check if you have multiple versions of the IDE running.
Check if you have multiple IDEs installed.
Check if you don't have the RX pin used while uploading a sketch.

Try the following:

Use a different USB port on your computer
Use a different USB cable
Reinstall the Arduino IDE


How to split a *char and pass to a function needing uint8_t? I have a requirement where an event has char *newvalue.

void event(char *newValue) {
//Code here
}

newValue is 2 digits. If it's 1-9 it is " 1" " 2" and 10+ is "10" "11" etc. It also can contain alpha characters as well not just numbers.

I am passing this to a function void function(uint8_t ascii) to display on a single digit display. If I pass newValue it doesn't register less than 10 as it picks up the space.

So what I am trying to achieve is if it's a single character, strip the space somehow into a uint8_t and if it's 2 digits strip just the right digit as a uint_8 and have a bool where I will turn on the decimal point.

I've googled like crazy and can't seem to get something workable. If somebody can help it would be appreciated. If the above is not clear please let me know what more info you need.

The code below, 'value here' is where I want to put the rightmost value from *newvalue.

void onUfcComm2DisplayChange(char *newValue) {
  comdisp.setBrightness(9);
  comdisp.writeDigitAscii(0, 'valuehere');
  comdisp.writeDisplay();
}

void Adafruit_AlphaNum4::writeDigitAscii(uint8_t n, uint8_t a,  boolean d, boolean w) {
  uint16_t font;
  if (w == false) {
    font = pgm_read_word(alphafonttable + a);
  } else {
    font = pgm_read_word(alphafonttableWD + a);
  }
  displaybuffer[n] = font;
  if (d) displaybuffer[n] |= (1 << 14);
}

I'm not real clear on exactly what you want to have there, but here are a few ideas that may help:

If you know what character you want, then just get it.  Like if you always want the second character (I think this is what you need):

void someFunc(char *p)
{
  char secondChar = p[1];
  Serial.print(secondChar);
}

If you just want the last character in the string no matter how long, get the length of it and then pull that character:

void someFunc(char *p)
{
  int len = strlen(p);
  char lastChar = p[len-1];
  Serial.print(lastChar);
}

If you want the last digit in the string no matter how long and no matter how many random characters that aren't digits after it:

void someFunc(char *p)
{
  int len = strlen(p);
  char lastDigitChar = 0;
  // Cycle backwards til we get the first digit
  for(int i=len-1; i>=0; i--){
    if(isDigit(p[i]){
      lastDigitChar = p[i];
      break;
    }
  }
  Serial.print(lastDigitChar);
}


Help needed to add and extra sensor I am new to Arduino, and already tried to edit this many time. But I cant figure out whats wrong.

The following code has a PIR sensor, 1 LED and 1 buzzer.
I want to add one more PIR sensor, but it should trigger a separate LED , and the same buzzer. In serial monitor.
I have searched many sketches, but all of them seems to have a different method , cant figure out the basics!

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

Well, after playing with the code for some time, I just did it!!
pasting the updated code here, may be useful for someone else like me..

int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 2;               // choose the input pin (for PIR sensor)
int inputPinB = 4;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

Link to circuit and virtual demo


How do I connect two slaves of same type in I2C? I am not experienced about I2C communications, but I do happen to have two HMC5883L magnetometer modules that I wish to connect to a single arduino. It uses I2C protocol, and hence the slave device will have a fixed address. Now Can I change the address of one of my sensors so that the Arduino can differentiate between the two? (I seem to find no way out by reading the datasheet)
Thanks in Advance
Siddharth Jha

P.S. Can an MPU 6050 module be used to find angle of rotation in X-Y plane (Parallel to the ground)?

The problem is with the magnetometer:
"The HMC5883L has a fixed I2C address, you can only connect one sensor per microcontroller!"
Wiring and Test

Also, it says it in the specs on page 2:
 I2C Address
8-bit read address 0x3D
8-bit write address 0x3C
3-Axis Digital Compass IC HMC5883L

Low cost magnetometers appear to have fixed I2C addresses. One solution would be to get a different one in addition to yours. For example, the MAG3110 has I2C address 0x0E and the FXMS3110CDR1 has I2C address 0x0F.
Xtrinsic MAG3110 Three-Axis, Digital
Magnetometer

More information on this page:

How to connect multiple of the same device to an Arduino using I2C?

P.S. You are more likely to get an answer to your second question by posting it separately (and help others in the process).


Can the Adafruit PN532 NFC/RFID be used to read Gen-2 EPC class RFID Tags? I used Mifare Classic cards on a previous project and it worked brilliantly with the RIFD/NFC shield and Arduino Uno. I came across a Gen 2 EPC Class 1 RFID tags. This tags are long range ones. They use an IC chip called Alien Higgs3. I know that the shield itself is not capable of reading from a long range. I would just like to know if the shield is just able to read this type of tag even in close contact.

Is there a UHF RFID Reader that I can use to connect it with the Arduino and read these tags?

Any advice or suggestions are welcome. Thank alot.

RFID Tag Specifications:

Protocol- EPC Class 1 Gen2
Frequency- 860-960 MHz
IC Type (chip)- Alien Higgs3

It can not. The frequencies are different: 13.56MHz vs.868–956 MHz.


Arduino Uno (master) and ATTiny85 (slave) I2C connection not working I am trying to send and receive data using I2C between an Arduino Uno and an ATTiny85. The Arduino Uno is using the Wire library. The ATTiny85 is using the TinyWire library and is programmed (and powered) using the Sparkfun Tiny AVR Programmer.

I am not receiving any data.

Arduino Uno I2C master code

#include <Wire.h>

#define SLAVE_ADDR 0x50

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

void loop()
{
  Wire.requestFrom(SLAVE_ADDR, 1);

  while(Wire.available())
  {
    byte byteReceived = Wire.read();
    Serial.println(byteReceived, DEC);
  }
}

ATTiny85 I2C slave code

#include "TinyWireS.h"

#define SLAVE_ADDR 0x50

void setup()
{
  TinyWireS.begin(SLAVE_ADDR);
  TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
  byte byteToSend = 23;
  TinyWireS.send(byteToSend);
}

I modified your Uno sketch slightly to add a delay:

#include <Wire.h>

#define SLAVE_ADDR 0x50

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

void loop()
{
  Wire.requestFrom(SLAVE_ADDR, 1);

  if (Wire.available())
  {
    byte byteReceived = Wire.read();
    Serial.println(byteReceived, DEC);
  }

 delay (1000);
}

Upon testing, it worked perfectly!

23
23
23
23
23
23
23
23
23
23
23
23

I suggest a wiring error. Check you have:

Uno    ATtiny85
--------------------
A4      pin 5  (SDA)
A5      pin 7  (SCL)
+5V     pin 8
Gnd     pin 4


json format in esp32 with arduino json I am using an ESP32 module for bluetooth connection and scaning wifi network. But I cannot format the json using arduinojson library in the way I want.

void scanWifiNetworks() {
  //creating json
  DynamicJsonDocument jsonDoc(1024);
  char jsonBuffer[512];
  JsonObject wifiJsonObject = jsonDoc.createNestedObject("wifiList");
  wifiJsonObject["ssid"];
  Serial.println("scan start");

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

      wifiJsonObject["ssid"] = WiFi.SSID(i);
      serializeJsonPretty(jsonDoc, SerialBT);
      serializeJsonPretty(jsonDoc, Serial);
      delay(10);
    }
  }
  Serial.println("");

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

The output is like this

scan start
scan done
5 networks found
{
  "wifiList": {
    "ssid": "quark"
  }
}{
  "wifiList": {
    "ssid": "Airtel_Zerotouch"
  }
}{
  "wifiList": {
    "ssid": "NETGEAR77"
  }
}{
  "wifiList": {
    "ssid": "Itobuz-technologies"
  }
}{
  "wifiList": {
    "ssid": "Nokia 6.1"
  }
}

what I want is something like that

{
      "wifiList": {
        "ssid1": "quark1",
         "ssid2": "quark2"
     }
}

I know I am looping in a wrong way but could not figure it out. if possible please pointing out the right direction will help a lot.

You are repeatedly overwriting the ssid property of the same object.
Instead, you want to write different properties, like

wifiJsonObject["ssid" + String(i+1)] = WiFi.SSID(i);

Then, only serialize the document once, when it is complete.

That being said, I strongly concur with Juraj in that the correct way to
represent a list in JSON (and wifiList is clearly meant to be a list)
is by using an array:

void scanWifiNetworks() {
    DynamicJsonDocument jsonDoc(1024);
    JsonArray wifiList = jsonDoc.createNestedArray("wifiList");
    int n = WiFi.scanNetworks();
    for (int i = 0; i < n; ++i) {
        JsonObject wifiNet = wifiList.createNestedObject();
        wifiNet["ssid"] = WiFi.SSID(i);
    }
    serializeJsonPretty(jsonDoc, SerialBT);
    serializeJsonPretty(jsonDoc, Serial);
}

This should produce a JSON document that looks like this:

{
  "wifiList": [
    { "ssid": "quark" },
    { "ssid": "Airtel_Zerotouch" },
    { "ssid": "NETGEAR77" },
    { "ssid": "Itobuz-technologies" },
    { "ssid": "Nokia 6.1" }
  ]
}

Edit: Note that, if it's clear from the context (e.g. a request URL)
that you are transmitting a list of WiFi networks, then you can get rid
of the outer object and the "wifiList" label, and use the array as the
JSON document:

[
  { "ssid": "quark" },
  { "ssid": "Airtel_Zerotouch" },
  { "ssid": "NETGEAR77" },
  { "ssid": "Itobuz-technologies" },
  { "ssid": "Nokia 6.1" }
]

As suggested by Jaromanda X, if you are never going to extend the inner
objects with extra information, you can further simplify the document by
removing those objects and just listing the SSIDs in the array:

[
  "quark",
  "Airtel_Zerotouch",
  "NETGEAR77",
  "Itobuz-technologies",
  "Nokia 6.1"
]


Issue with Speck cipher on Arduino UNO I found a library for the Speck cipher here: https://github.com/Chien-Ning/ArduinoCrypto

And I'm trying to use but haven't had much luck. My code is the following:

#include <SPECK_AVR.h>
#include <SPECK_spec.h>

#include "SPECK_AVR.h"

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

  SpeckTxtLen = 32;
  SpeckKeyLen = 64;
  speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

  speckKey();
  speckEnc();

  Serial.println("");
  for (int i = 0; i < SpeckTxtLen/8; i++){
  Serial.print(speckTxtKey[i], HEX);
  Serial.print(", ");
  }
}

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

}

And I'm getting this error:

error: lvalue required as left operand of assignment

and

error: expected primary-expression before ']' token

Do you think I'm missing something in the usage of this library?

Thanks in advance

speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

That's not how you assign an array.
And you never defined a type for the array.

It sould be:

byte speckTxtKey[] = {0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00};

EDIT:

I checked the source of the library to figure out how to use it, but it doesn't seem the library is meant for actual use.

SpeckTxtLen and SpeckKeyLen are macros inside SPECK_AVR.h, which are supposed to be changed there, not in your code.

The library also defines speckTxtKey inside SPECKenc_AVR.cpp with predefined test data based on the chosen length.

This library looks like a test implementation of the speck cipher, which was just dumped onto GitHub.


Passing a reference as a variable I have a function for manually jogging a stepper motor using the AccelStepper library. At the beginning of the function I would like the motor in question to be selected until told to stop.

Here is what I imagine it would look like:

AccelStepper X_Axis(AccelStepper::DRIVER, 3, 2);
AccelStepper Y_Axis(AccelStepper::DRIVER, 5, 4);
AccelStepper Z_Axis(AccelStepper::DRIVER, 7, 6);

void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  if (Dir == 0){i = 1;}else{i =- 1;}
  setSpeed(i * Spd);
  switch(axis)
    {
      case 1:
      axis = X_Axis;
      break;

      case 2:
      axis = Y_Axis;

      case 3:
      axis = Z_Axis
    }
  while (!Serial.available()){

      axis.runSpeed();
    }
  }

The axis variable should map to whichever axis is called and so control the desired stepper.

How can I achieve this?

Note: I submitted this to StackOverflow with no response. Any help would be appreciated

To do it in the form you have, you would want to use a pointer.

void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  AccellStepper *thisAxis = NULL;

  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  switch(axis)
  {
    case 1:
      thisAxis = &X_Axis;
      break;

    case 2:
      thisAxis = &Y_Axis;
      break;

    case 3:
      thisAxis = &Z_Axis
      break
  }

  if (thisAxis != NULL) {
    while (!Serial.available()) {
      thisAxis->runSpeed();
    }
  }
}

Briefly: the & before the name of a variable in assignment means "Give me the address of this variable".  A * before a variable when declaring that variable means "Make this variable hold the address of another variable of this type".  You then have the address variable hold the address of your chosen axel, and then "dereference" that with the "poiner dereference operator" -> (instead of using .).

A check is added to see if thisAxis has actually been assigned anything or not, although you could use the default: case in your switch to abort on an invalid axis number instead.

Depending on how the rest of your program works, though, it may be possible to not use the "axis" integer at all, but pass a reference to the correct stepper to the function:

void ManualJog(int Dir, int Spd, AccelStepper &axis) {
  int i;
  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  while (!Serial.available()) {
    axis.runSpeed();
  }
}

In this example the & before the axis variable in the function prototype means "Pass me the address of the variable", and a new variable is created located in the same memory space. This is the pass by reference operator in C++.


Is there any way to check with Arduino UNO if a sensor is connected and ready to be read? I would like to check the status of the sensors with Arduino UNO. For example, when I turn on the robot, I would like to check if all the sensors are connected and ready to be read or not. Maybe one sensor is unplugged and I want to detect this situation.

I read something about pull up resistors, but I didn't find any clear example of my problem. Also, I don't have any idea how to connect the resistor, how to calculate the resistor needed, as well as how to use the pull up resistor for digital and analog sensors.

Any schema, explanations and example would be very helpful!

Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.

So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.


how to push data from an Arduino pin to Bluetooth module I'm writing a software that can receive data from Arduino via Bluetooth. My software is pretty fine now, at least it can pair with my hardware but when I try to test whether it can receive data via Bluetooth, I'm stuck. My Arduino receives temperature readings from a sensor at Analog pin 0. My Bluetooth module HC-05 connects with Arduino at Digital 0 and 1 (RX and TX pin respectively, as default). I don't know how to push data from Analog pin 0 to the Bluetooth module. Thanks in advance for any suggestion.

The HC-05 looks like like any other terminal to the Arduino so any serial operations that you would use for a wired terminal can be used with the HC-05. See the HC-05's manual for how to set it up initially. Note that HC-05s don't forget their settings and they have no reset command to put them into a known state, so write down your settings for your future reference.

- Read the analog pin value;
- Convert the value into whatever physical units you require;
- Print the result with Serial.print() or Serial.println()

Edit:  You wrote that your HC-05 is connected to Digital 0 and 1, but you created your SoftwareSerial, mySerial, to transmit on Digital 11. In that case your HC-05's receive pin must be connected to Digital 11.


Distance and Serial or SPI I'm setting up a grid of 200+ slave modules which will be about 12 inches apart and the master will be anywhere from 5 to 10 meters away from the closest module. Each slave module will have a ATtiny85 to manage the sensor reading, LEDs and the network protocol.

The communication packets will be small and will probably be at 115200 baud if using ATTiny85's TTL serial or 1MHz if using SPI. In either case, the modules will be connected in a daisy chain to each other.

Each module will have a resistive touch sensor and be driving about 12 - 16 RGB LEDs (I'm making a step responsive disco dance floor). There will be 12v+ running to each module to drive the LEDs and regulated down to 5V for the ATtiny.

Which brings me to my question. With these constraints, do you think the ATtiny85's built-in serial or SPI would still work well over the 5 to 10 meters from the closest module to the master.

I know some people push towards RS422 or RS485 transceivers for distance applications, but I'd like to keep the total part count down, if possible.

I have a few years working with DMX, SPI (and other serial) & LEDs. I have worked with DMX and a video dance floor for 10+ years previously. I would offer that "some people" are correct. You will get a reliable system with differential pair signalling (such as DMX).
I have found from experience that over 5m of unbalanced serial starts chancing it. Over 10m and you are likely to come up with at least reliability issues, but more likely garbage.

I have used the TI SN75176B driver a fair bit and is cheap and works.

Depends on your audience. You can afford to chance it for your bedroom, but not paid business.


Programming Arduino Pro mini 328 with Arduino Uno SMD I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.

I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).

I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?

Thank you for your help.

check this tutorial:

  http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:

UNO BOARD (SMD)    Pro Mini 5V
       GND             GND
       5V              VCC
       RX              RX1
       TX              TX1
       Reset           GRN


How to send messages to multiple numbers using Arduino uno & SIM800 module? I am using following code to send message using Arduino Uno & SIM800 module.
But I need to send same message on multiple numbers then what changes should I make in my code.

const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
  void sensor1()
  {
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91...................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is Closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91........................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
  }
  void sensor2()
  {
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

@nilesh just add some delay between two massege

I modified your code check it

const int Main1 = 8;
const int Main2 = 9;
const int Store1 = 7;
const int Store2 = 10;
bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(Main1, INPUT);
  pinMode(Main2, INPUT);
  pinMode(Store1, INPUT);
  pinMode(Store2, INPUT);

  digitalWrite(Main1, LOW);
  digitalWrite(Main2, LOW);
  digitalWrite(Store1, LOW);
  digitalWrite(Store2, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
void sensor1()
{
  if (digitalRead(Main1) == HIGH && digitalRead(Main2) == LOW && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }
  if (digitalRead(Main2) == HIGH && digitalRead(Main1) == LOW && j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91---------------");//first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91--------------"); second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
}
void sensor2()
{
  if (digitalRead(Store1) == HIGH && digitalRead(Store2) == LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is closed");
    Serial.write(0x1A);
    delay(10000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(Store2) == HIGH && digitalRead(Store1) == LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

thanks

bhupendra.sinkar727@gmail.com


nRF24l01+ Outputting Garbage Values I just purchased a set of 10 nRF24l01+ modules with a breakout board that looks like this:

Note: This is the nRF24l01+ chip, not a clone Si24Ri. Also, I'm using an Arduino Mega.

I'm following the Sparkfun tutorial here:
https://learn.sparkfun.com/tutorials/nrf24l01-transceiver-hookup-guide

The wires are hooked up like so:

3.3V → VCC
GND → GND
PWM 8 → IRQ
PWM 9 → CE
PWM 10 → CSN
PWM 11 → MOSI
PWM 12 → MISO
PWM 13 → SCK

I've verified the two modules are hooked up as they should be. I'm using the GettingStarted example program for both units. Whenever I go into the serial monitor when connected to the transmitter, I get garbage values like <¯�SžRÖ being output. Whenever I try to transmit a message by entering t, nothing gets returned. The same problem is happening on the receiver end.

As for troubleshooting:

I've wiggled all of the jumper cables to verify a stable connection.
I've swapped out the modules I was using with others from the package (twice) so the modules probably aren't bad.
After reading that a capacitor is sometimes needed to provide a smoother voltage to the module, I upped the voltage from the 3.3V the Arduino was providing to a stable 3.5V from an external variable power supply to account for any small voltage dips. I don't have any capacitors available to me at the moment, so I figured this would be the next best option.

Unfortunately, my RF modules are still not correctly transmitting any data, and I don't know where to go from here.

Check these things first:

Is your power supply give a constant 3.3V and a minimum of 0.5A(500mA)?
Does your code work for others?
Are you on the right serial baud rate?
Is the path from the radio to the Arduino as short as possible?
Are your MISO and MOSI wires twined into each other?

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.


Problem with arduino starter kit project 7 Can someone pls help me only the two buttons clossest to the big green wire work and i don^t know why i have already tried swapping buttons

EDIT 1:
my code

and i know the first two are working because they generate a tone with the piezo
the third one does nothing and the last one only makes static noises

I see the problem. The connections to the first 2 buttons are correct. You're missing a yellow wire linking the output of the bottom 2 buttons to AO however, so the 3rd and 4th buttons are not connected to your A0 pin at all. Add a yellow wire between row 24 and row 20 on your breadboard.
EDIT:
I see now that there is a green wire connecting rows 24 and 20 together. However, that is the likely place where things go wrong. I would suggest taking a couple of jumpers and connecting them to a multimeter set to continuity mode. Put one in row 28, and then test continuity to row 24, row 20, and row 16.
One of your wires may not be seated into the breadboard properly, or you may even have a bad row on your breadboard. I've seen that before.
EDIT #2:
A multimeter is your friend. If you don't have one, you should get one, and learn how to use it. It's invaluable for troubleshooting circuits. (Get one that has a continuity mode that beeps when it detects continuity, and that has auto-ranging voltage and resistance measurements.)


Maxbotixs LV-EZ4 analog read question I am using an external 5 volt power supply to power my Sonar, and I am using a Teensy 3.1
to read in analog signal  from the sonar. my question is since the teensy is only 3.3v tolerant with analog in, is it safe to use with the maxbotix sonar?

Converted Gerben's comment to an answer

That is not safe. Maximum voltage on the analog pins is 3.3v, according to the datasheet. But why don't you power it from 3.3v? Minimal voltage for that unit is 2.5v. And it uses only 2mA.


How to: soil moisture measurement with WaterMark? I am new with Arduino, and i cant find documentation about how to connect Arduino with Watermark successfully.

I would like to connect my Arduino UNO with a watermark like this:

http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable_3234944.jpg

Does anyone know any schema or documentation about how to do it? Have anyone tried it before?

I have found this: https://oceancontrols.com.au/datasheet/davis/ECS-014_07395-158_IM_06440_6470.pdf

but still not clear how to do it in Arduino.

Thanks you for your time.

You can google
"Arduino-based system for soil moisture measurement"
and the author about this paper is "Vuk Radman" .

Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.


Additional Digital Input Pins I require additional digital input pins for 5 PIR sensors. Can I use the shift register (74HC165) to read these input? And will I be able obtain real time values from all the 5 sensors?

You could use a GPIO expander (MCP23017 or similar) which could give you 14 extra pins (16-2 for I2C bus), but this is putting extra load on the microprocessor.  (you haven't said which one by the way).

Or another option might be to revisit you design and see if you can split it out to multiple processors.  This is effectively the same as a GPIO Expander, just using an Uno or ESP8266 as the expander.


Algorithms to reduce measurement error from analogue sensors When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).

My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...

My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected.
Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.

Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?

Many thanks in anticipation

// Take mean of multiple sensor readings excluding outliers:

# define SAMPLES 100 // number of samples to take mean of
# define TOLERANCE 0.1 // % range of allowable deviation
                       //between current mean and new values, expressed as decimal

n = 1; // loop variable
total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
mean = total; // mean of all current data

while (n < SAMPLES) {
    new = analogRead(analogPin);
    if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
        total += new; // if new reading is within range, calculate new mean
        n += 1;
        mean = total / n;
        }
    // (else ignore new reading)
}
Serial.print mean;

I use something very similar to what you are proposing to measure RSSI in an antenna pattern generator.  Say you have an array of 16 samples.  You start filling the array with samples but don't actually output a result until the array is full.  This will give you a startup period of 16 samples where no decisions are made.

After the array is loaded, set a semaphore that indicates that results may now be used to make decisions.  New samples overwrite the oldest sample in a recirculating buffer.  You will now get decision outputs at the same rate as the sample rate with a lag, i.e. when the inputs go to zero abruptly, it will take 16 sample periods for the output to catch up.  I call this a 16 sample rolling average.

For relatively stable inputs, simply take the mean of the array and output that result.

For inputs that are glitchy such as RSSI take the mean of the array and then find the sample(s) that is (are) the farthest away from that mean.  You then recalculate the mean without that sample included.  Note:  Do not discard that sample, simply ignore it for that cycle.  I call this a 15/1 outlyer average.  For my RSSI measurements, this gives me the equivalent of a 48 sample rolling average.  You can do an 8/1, 16/2 system etc requiring 9 and 18 samples per sample respectively, tuning the counts to your particular application.  I am able to get nearly anaechoic chamber results in the middle of a radio noisy office.

Again, note that the outlyers are NEVER discarded as they may represent a real trend.


What connects to Arduino Solar Shield? I see there is an Arduino EnergyShield available, and am wondering what (specific) solar shield/panels/attachments can be used to power it. Thoughts?

Bonus points if someone can explain how long the solar unit would take to charge the Energy Shield if the Arduino was on but idling (low-to-nonexistent power output).

First, panels that you can use...

There are a few at Adafruit (here, here or here)

You just want to check that the barrel jack and plug are the same size.  I couldn't find dimensions in the documentation for the energy shield so you may need to dig a little deeper or just swap it for one that you know will work.

Also, the question about how long it will take also depends.  First, if we assume that the arduino is not running we can get ~500mA from the second solar panel listed.  If we can get all of that into the battery, it would take (1200mAH/500mA) about 2.4 hours to fully charge the battery.  It looks like you have to make some adjustments on the shield to get the most out of your solar panel.  And of course, you'll want to adjust those calculations based on the panel that you end up getting.

Now, if we assume the Arduino is running and consuming about 25mA you will have to subtract that 25mA from the 500mA that the solar panel is providing.  So, in general...

**

  (Battery Capacity)/(Solar Panel Current - Arduino Current) = Charge
  Time.

**

And you have a lot of control over the solar panel current and the arduino current based on the exact arduino that you use, etc, etc.

There is also probably some loss regulating the solar panel voltage from 5-6V down to charge the battery (which is probably at 3.7V). I also don't know if the charging circuitry will limit the amount of current going to the battery.

Take Away: There's a lot of stuff to consider when trying to answer this question.  I think your best bet would be to get a panel that fits and dump the fuel gauge values out to the console every few minutes.


Reading several rotary encoders Have an upcoming project where user input will be based on spinning a large cog and I have several UNOs available

Since rotary encoders need two pins, only a Mega would be able to handle the 7-8 encoders needed. Unless theres a better method of reading them?

Is it worth using an ATTiny85 per encoder and passing all this data to a mega via 1 pin each? This way, I could extend the project beyond 7-8 later?

Or is this idea out the window, because there's a much simpler way?

Library and schematics are at https://github.com/maxgerhardt/rotary-encoder-over-mcp23017.

To read a rotary encoder (i.e., detect state changes of the knob), there are two possible implementations:

poll the state of the two output pins and check for changes
set up an interrupt which will be called when an output pin changes, then check for changes

Using interrupts is more efficient than always polling the pins, because an action is only executed when an actual change occurs.

Per rotary encoder you would need two pins on your microcontroller. However, we can use GPIO expanders over e.g. I2C or SPI, such as

Microchip MCP23017 (16-bit, I2C)
Texas Instruments PCF8575 (16-bit, I2C), PCF8574 (8-bit, I2C)

Using a port expander over I2C has the advantage being a bus that only uses 2 pins. This means that there can be multiple (up to 127) devices on the I2C bus, and each I2C device can then e.g. provide 16 GPIO pins.

Using an ATTiny85 per encoder and possibly joining them via an I2C bus is also possible, however more expensive and more work.

I've chosen a MCP23017 here because it is interrupt-capable, has 16-bit and I had it lying around. A PCF8574 would have also worked just fine, since it has the same capabilites.

Tests were made using an MCP23017 and a KY-040.

The written library uses a modified Adafruit MCP23017 library and the Rotary library. The Rotary library also handles debouncing by using a state-machine based approach for decoding. The library is a simple header file which defines a RotaryEncOverMCP C++ object, with which a rotary encoder connected to an MCP23017 device can be easily described and managed. It has an example for the polling method and the interrupt method.

For 1 encoder, one can write down schematic like: (interrupt based)

Since one MCP23017 has 16 ports, we can connect up to 8 rotary encoders to one such device.

However the MCP23017 also has three address pins with which its I2C address can be selected. This means we can have 2^3 = 8 such device on the same I2C bus (i.e., connected to the same SDA and SCL lines).

Thus, with one I2C bus, which uses 2 pins, we can have a maximum of 8xMCP23017 and 64 rotary encoders (assuming no interrupts are used, which would need 1 pin for any number of rotary encoders). At the cost of 2 more pins on the microcontroller, we can create another software bit-banged I2C bus, each of which adds again a maximum of 64 rotary encoders.

Assuming D2 to D13 and A0 to A5 are free, on these 18 pins we can have 9 I2C buses with a total of 72 MCP23017 devices hosting a grand total of 576 rotary encoders. Whatever one might need that for.

I've tested this library with one rotary encoder and a MCP23017, but the code is structured in a way that adding more encoders is just adding an entry in an array.


How to dynamically allocate arrays Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(" " + answer);
  Serial.print(" " + test[0]);
  Serial.println(" " + test[1]);
  Serial.println("test");
  delay(100000000000);
}

All of my attempts result in either some garbage in the serial or in most cases:

test

test

Does anyone know what I'm doing wrong?

This works:

int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(answer);
  Serial.print(test[0]);
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);
}

In C/C++, you can't add/concatenate Strings and int.


It seems my Arduino doesn't work I've got an Arduino Uno.

I was building a simple circuit with only one switch and it doesn't seem to work (I followed the Arduino project book from the Arduino starter kit).

This is my circuit :

Then I try again to move the switch and then it works (but I don't understand why).

So I tried to understand where the error is and I try to read digital input from the simple circuit with only one LED :

And this is my code :

int SWITCH = 13;

void setup() {
    Serial.begin(9600);
    pinMode(SWITCH, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
    int val;
    val = digitalRead(SWITCH);
    if(val == HIGH) {
        Serial.println("OKAY");
    }
}

I expect to see on the Serial Monitor "OKAY OKAY" and so on... but nothing appears on the Serial monitor.

Then I try to change the condition :

if(val == LOW)

And now I see "OKAY OKAY" and so on...

I think that there is something wrong with this Arduino... Can someone tell me something about what is happening? Am I stupid or there is really something wrong with this?

It looks to me like your arduino is working just fine.

In the first two images you use the arduino only to provide 5v power to the circuit on the breadboard. In the first image you haven't connected your button to properly function as a button. I don't know the exact pin layout of the button (which should be explained in a datasheet of that button), but it is also good to know exactly how to holes in a breadboard are connected. This picture shows why your button works on your second image but not your first:

This picture also shows how the breadboard holes are connected:

In your third image you have practically connected input pin 13 to GND, so it makes sense that digitalRead(13) in your code always returns LOW. Thus, the variable var is always LOW (or 0). Thus, the comparison (var == HIGH) is FALSE, which won't send "OKAY" to the serial monitor. And, the comparison (var == LOW) is TRUE, which will* send "OKAY" to the serial monitor.

I hope you can follow the logical steps and it is clear to you what is happening.


What is the best way to unit test my code without controller? I want to unit test my Arduino code. Ideally, I want to execute and test my code without uploading it to the board. What tools or libraries can help me with this?

There is an Arduino emulator in development which could be useful, but it doesn't yet seem to be ready for use.

You can easily simulate your Arduino code using the famous Proteus ISIS.
You just will have to search for the specific Arduino simulation library for Proteus.

Here you a small tutorial of how to make this thing done:

First, identify the path the Arduino IDE generates the hex file to?
for example if you are using the official IDE you will find the hex file location in the "arduino IDE path/lib/preferences.txt"
Or if you are using Arduino ERW which I recommended the most on windows! So you can simply open the output folder by "Sketch > Copy HEX file as path".

Second, download the Arduino library from Here. Then copy ARDUINO.LIB and ARDUINO.IDX to folder "library" in the install directory Proteus.

Third, open ISIS and you should be able to find the component.

Please find this image of the worksheet after finishing the above steps, and simulation works just fine!

And as a head start for you, please find this small memo I prepared for the Arduino Uno Pins Layout:

0-14: I/O
A0-A5: Analog

We can use analog as digital:
=============================
Pinout:
00: Rx      | Can't be used as I/O if I wrote in the code Serial.begin
01: TX      |
02: Interrupt
03: Interrupt & PWM
04:
05: PWM
06: PWM
07:
08:
09: PWM
10: PWM & SPI
11: PWM & SPI
12: SPI
13: SPI
A0:
A1:
A2:
A3:
A4: TWI
A5: TWI


Arduino analog joystick I'm planning to make a handbrake for my racing simulator (Assetto Corsa) and I wanted to know how can I transform arduino into a joystick so the game can read the analog input?

Thanks in advance, and sorry for my bad english.

I made this video and github just for this about a year ago.

And here is the code:

/*
2-axis joystick connected to an Arduino Micro
to output 4 pins, up, down, left & right

If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
This skectch is using pull up resistors.

*/

int UD = 0;
int LR = 0;
/* Arduino Micro output pins*/
int DWN = 13;
int UP = 12;
int LEFT = 11;
int RT = 10;
/* Arduino Micro Input Pins */
int IUP=A0;
int ILR=A1;

int MID = 10; // 10 mid point delta arduino, use 4 for attiny
int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, HIGH);
  digitalWrite(UP, HIGH);
  digitalWrite(LEFT, HIGH);
  digitalWrite(RT, HIGH);

  //calabrate center
  LRMID = analogRead(ILR);
  UPMID = analogRead(IUP);
}

void loop(){

  UD = analogRead(IUP);
  LR = analogRead(ILR);
  // UP-DOWN
  if(UD < UPMID - MID){
   digitalWrite(DWN, LOW);
  }else{
   digitalWrite(DWN, HIGH);
  }

  if(UD > UPMID + MID){
   digitalWrite(UP, LOW);
  }else{
   digitalWrite(UP, HIGH);
  }
  // LEFT-RIGHT
  if(LR < LRMID - MID){
   digitalWrite(LEFT, LOW);
  }else{
   digitalWrite(LEFT, HIGH);
  }

  if(LR > LRMID + MID){
   digitalWrite(RT, LOW);
  }else{
   digitalWrite(RT, HIGH);
  }

  delay(400);

}