SRF04 Ultrasonic sensor - inaccurate readings I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/

I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.

I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).

Has anyone experienced something similar?

Just don't use that library, it seems poorly designed.

Here is how the distance for roundtrip is calculated (code excerpts):

long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

If we remove the averaging stuff (as _average is 1 by default), this boils down to:

digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

pulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.

If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return:

3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.

Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor; in this situation, pulseIn() will return 36000us.

The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs.

Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:

int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

The problem here is the int calculation, it should rather be performed as float. For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance!

If you want to go on using this library, then just forget about the getDistanceCentimeter()method and replace it with the following code:

distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as float and converted to int distance only at the end.

Your code should also explicitly detect negative values as meaning "no object detected".

Have you got a satisfying answer to this question?

I'm having a same issue with my HC-SR04 sensor.
It's supposed to be mm-accurate, instead I'm getting ~30%+ off values.
E.g.) @ 30cm, the readout is ~40cm.
      @ 15cm, the readout is ~20cm.

This isn't exactly a "solution" but here's what I did.
For calculating distance, I divided by additional 1.25.

    distance = (duration/2.0)/29.4/1.25

Now my readings look a lot more accurate(+/-0.5cm) within ranges of 0~30cm. And although it wasn't perfect, at 2m it read 202cm.

Not sure if this is sensor issue or Arduino issue... Maybe it's lacking power such that a portion of echo pulse is not being registered at Ardu as High. I'm running my board on USB 5V, which is in turn taken off raspberry Pi2.
Still, 25% is a huge discrepancy...

WOWOWOW OK I FOUND SOMETHING!

After writing that last paragraph, I connected Arduino to my PC (instead of RPi), uploaded the s/w without 1.25 factor, and the readings are correct! (more or less. NOT like +30% before)

So yeah, it's because of lack of power.

Hope this is the case with you as well, in which case we can finally put this issue down for good.


Android  HC-05  Arduino communication issue My project involves Android (Samsung Galaxy 2) to Arduino (Uno) communication via HC-05.

HC-05 is connected to Arduino on pins 10,11 using SoftwareSerial lib.

I got this setup running for a while and was satisfied by the outcome - my bi-directional communication worked fine.

Issue:

I made a change to the communication protocol and now messages sent from Android to Arduino get corrupted. It happens under particular circumstances - when Arduino writes (streams) packets of data to Android and, at the same time, monitors the input from Android for a particular message which signals the end of communication. This message, when read from SoftwareSerial buffer, gets corrupted. This corruption is not consistent - it corrupts the packet in (seemingly) random way.

I've already run many tests and am pretty sure that this message is not corrupted on the Android side.

Questions:

Is there anything about HC-05 or SoftwareSerial lib which prevents
simultaneous bi-directional communication?
Can it be that input/output buffers interfere in some way?
How can I achieve reliable communication using the aforementioned HW and comm scheme?

P.S. I got pretty much code and am not sure what parts of it might be relevant to this issue. Will provide relevant parts per your request.

Thx

As mentioned by @alex.forencich, SoftwareSerial is not designed to support simultaneous bi-directional communication.

I found a link to AltSoftSerial library on Arduino site, and this lib seems to work properly in my setup.

To convert from SoftwareSerial to AltSoftSerial you need to change the pins that HC-05 is connected to (on Arduino Uno these are pins 8,9), and to make this minor change in the code:

//#include <SoftwareSerial.h>
//SoftwareSerial swSerial(10, 11);

#include <AltSoftSerial.h>
AltSoftSerial swSerial;

Hey thought I'd pitch in.
I was having quite a few issues in trying to control an led using hc 05 from an android phone.
I was using SoftwareSerial. It didn't work.
The board is an arduino mega 2560.
Finally, I got it. SoftwareSerial turns digital pins to tx and rx com pins.
Make sure to use digital pins on the board to communicate when your using SoftwareSerial.
Hope it helps...


What could cause AdC Reading only to get stucked? I am doing a Solar water heating contrôler with arduino.
I have had a freeze of the AdC value read (ntc probe that read Solar panels) that remained at -1.75degc. this was confirmed by the serial data sent an recorded (using raspberry and Time series database) but also the direct Reading on the LCD (16x2). After rebooting Arduino everything get back normally.
Additionnel strange thing is that the water tank ds18b20 temperature sensor serial data value showed a huge spike 1e4... That lasts less than 1 second (which Can not happen as the sensor max value is 125 deg c from this numerical sensor.). After that spike, the adc recorded value remained Frozen. The other ds28b20 and LCD menu navigation and display were ok...
Could that be related to EMI?
To SRAM overflow? Even if the rest of the program seems to work?
What could enables me to discriminates between those issues?
It seems it happened arround 2 days after the Arduino was rebooted.
Description of set up:
I am using a standalone atmega 328 with polulu programmer. 8mhz internal crystal. Everything places on veroboard (main). Then a child veroboard holds the various resistors (Pullup, pulldown) for the input signals. Another child veroboard holds the outputs (pwm pump speed driver), optocoupler for pump Relay.
The supply is a meanwell din rail 5v ac-dc concerter.
I places decoupling caps arround atmega 328, diode+ pull up resistor + cap on reset Line as i had resets regularly (they are gone now).
The pump Relay is on a separate 24v supply. Grounds are separrated from Arduino with this 24v circuit (that incluses flyback diode). But grounds are common to main and 2 children veroboards. The ntc Solar panel probe wire is twisted rj45 cat6. It is shielded and shielding is connected to the atmega grounds.
My program is non blocking type with use of millis and state machines. During developpent I checked the Time operation of the program that was running fast (no delay).
The main structure is quite straightsforward. See bellow commented:
//Get Button state and debounce
buttonLeft.launchSM();
buttonRight.launchSM();
buttonDown.launchSM();
buttonUp.launchSM();

//Menu(uses menubackend library)
menuNavigationBehavior(); // ie detect action from button pressed.Should be executed very rapidely... (less than 10 ms).
EditingVarInMenu(); // changing variables in Menu requiring speed loop (set parameters for example)

//Getting Temperature from panel1, 5 for 5 averaged values
//every 20 ms ie 20 * 5 we have a temperatuure every 100 ms.
TemperaturePanel1(5,20,Tpanel1);

//Getting Temperature from one wire. Time between fetch and return of 100 ms.
getOneWireTemp ();

//CONTROLLER---------------------------------------------------------------
//System Control Logic updated at Time loop
// Controller logic state machine execution
switch (ControllerMainState)
    {
        case CONTROL_MANUAL:
          ManualStateActions();
          break;

        case CONTROL_AUTO:
          AutoStateActions();
          break;

        case CONTROL_ERROR:
          ErrorStateActions();
          break;
    }

    //MENU DISPLAY_____________________________

    if( millis() - timer_50_ms > 200) //
         {
              timer_50_ms = timer_50_ms+200;
              displayMenu(); // change the display. Can be done less often ie every 200 ms
          }

You appear to have a difficult problem.  One of the rules I use is never power the arduino with 5V power, always use the barrel connector and go with about 8 volts. The additional filtering etc the on board power supply does is amazing. The external 5V is ok for most of the other devices. Another option would go to the local electrical store and purchase a metal junction box and mount the electronics in that complete with a metal cover. Be sure it is grounded to earth. The reason for this is your prototype assembly has a lot of antennas that will pick up just about all of the electrical noise in the area. Remember all grounds must be connected. Arduinos are not hardened for industrial or commercial controller applications.


Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini? I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.

How do I do this?  The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?

To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+.  The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.

The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.

You might want to look into using a 3.3V Pro Mini with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.

you can download the references from this link: https://s3-ap-northeast-1.amazonaws.com/sain-amzn/20/20-019-102/NRF24L01.rar
Hope the information may be helpful. Cheers!


How to create TCP server on Arduino UNO WiFi? I'm currently trying to make my Arduino UNO WiFi work as a TCP host, so I can send him a TCP message and it sends a response.

I had no problem doing this on the Arduino Galileo Gen 2 using the EthernetServer, but since this one is using WiFi, EthernetServer isn't an option.

I can, however, run a web server, but that's not what I want.

So how do I make the Arduino receive, handle and respond to sent TCP/IP messages?

For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".

Hope this can help you.

Ethernet and wifi are basically the same thing but only joinig Ethernet is codewise different than joining a wifi address and thus these two need 100% different code because wifi and Ethernet are a different thing.

See, compare codes in below links, and you see the difference is on making up the level 1 connection, and tcp and ip on 2 and 3 do not change.

https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinoethernet/arduinoethernet/arduinoethernet.ino

https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinowifi/arduinowifi/arduinowifi.ino


How to connect more than one arduino serial port together The idea is to connect more than 1 arduino slave to master as shown in schamatic

simulate this circuit – Schematic created using CircuitLab
The problem is TX slave can not just combine to master RX.
It need to done some trick like tri-state buffer to make slave TX one at time.
Anyway, avr port can config as tristate buffer.
(Q1)Is there any software solution to done this?
Second If I connnect TX to RX for half-duplex communication (using 1 data line). How to make Rx stop listenning to its self while transmiting data?

You can do it with two diodes and a resistor:

simulate this circuit – Schematic created using CircuitLab
You'll still have to implement some system to prevent collisions, but electrically that will be sound.

Update Nov. 2020: my answer below, though a bit insightful and with many correct statements, is wrong. My schematic below will indeed prevent the Arduinos from damaging each other, but it will not allow proper communication. Majenko's answer here is right. Use his schematic, but read my answer below as well for additional insight and ideas.

ORIGINAL ANSWER:
You can do it with 2 resistors, as shown below. That's it! Super simple!
Electrical explanation:
The goal is simply to protect the two Tx pins from killing each other. Without the resistors one Slave might be writing output LOW while the other Slave is writing output HIGH, which is a dead short--damaging both devices. Simply putting a 1k resistor in series with each Tx pin like this prevents that dead short. Now, if one Tx pin is HIGH while the other is LOW, you get current flow from one into the other through a total of 2kOhms, which means the current will be only I = V/R = 5V/2000 Ohms = 2.5mA, which isn't a problem, as each pin can handle 40mA max and 20mA~30mA continuous safely. Also, a 1k resistor isn't much load, so you should still get good serial throughput even at fairly high baudrates.

simulate this circuit – Schematic created using CircuitLab
The code:
The communication code will be done as normal with Serial.print() or Serial.write(), Serial.read(), etc. Nothing special about the code, except you should make an effort to keep the slaves from talking at the same time to prevent data corruption from slave to master. So, you should have Master request data from a Slave, and a Slave should only talk when it knows the other Slave is not talking (ex: it should only talk when spoken to). The Master coordinates the communication. In this way, this is like SPI: the Master is in charge and tells each Slave when to talk. Since both Slaves are always listening, just use an "ID" to indicate which slave is being spoken to. If a Slave doesn't see it's ID, it should ignore the message.
Ex:
Request a new temperature reading from Slave 1:
Serial.println("1:T");

Now, wait until you get the full response from Slave 1, then send out a request for...let's say, some current reading, from Slave 2:
Serial.println("2:C");

The exact communication codes are up to you--your imagination is the limit.
Again, both slaves see both messages, but they look at the number at the beginning and only reply if it's their number. Doing this technique, you could connect nearly infinite Slaves all on the same line, just adding a 1k resistor to each Slave's Tx line before the junction where they all connect back to the Master's Rx line.
Pretty cool. I never thought of doing this before until you asked the question. Good question.


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)

If you are calling the tone function, my Uno seems to automatically default to output configuration on the digital pin 8.  You don't have to declare digitalWrite().  I don't understand this, and can't find it in the documentation.


Transfer 10-bit via Arduino-to-Arduino SPI protocol The task I need to accomplish is as follows:

I have an analog/digital converter that sends out a 10-bit signal. This signal needs to be transferred to an Arduino Uno using the SPI protocol. Because the SPI protocol works with a 16 bit pattern I need to expand the incoming signal. The slave Arduino then needs to put out the transferred number in decimal.

I imitated the ADC with another Arduino Uno, setting it as master, but unfortunately at the time I only had one Arduino so I couldn't test my code. Furthermore, I don't really have a clue how to "expand" a 10-bit signal to a 16-bit one. Can someone please explain it to me and have a look at my code?

Code for the master Arduino:

#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, OUTPUT);
  pinMode(MOSI, OUTPUT);
  SPI.beginTransaction(SPISettings(62500, LSBFIRST, SPI_MODE0));
}

void loop() {
  byte x=0000001101;
  byte y=0011111111;
  digitalWrite(SS,LOW);
  SPI.transfer(x,y);
  digitalWrite(SS,HIGH);
  delay(1000);
}

Code for the slave Arduino:

#include <SPI.h>
#define SS 10
#define MOSI 11

void setup() {
  pinMode(SS, INPUT);
  pinMode(MOSI, INPUT);
}

void loop() {
  byte x=SPDR;
  byte y=SPDR;
  printf(x,DEC);
  printf(y,DEC);
  delay(1000);
}

A byte is only 8 bits, so your code:

  byte x=0000001101;
  byte y=0011111111;

won't do what you think it does.

A 10 bit value will be stored as an int (which is 16 bits) or 2 bytes.

Assuming it is an int then this will convert it to two bytes.

 const int adcData = 0x03FF;  // From ADC
 byte dataToSend[2] = {0, 0}; // Initialise it to zeros
 dataToSend[0] = (adcData & 0xFF00) >> 8;  // didn't really need the bit mask just to make it clearer.
 dataToSend[1] = (adcData & 0x00FF);
 // Now send dataToSend via the SPI bus.

To reassemble the data on the otherside:

 byte dataReadFromSPI[2];  // Filled with the data read from the SPI
 int adcData = 0;
 adcData = (dataReadFromSPI[0] << 8) | (dataReadFromSPI[1]);


delayMicroseconds not working on STM32F103C8T6 Due to the fake STM32F103C8T6 module in the market, the delayMicroseconds function is working qucker than expected, when I expect a delay of 1000 us , I get a delay of 500 us. Is there a better method, like to create separate module for counting in microseconds using micros timer? Or there are other proper bootloaders than this one . I use Arduino IDE for programming STM32F103C8T6

Have you considered using a RTC? Something like a DS1307 breakout with I2C communications will provide you with accurate timing.
https://www.bobmixon.com/2020/03/real-time-clock-and-arduino/


How to connect an ESP8266 using an ESP-01 adapter to an Arduino Uno? I am pretty new to Arduino programming and wanted to learn how to connect an ESP8266 generic WiFi module to an Arduino Uno using the ESP-01 Adapter shown in the image below.
I tried doing it on my own while connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively but was getting the following error while trying to upload the sketch:

warning espcomm_sync failed
error espcomm_open failed
error espcomm_upload_mem failed

To the best of my knowledge there is no tutorial on the internet that explains about the above mentioned adapter and its interfacing with the wifi module in detail. It would be a great help if someone could please guide me through the process so as to convert my Arduino into a server.

Recommended tutorial

you can't flash an esp-01 module with this adapter, unless you find a way to connect io 0 to ground in this setup

I have this type of adapter with esp8266 glued. I can't recommend this type of adapter boards. Easier is to use a development board like Wemos or NodeMCU with on-board USB adapter. And they are cheap.

The adapter has the esp-01 2x6 header J2 but the io 0 and io 2 pins were not connected on my version. I patched io 0 to JP2 header to be able to flash the module. On the picture you see a paperclip jumper connecting GPIO0 to ground.

...connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V,
  GND, Tx and Rx of the Arduino Uno respectively...

At least one issue is the serial connections. Rx and Tx need to be cross-connected with whichever Arduino pins you are connecting to the ESP. Using the Arduino's built-in UART, Arduino pin #s 0 and 1, cannot work for uploading (to either board) since those pins are used to communicate with your PC.

If you are trying to upload to the Arduino, try removing the ESP adapter board during the upload. Even with that, communicating at run-time from the Arduino to the ESP (with it plugged back in, of course) may run into interference from the Arduino's 16U2 chip (serial <-> USB processor) which is hard-wired to those pins. And if it does work at run-time, you will have to forego serial communication to/from your PC, which uses those same pins.

The alternative is to use the SoftwareSerial library in your code, which will let you select two other Arduino pins as a second "software UART" to communicate to/from the ESP. This route come with it's own initial-setup complexities - you'll first have to change your ESP's default baud rate to 9600, about the maximum that SoftwareSerial can reliably receive. See my post about how to do this. To implement it, you'll need a short sketch that continuously tests Arduino's terminal for an available character and sends any to the ESP, and likewise tests the SoftwareSerial and sends to the Arduino's terminal.


STM32 and NRF send & receive This is my send and receive code in STM32 (blue board).
But i can't send and receive data . why?
I did use Enrf24.h .
Enrf24 link: https://github.com/spirilis/Enrf24
send code is:

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}

void loop() {
  Serial.print("Sending packet: ");
  radio.print("OONN");
  radio.flush();  // Force transmit (don't wait for any more data)
  delay(1000);
  Serial.print("Sending packet: ");
  radio.print("OOFF");
  radio.flush();
  delay(1000);
}

receive code is:

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
}

void loop() {
  char inbuf[33];
  while (!radio.available(true));
  if (radio.read(inbuf)) {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

this image can help :

You did not say which library you are using, but based on the #includes, I am assuming http://maniacbug.github.io/RF24

This line in your receiver code:

  while (!radio.available(true));

does not make sense. You are passing true to the radio.available() function, but the function does not care about a parameter.

You probably mean something like:

while (!radio.available());

When you pass in a variable, you are calling a variant of the function that expects a pipe number to be given, and true is defined as 1. Your transmitter, however, is not sending on pipe number 1.

It is better answer for some reseans
in Enrf library you can not send data with write untill txbuf_len==0

  size_t Enrf24::write(uint8_t c) {
  if (txbuf_len == 32) {
  flush();  // Blocking OTA TX   }
  txbuf[txbuf_len] = c;   txbuf_len++;
  return 1; }

dont use purge then

  txbuf_len = 0

this is for read dat

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
 // radio.autoAck(false);
}

void loop() {
  char inbuf[35];
  if (radio.read(inbuf))
  {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

this is write for write data:

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}
int i=0;
void loop() {
  i++;
  Serial.print("Sending packet: ");
  Serial.println(i);
  radio.print("1234567890123456789012--------->");
  //radio.purge();
  delay(100);
}


Arduino IDE Permision Denied For Upload, Ubuntu I am having issues uploading to my Arduino from the IDE on Ubuntu 18.04. The error message I have received is:

  Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Uno"
  avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

I have checked other questions similiar to this one and have tried adding myself to the dialout group running:

sudo usermod -a -G dialout username

and added permission to write:

sudo chmod a+rw /dev/ttyUSB0

After, when I run:

ls -l /dev/ttyUSB0

I get:

crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

However,I still get the same error message from the IDE.

Any help would be greatly appreciated!

As mentioned on the official guide for Linux, you need to run

sudo usermod -a -G dialout <username>

with the <username> replaced with the username of your system.
After running this, log out and log in and you should be good to go.

The only way I could install the IDE and pass the programs without giving permission error, in an Ubuntu 18.4, using make.

See this answer  to How to install latest Arduino IDE?.


Sending arduino signal to another arduino I'm working on a project which consists of 2 different function. since the arduino only can do 1 function so i decide to use 2 arduino instead. my idea is 1st arduino will give a output and the sketch on the 2nd arduino will run Only after the input given from the 1st arduino. So can i make a digital output which will be send to the input of 2nd arduino?

if it could be, i already make a code for the 2nd arduino which will be run after there was an input from the 1t arduino:

//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3
//setup runs once
void setup()
{

  pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
  pinMode(output1starduino, INPUT_PULLUP);

  //setup output pins for relays/pumping station and LED board
  pinMode(PUMP_1_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

}

//loop() runs indefinitely
void loop()
{

  if(digitalRead(output1starduino) == HIGH) // output from 1st arduino
  if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
  {
     digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
     digitalWrite(LED_PIN, HIGH);    //turn on the LED
  }

  {
     digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
     digitalWrite(LED_PIN, LOW);    //turn off the LED
  }
}

as i write on the line, the "output1starduino" which an digital output from the first arduino. Is this the right way for me to write if i want the program here to run only right after the output from 1st arduino given?

*** this is the code of first arduino which will be sent to the 2nd arduino

int motorPin = 3; // motor pengisian (m1)
int blinkPin = 4; //
int motor1 = 5;// motor pembuangan
int motorklorin = 6;// pam topap
int switch1 = 2;// switch float
int indicator1 = 7;
int indicator2 = 8;
int indicator3 = 9;
int output1starduino = 2;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
  pinMode(motor1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
  pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
  pinMode(indicator2, OUTPUT);// lampu penunjuk topap
  pinMode(indicator3, OUTPUT);// lampu menunggu
  pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2
}

void loop()

{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(motor1, HIGH);// on lampu
  digitalWrite(motorklorin,HIGH);
  delay(1000);        //

  digitalWrite(motorPin, HIGH);  //
  digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
  digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
  digitalWrite(motorklorin,HIGH);
  delay(180000);        //tempoh pembuangan

  digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
  digitalWrite(blinkPin, LOW); //
  digitalWrite(motor1, HIGH);// filling motor on
  digitalWrite(indicator1, HIGH); //indicator
  delay(150000);        // duration filling

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(motor1, HIGH);//
  digitalWrite(output1starduino, HIGH);
  delay(100000);        // multiply by 60000 to translate minutes to milliseconds
  }

An arduino may not be as fast as a PC or phone, but it is VERY fast indeed (16,000,000 operations /sec). Unless the code for arduino #1 is incredibly complex, the one arduino should be able to do it all on its own.
P.S. Please post the code for Arduino #1

Combine them like this - I moved the duplicate pins to other pins

//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3

byte motorPin = 11; // motor pengisian (m1)
byte blinkPin = 12; //
byte motor1 = 5;// motor pembuangan
byte motorklorin = 6;// pam topap
byte switch1 = 2;// switch float
byte indicator1 = 13;
byte indicator2 = 8;
byte indicator3 = 9;
byte output1starduino = 10;

//setup runs once
void setup()
{

pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
pinMode(output1starduino, INPUT_PULLUP);

//setup output pins for relays/pumping station and LED board
pinMode(PUMP_1_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);

pinMode(motorPin, OUTPUT);
pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
pinMode(motor1, OUTPUT);
pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
pinMode(switch1, INPUT_PULLUP);// PELAMPONG
pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
pinMode(indicator2, OUTPUT);// lampu penunjuk topap
pinMode(indicator3, OUTPUT);// lampu menunggu
pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2

}

//loop() runs indefinitely
void loop()
{

if(digitalRead(output1starduino) == HIGH) // output from 1st Arduino
{
digitalWrite(motorPin, HIGH); // turn on the motor
digitalWrite(blinkPin, HIGH); // turn on the LED
digitalWrite(motor1, HIGH);// on lampu
digitalWrite(motorklorin,HIGH);
delay(1000);        //

digitalWrite(motorPin, HIGH);  //
digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
digitalWrite(motorklorin,HIGH);
delay(180000);        //tempoh pembuangan

digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
digitalWrite(blinkPin, LOW); //
digitalWrite(motor1, HIGH);// filling motor on
digitalWrite(indicator1, HIGH); //indicator
delay(150000);        // duration filling

digitalWrite(motorPin, HIGH);  // turn off the motor
digitalWrite(blinkPin,HIGH);  // turn off the LED
digitalWrite(motor1, HIGH);//
digitalWrite(output1starduino, HIGH);
delay(100000);        // multiply by 60000 to translate minutes to milliseconds
}

if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
{
 digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
 digitalWrite(LED_PIN, HIGH);    //turn on the LED
}

{
 digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
 digitalWrite(LED_PIN, LOW);    //turn off the LED
 }
}


Read Audio Data in Real-time over 3.5mm Stereo Cable My Goal

Have Arduino read audio output from a TRS stereo audio cable (coming from a computer, smartphone, etc.). As motivation for this use-case, once some audio data (depending on the sample rate) have been stored in a buffer, the Arduino will perform an FFT on the buffered data. The power contained in the FFT is mapped to the red, green, and blue frequency-bands of visible light to determine the color of an LED strip.

My Set-up

The obvious first step was to connect a Right-Angle 3.5mm Stereo Plug to Pigtail Cable to the Arduino. As is commonplace, this cable has a Tip, Ring, and Sleeve connector; Adafruit labels the black wire as ground (sleeve). They further label the red wire as "left channel live" (tip) and the white wire as "right channel live" (ring), if I can trust Wikipedia:

  Stereo sockets commonly provide two such NC contacts, one for the tip (left channel live) and one for the ring or collar (right channel live).

My Question

So, I've plugged the red wire into the A0 pin and the white wire into the A1 pin. However, I'm unsure of how to sample the actual audio signal from these analog pins.

I don't believe the analogRead() function solves the whole problem - it only converts a voltage reading at the pin into a value between 0 and 1023. Presumably, if I knew the bit rate (i.e., sample rate) & of each packet in the transmitted audio signal, I'd be able to construct signal from that. Is it possible to extract the original audio's waveform from a simple voltage signal? If not, what approach would enable the Arduino to read audio data from an audio cable?

Note: For those wondering, I have indeed heeded the advice from this Electronics SE answer to attach a DC-blocking/DC-bias circuit to the signal source before driving it into an analog pin on the Arduino.

The middle path

Build the simple op-amp (or whatever) 70s-era color organ, but without all the LEDs. Then basically feed the organ's LED-driving lines into the Arduino's ADCs. Sampling that pre-processed/summarized data, you can define a wide variety of RGB interactions without complicated math or an EE background. The timing requirements will be well-within the Arduino's reach, unlike computing FFTs or other "difficult" processes. Besides, old/new hybrids are cool!

Simply, YES: it is possible to reconstruct the waveform from the sampled signal. There are entire 400 level college courses on this subject, in fact, but it is rather simple to implement. However, you should study the FFT algorithm you plan to use a little more closely, as it actually requires a discreet time (sampled) input.

Some background: The audio signal you are getting from the TRS cable is continuous, but was recreated from discreet samples (unless your using a tape deck) by using reconstruction theory. The basic idea is this: you take a continuous train of discreet values (the sample points of the sound you want to make), then you multiply each one by a sinusoidal rectangle function (called a sinc, if you want to look it up), which basically takes your discrete values and makes them analog. The frequencies of the sampled signal will probably be 44.1 or 96kHz, although the signal you actually get is analog.

Now, the FFT!
The FFT itself is a discrete time function, meaning that it is designed to use sampled data (for instance, of vector of values read from analogread() once every T seconds, where T=1/f, f being your sampling frequency). I should warn you, unless you're planning on using a library someone else already made, the FFT is a complicated beast! It's not impossible to use--in fact once you understand it, it's really quite beautiful--just be aware there is a lot of circle-based math and opaque optimization.

So, again in short, yes, you can reconstruct a signal from its sample, but you don't need to!

Note: there may be more information on what you're trying to do on the Signal processing SE as well.

Hope that helps!

EDIT ADDITION:

In response to the comments, I very much agree that most lower level arduinos (assuming uno or similar) is not the ideal chip. However, there is a way around your sampling problem. Whether your processor can handle the higher sampling rate is questionable, but we'll address that momentarily.

Q: How to get a higher sample rate out a 10kHz max ADC.
A: Double up. Or triple up, or quadrupile up, etc.
The basic idea is, if you have one ADC reading channel 1 of a signal nT seconds (T being period = 1/10kHz and n being a discrete set of integers = 0,1,2,3...), then you can have a second ADC reading the signal every nT+(T/2) seconds. Then, you populate your data vector as DATA=[ADC1(0*T),ADC2(0*T+T/2),ADC1(1*T),ADC2(1*T+T/2),...] and so on. This effectively doubles your sampling rate. If you want to sample at ~40Hz, you use 4 ADC channels. The real question is how high do you need to go. By Nyqist's Theorem, you need a sampling freequency >= to twice of the highest frequency you expect to be present in your signal. In most recorded sounds this never above 18kHz. So, you do this with 4 ADC channels offset from each other by a quarter period, and you have a high enough sample rate.

Q: What if I can't process the data with an FFT that fast?
A: Never fear! Discrete time filters and power integration are here! (okay, that was a bit corny).
A much less processor intensive method of frequency band power estimation would be to implement band-pass filters in your software (which can work with very little overhead processor-wise) and then average the power output of each filter.

Again, hope this addition helps! But as another commenter pointed out, what you want to due may be much easier with a different chip. And as I will point out, moving the filtering and power integration to external op-amp circuits would be an equally simpler option, eliminating the entire sampling problem!


Arduino 1.6.4 not showing any /tty/ options in Serial ports hej guys,

recently I upgraded to Arduino's 1.6.4 IDE just to find out, that I can't seem to upload anything to my board. More specifically: The 1.6.4 IDE is not giving me the option to select the /tty/ board from the serial port list. I am avid Sublime Text 2 user, so obviously I tried to select the port in Stino and voilá: I was able to upload it to my boards.

Since I wanted to sort out if this is a software or hardware problem, I started to experiment with all my boards:

(all of them official boards, no clones)

2 x Arduino Micro
1 x Arduino Uno r3
1 x Arduino Duemillanove
1 x Arduino Mega 2560 r3
12 x Teensy 3.1
a bunch of different USB cables.

none of these boards were registered by the Arduino 1.6.4 IDE, even after restarting the software and the computer several times. i'd only get this in my port selection:

funny enough, my terminal told me the /tty/ device was there. here with the uno connected:

Dash:~ julianh$    ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodemfa131

I also tried to re-install FTDI drivers, with no results.

only when I installed the old (trusty) 1.6.1 version, I was able to upload again.

all of the boards are also working fine. I just used my uno and mega another machine a few days ago for some side projects.

can someone confirm this problem with the new IDE 1.6.4 on OSX Yosemite 10.10.3? or is there any solution available online?

thanks!

I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro.
Did a "reset to bootloader" on the pro micro, and hit upload, and it worked
 out nice and it still does!


Do we need to burn bootloader in new Atmega328p before uploading the arduino code I have an arduino code which is working fine. Now I am planning to make a PCB out of it. But I do not want to use the complete Arduino board. I just want to use the Atmega328p microcontroller. So my plan is to connect the USBasp programmer to the new Atmega328p and upload the code. So before this code, do I need to upload the bootloader or uploading the code first will run fine.

Tools > Burn Bootloader in the Arduino IDE does two things:

Set fuses according to the settings in boards.txt for the Tools > Board selection
Install the bootloader.

The latter is pointless since when you do an Upload Using Programmer the bootloader will be overwritten but the former is very important to do the first time you use a new chip(or anytime you want to change the fuses) to be sure that the correct fuses are set, which likely will be different from the default settings of the chip when you get it. Upload Using Programmer does not set fuses, the only way to do this via the Arduino IDE is Tools > Burn Bootloader.

So yes, you should Burn Bootloader.

If you want to upload code using the bootloader then yes you need to install the bootloader. If you don't want to upload code using the bootloader then no you don't need to install the bootloader.

It's simple logic.


Using TMRpcm object, why is the SD Card failing to be found by arduino? I am using this micro-sd card reader, and my wiring configuration is as follows (double and triple checked):

3.3v goes to 3.3v on the Arduino UNO
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 4 on Arduino UNO

When I run the 'basic' example from the TMRpcm library, everything compiles and uploads properly with no warnings. Looking at the Serial Monitor, I get "SD Fail", which, according to the comments, means that the SD card failed to initialize. The card is present, and works in my computer. Do I have something wired wrong, or is there another issue?

EDIT

I have tried using a different pin for D3, and changed the code as needed. Still no luck.

See  https://github.com/greiman/SdFat

Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.

Check if the reader is plugged in correctly. This will give a PEBKAC error.


HTTP Requests using Arduino I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.

void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post).
The fourth and the fifth posts also works fine but the sixth is same as the third.
Knowing that my API works 100% with Raspberry Pi and it has no errors.

The same thing for PUT and GET.

After Edition:
After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:

Attempting to connect to WPA SSID: WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.149
signal strength (RSSI):-66 dBm

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...

Starting connection to post server...

Starting connection to post server...

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.

I THINK the problem might be the client.println() statement.  I believe REST messages should be terminated with a \r\n and I think println just does \n.  So if you change it to client.println("\r") it should start working on every message.

Also you might want to consider moving creating the message into a function to reduce the amount of code you have.

I've observed that virtually every example of an Arduino web server posted online fails to adhere to the HTTP standard. When a "GET" request is received, the server should parse the "Content-Length: xxx" attribute to get "xxx", then read xxx characters. When sending a web page to a client, the length of the request should be calculated, omitting the HTTP headers (everything before the "html" tag) and the "Content-Length: xxx" attribute should be included in the header, where xxx is the length of the response from "html" tag to "/html" tag, inclusively.

I had the same problem described here, and nothing I did fixed it until I implemented the standard-compliant code described here.


Read/write data from 2 Arduinos simultaneously with Python So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.

If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like pin.write(1) to turn on or pin.write(0) to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.

The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.

At the moment I have custom code on My Arduino Mega and a StandardFirmata on the Arduino Uno, but I am open to other suggestions that could work.

Arduino Mega code:

/*
by Ben-Tommy Eriksen
https://github.com/BenTommyE/BenRotaryEncoder
*/

// Encoder connect to digital pin 2 and 3 on the Arduino.

int counter = 0;
//This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (4600);
  //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  Serial.println (counter);
}

void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
    counter--;
  } else {
    counter++;
  }
}

Python code:

import pyfirmata
import serial
import time

#Associate pyfirmata with python for my UNO board
port='COM5'
board= pyfirmata.Arduino(port)
#Use iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start()

#Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
outPin1 = 12 #passes the signal to the valve

s = serial.Serial('COM4',4600)
while time<60s #generalized:
    rotary = s.readline() #reads the counter of the rotary encoder form arduino

    #convert the rotary to an integer try/except is needed to work
    try:
        var = long(rotary)
        last_var = var
    except:
        var = last_var
        pass

    value1 = lickpin.read()

    # Here I move the cursor up and down depending on the rotation of the encoder
    # if the cursor moves above a certain value
    if y>-18:
        board.digital[12].write(1) #should open the valve

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).

Here is the pinout:

ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :

/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}


Transient and reverse current Does anyone know (1) how much transient current can be output from a pin and (2) how much (and how long) reverse current an output pin can take?  For instance, consider the following circuit (driven by a series of 10 ms pulses at 5V):

  o----------------
       |          |
       = 10µF    1k LOAD
       |          |
  o----------------

which would be a classical filtered (smoothed) PWM circuit.  When the pin goes to +5V, the capacitor would act like a short and allow very high current (assuming about 20 ohm impedance, maybe 250 mA) for a millisecond or so.  Similarly, when the voltage drops to 0V, the charged capacitor will discharge, leading to a reverse current until it bleeds through the load.  Will either of these damage the diodes in the pin or even the IC?  Thanks.  (Worse comes to worse, does this mean that a resistor and diode are needed to protect the pin?)

More info

1)  It's 10µF.  10 pF would be useless in a power supply, it would only store 0.05 µC of electricity at most, which would only be able to smooth the output for a few microseconds.

2)  The load is resistance, 1 k ohms.

3)  A diode would be handy if you wanted to prevent reverse current, since you could put a much larger diode outside than the protective diodes in the Arduino.  They are classically used with motors (inductive load) as a clamp diode.

4)  My general question is about high transient current or reverse currents.  A capacitor is just an example of a situation that could cause this.  Another example would be a pin that is putting out only occasional (for example) 1ms long 100 mA pulses, separated by many seconds.  Such a circuit is really not delivering much power, but for very short periods it exceeds that recommended 40 mA.  Would this burn out the pin or not?

5)  A capacitor in parallel with the load is pretty much the classic filtered DC power supply.  Open any wall wart you have and you'll see a transformer, a rectifier and several large (electrolytic) capacitors (along with a couple small ones) and a voltage regulator.  Closer to this example, say you want to deliver current at 2 volts DC.  You can do this by alternating 2 ms pulses (at 5V) with 3 ms at 0V.  Then have a capacitor in series to smooth it to closer to DC, making it more like analog output.  That is, in fact, exactly how adjustable power supplies often work.

It sounds like you are trying to make a digital to analog converter driving some type of load.  Look at this link: http://emesystems.com/BS2PWM.htm
It will give you a start. Please note they use an opamp as a buffer.

This 'buffer' has a very high input impedance and a low output impedance.  It can drive from a few mills to over an amp depending on the opamp chosen.  Additional circuitry can get you into thousands of amps if desired.  The schematic is a 2 pole filter originally designed for the Stamp microcontroller.

The filter soothes it out but adds a delay on the final output value (settling time).  The greater the filter capactance the lower the ripple and the slower the response.  You can add another pole to filter if you want.

As a bit of information from an old semiconductor guy absolute ratings are just that.  If you exceed them even for a few nanoseconds you can be sure you damaged the device, you just do not know when it will fail.

I have seen a lot of microcontrollers damaged because of capacitors connected to the pins, power excluded, doesn't matter if the pin is input or output.  When the power supply collapses it will inject current into the microprocessor substrate possibly damaging it.

Good Luck

I have had fairly lengthy discussions with Mike Cook from the Arduino forum about this sort of thing. I asked, for example, if it was OK to drive LEDs by PWM providing the duty cycle was short enough that "on average" the pins put out a current in specified range.

His answer always is: no!

The datasheet does not say you can exceed the absolute maximum ratings for a certain amount of time (like 1 µs). You are not supposed to exceed them at all.

It doesn't take a particularly large series resistor to limit current to the recommended 20 mA (250 Ω at 5 V).

Now you can probably "get away with" not using it, but you are basically moving into unsupported territory. If the chip fails after a year, don't blame the manufacturer.

  It's 10 microFarad = 10mmF. 10 picoFarad would be useless in a power supply

According to Wikipedia:

  A "micro-microfarad" (μμF, and confusingly often mmf or MMF), an obsolete unit sometimes found in older texts, is the equivalent of a picofarad.

Your use of mmF as a replacement for µF is confusing. I suggest either copying and pasting "my" µ from this post, or using a simple "u" instead.

  ... useless in a power supply

Surely you are not seriously suggesting that you are going to make a power supply, powered by an Arduino output pin?

I am presuming not, so perhaps if you describe your application?


How to flash/blink I2C LCD backlight without delay function? Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like #define BACKLIGHT_PIN 13. I know lcd.setBacklight(HIGH); and lcd.setBacklight(LOW); controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.

How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to lcd.setbacklight so as to control it.

I want to use an if statement to warn the user that so and so has happened, eg:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Ticker flashBacklight(toggleBacklight, 100);
// when I use ticker here am getting not declared in scope
const int buttonPin = 3;
int buttonState = 0;
// pls declare flashBacklight, long flashBacklight = 100; ??
// pls declare toggleBacklight

void toggleBacklight() {
  // lcd.setBacklight(!lcd.getBacklight());
  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}

void setup() {
  lcd.begin(20, 4);
  lcd.setBacklight(HIGH);
  pinMode(buttonPin, INPUT);
 }

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    // if button goes high the back light must keep on flashing until it's released
    flashBacklight.start();
    //flash the lcd backlight
  } else {
    flashBacklight.stop(); // Stop flashing the backlight
  }
  flashBlacklight.update();
}

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.

Besides the standard 'compute a target millis() and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.

One example is the Ticker library.

With these methods, you create a callback function and pass that function name into the object constructor, along with the timing parameters.

So you might:

[various #include, #define, etc.]

Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

// Create the callback function, which just toggles the backlight each call.
void toggleBacklight() {
  lcd.setBacklight( !lcd.getBacklight() );
}

setup() {
  [...]
}

loop() {
  // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

  if (warningSituation) {
    flashBacklight.start();
  } else {
    flashBacklight.stop();
  }

  flashBlacklight.update();
}

Another related library is SimpleTimer

EDIT

Your code example, updated:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void toggleBacklight();

Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

const int buttonPin = 3;
int buttonState = 0;
                      // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                      //   pls declare toggleBacklight

void toggleBacklight() {
 // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}
void setup() {
   lcd.begin(20, 4);
 lcd.setBacklight(HIGH);
 pinMode(buttonPin, INPUT);
 }
void loop() {
      buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
   {
    flashBacklight.start();          //flash the lcd backlight
  } else {
    flashBacklight.stop();           // Stop flashing the backligh
 }
   flashBacklight.update();
  }

You record the timestamp when you want the LED to turn off again and then check that against millis in the loop()

  if ( level 1 > level 0)
  {

     NewTone(4,1000,50); // initiate alarm
     blinking = true;
     lcd.setBacklight(HIGH);
     lcdToggleTime = millis();// this is a global
     lcdOn = true;
  }else {
     blinking = false;
     lcd.setBacklight(LOW);
  }

  //at the start or end of loop(); make sure it's always checked.
if(blinking){
      if(millis() - lcdToggleTime>+100) {
         if(lcdOn)
             lcd.setBacklight(LOW);
         else
             lcd.setBacklight(HIGH);
         lcdOn = !lcdOn;
         lcdToggleTime = millis();// this is a global
     }
}


How to reset ESP8266 wifi module I have programmed ESP8266 to make it accessible over the network using below program.

First Program

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

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

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();          //Handle client requests
}

It is working fine, What is the way to reset it to run below program? I wanted to send AT commands on serial monitor using below program which has been uploaded successfully but not responding AT commands on Serial Monitor, as ESP8266 is running above program and showing output of above program on running below program on Serial Monitor.

I want to reset ESP8266 so it responds to below program. What is the way ?

Connected to Moto
IP address: 192.168.43.115
HTTP server started

SecondProgram

#include "SoftwareSerial.h"

SoftwareSerial esp8266(2, 3); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(9600);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer
    Serial.write("Hello");
    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

You need to reinstall the AI Thinker AT firmware.

Here's how you do it: How to flash ESP8266 firmware update ESP-01 AI thinker

Last time I did it I used the esptool.py program, and used the ai-thinker-0.9.5.2.bin firmware (there's two versions on there, the default 115200 baud, and a 9600 baud variant).

On Linux I then used the command:

foo@bar:~$ ./esptool.py --port /dev/ttyUSB0 --baud 57600 write_flash 0 ai-thinker-0.9.5.2.bin
Connecting....
Detecting chip type... ESP8266
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 512KB
Flash params set to 0x0000
Compressed 520192 bytes to 165297...
Wrote 520192 bytes (165297 compressed) at 0x00000000 in 29.0 seconds (effective 143.3 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting...

This was, of course, with GPIO0 held LOW for programming mode (I actually use an adaptor with a programming switch that controls GPIO0), and for other operating systems you will need to change the port name to suit (COM3:, /dev/cu.usbmodem4873, etc).

//reset settings - in case of trouble just put in your code
//wifiManager.resetSettings();

That`s all you need


Programming an Array of ATTiny I am designing a board for my electronics project and i am using a number of ATTiny85 for it. The ATTiny's will be SMD so i will not be able to remove them for programming.

Moreover all of the pins of my uCs will be used for connections (apart from reset).

Is it possible in this case to achieve that, any ideas and suggestions are welcome

EDIT: Well, Vcc and Ground will be common, i will be using an external oscillator for all of them, the reset pin will be free, the other three pins will be used for gpio communication between the attinys.
I am connecting about 10 attiny in a daisy chain kind of thing

As long as whatever you're connecting the MISO, MOSI, and SCK pins to doesn't mind being driven externally, you can still program the ATTiny in-circuit - just break out those pins with reset to a standard 6 pin header and program them that way.

If one or more of those pins can't be driven externally (eg, because they're connected to another device that drives them and has no output disable), you'll need to add a tristate buffer IC between the MCU and the other device, or some jumpers you can remove when you want to program them.

Well you need access to pins 0 & 1 to program them, so you either do it off-board, or design in a way to access them - perhaps a PCB hole you can wire to temporarily, or a link you can fit/remove that changes the connection.

You will probably need to program them before the rest of the board gets filled up?

You havn't said what you will be connecting to these pins nor how many is an "array" which kind of limits how specific we can be here!


Button that increments a counter #include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

Your code, simplified, is:

void loop()
    int a;
    a += 1;
}

The problem here is that, by putting the declaration of your counter variable within the loop() function, you've made it local to that function. Every time loop() is called, a new variable a is created, initialized to zero, and then incremented.

You want to move the declaration outside of loop(), creating a global variable that will remain in existence and maintain its value after loop() exits, so that the value is still there when loop() is called again:

int a = 0;
void loop() {
    a += 1;
}

(This could also be done with a static variable, but that's probably beyond the scope of this question.)

all it is doing is printing 1 everytime the button is pressed.

make variable a static, or global.


Variable scope error guys.

I'm writing here because I cannot find an obvious error, so I'm stuck. Could you please help me?

Here's the code:

int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

int newArrayLength = 0;

void setup() {

    Serial.begin(9600);

}

void loop() {

  String dir = "AAA";

  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope
      Serial.print("   ");
  }

  Serial.println();
  Serial.println();

}

What I'm trying to do is to copy the array to a new one, but depending on the circumstances I need to take different source arrays (AAA or BBB).

The problem is in checking the values of an newly crreated array:

'newArray' was not declared in this scope

if I try to check its valus outside of if statment.

It seems my stupid mistake, but I can't find it.

After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)

So, the final code became like this:

int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

//Create a pointer, which will point to any of your arrays of your choice
int *newArray;

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

void setup() {

    Serial.begin(9600);

    //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
    //&: points to address of a chosen array.
    //[0]: is a must to grab all values!
    newArray = &arrayAAA[0];

    Serial.print("arrayAAA:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(arrayAAA[i]);
    }
    Serial.println();

    Serial.print("newArray:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(newArray[i]);
    }
    Serial.println();
}

void loop(){
    //Left empty
}

And it works perfectly, just what I expected!

Made corrections per @Majenko's comment

The following will not work on real Arduinos, but it did work for me on the ESP8266 and the Teensy3, which are what I use mostly, and the only ones I tested the code for: https://github.com/jayeye/jardino/tree/master/esp8266/ase25017

#include <vector>
  ...
  size_t vector_size = 42;
  std::vector<int> foo(vector_size);  // foo is a vector of 42 integers

Another correction: Exceptions do not work even on the aforementioned platforms, so do not access the vector with .at(n)

If you must have an array, use a unique_ptr with an array allocator:

#include <memory>
  ...
  size_t vector_size = 42;
  std::unique_ptr<int[]> arr(new int[vector_size]);

When arr goes out of scope, the array will be automatically freed.

You can always use malloc(), but you'll have to remember to free() it, and that's always a source of bugs.


Is it possible to increase the Arduino's input and output pins? I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.

I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.

In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?

I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

I am good at coding however when it comes to hardware sometimes I'll need some push.

Thanks a lot.

You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.

Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf

As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.

You can use a CD74HC4067 Mux multiplexer to increase the number of inputs/outputs. This IC will convert 4 analog or 4 digital pins to 16 inputs and outputs.


How many transistors can be connected to Arduino pins? How many TIP122 transistors can I connect to the Arduino digital pins? The Atmega328p datasheet states that the pins can source a total of 200 mA, while other documents state 40 mA per pin.

In the following circuit layout, I connected six TIP122 transistors with 2.2  kΩ  base resistors. I used an LM338 regulator to power the Arduino IC and other functions.

The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.

To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.

Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler.
Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.

Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.

I would use a N-channel MOSFET instead of the TIPwhatever.
AOD514 from Digikey has really low Rds, somewhere around 0.01 ohm, and can be driven from an Arduino pin, say thru a  150 ohm resistor to protect against the gate input capacitance of the MOSFET. A 10K pulldown resistor on the gate will hold the MOSFET off until the Arduino sketch starts up and controls the pin.
AOD514 is surface mount, but tab and pins are pretty good size and can be manually soldered.
AOD508 and AOD510 are even lower Rds, but cost a bit more at Digikey.


Arduino program using i2c stops working after printing to OLED a few times A NOTE ON THE PROJECT AND PROGRAM STRUCTURE

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

WHAT I AM TRYING TO DO ?

Read RTC into State class's static variables
Display once
Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
set to 1 minute) Service interrupt in loop by:

Read RTC into State class's static variables
Reset alarm for RTC
Update display

WHAT IS THE PROBLEM ?

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

WHAT HAVE I TRIED TO SOLVE IT ?

With Serial.println() in many areas such as before and after OLED::writeString is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing OLED::writeString statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.

This is wrong in many ways:

String input = Serial.readString();
serialInputBuffer = new char[input.length()];
input.toCharArray(serialInputBuffer, input.length());

What's fatal is that you later don't free the memory allocated with new. Don't use String and new. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.

Use a global buffer like char serialInputBuffer[64]; and use:

int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.

Don't use the Wire library.  If you look closely at twi.c, you'll find it has blocking calls with (potentially) infinite loops.  Eventually a condition will occur that causes one of the blocking calls to hang forever.

See this post and this post for details

Use something like SBWire

Frank


Can we control other servos with common servo code Arduino I am trying to control MG996R using code for a typical servo (SG90)
I used an external power supply, 5V,2A
I connected the servo signal line to Arduino slot 7,
servo positive to external power supply positive,
servo ground to external power supply ground,
while leaving the Arduino power supply and ground unconnected.
I tried the below code.
it works for SG90, while MG996R is not moving at all.

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(7);  //pin 7 is the one control servo

}

void loop()
{

  for (int pos=0; pos<=60; pos++)
  {
    myservo.write(pos);
    delay(15);
  }

}

Is it because the different servos need different code?

They work with same control signal, so the same code should work for both of them
You need make sure the ground of servo is both connected with the Arduino ground and the power supply ground (power supply ground for power supply positive, Arduino ground for the signal line)
I think SG90 worked even not connecting the Arduino ground is because the difference in design.
But you should always connect Servo ground to the Arduino ground.

@jsotola's comment is the answer, so I'll just quote it here:

the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

Also, make sure you're using the pin you set with myservo.attach(). Your comment says pin 9 but your code says pin 7, which is confusing. This code is using pin 7 as the servo signal:

myservo.attach(7);  //pin 9 is the one control servo


Is an atmega 2560 board compatible with the Adafruit Trellis? I want to build a custom midi controller for my computer, and yes, Adafruit has a mini Untz project. For my purposes, I need more analog inputs than the Leonardo, and the only other option I can find is the atmega 2560. Can i use that?

MIDI comes in many different arrangements.

The two most important ones for you are "MIDI Over USB" and "Traditional Serial MIDI".

The former encapsulates MIDI messages and sends them over USB to the computer. This is what you normally get when you plug in a USB-based MIDI instrument, or a USB to MIDI adapter cable.

The latter is a simple serial port running at a specific baud rate. It's generally opto-isolated as well.

On the Leonardo you can do either of those methods (you haven't mentioned which you use), but on the ATMega2560 you can only do the latter (that is, connect the board to a USB to MIDI adaptor cable).  However the Arduino Mega2560 (Note: this is a board, what you talk about is a bare chip) has a USB interface chip that can be re-programmed to look like MIDI.  That will bridge between the "traditional serial MIDI" to the "MIDI over USB". However doing so may impare your ability to program the board.

Another option is to use some PC-based Serial-To-MIDI bridge software which reads normal Serial data as provided by the Arduino and converts it into MIDI signals within your computer.

A third option is to step away from Arduino and choose a board that has both a native USB interface (with MIDI support in software) and more analog inputs.  A board such as one of the Teensy 3.x range would probably suit you well.

Mega2560 also has 4 hardware serial ports. Serial() can be left alone for programming via the PC.  Serial1, Serial2, Serial3 can all have Serial/USB chips added to talk to MIDI, after all it's just a Atmega16U2 that is programmed as needed.


Arduino Uno Issue: No output power I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.

I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab

I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.

I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.

Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you think you have built.

You need to have a current limiting resistor for each of the LED segments. Sharing one resistor between them all is a very bad idea, as multiple lit LEDs (in parallel) will be using the same resistor - see this excellent answer to Why exactly can't a single resistor be used for many parallel LEDs?:

  The main reason is because you can't safely connect diodes in
  parallel.

  So when we use one resistor, we have a current limit for the whole
  diode section. After that it's up to each diode to control the current
  that goes through it.

  The problem is that real world diodes don't have same characteristics
  and therefore there's a danger that one diode will start conducting
  while others won't.

I would hazard a guess that you've drawn too much current, or, in your case, tried to sink too much through the PWM pin.

Also, it would (probably) be better to use individual data pins, not PWM pins, to turn on each segment, rather than connecting all of the segments to just one pin. It just seems a bit odd to do it that way.


HM-10 discovery issue i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance

The HM-10 is a BLE-only device.

Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.

The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.

Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on both devices.

Detecting the physical Bluetooth layer is likely different from detecting the underlying protocol.  So it might be that the Arduino code is waiting until it sees a specific Bluetooth protocol.  I am guessing that it wants to use a serial Bluetooth protocol (as oppose to music or some other protocol).  You have not given enough details to determine if this is the problem.  However, I would next test your devices / hardware by loading up what is assumed to be working code on both your Android and your Arduino to test the connection.  The code in this project looks promising:


Can I reuse crystal frequency of Arduino? If I use some IC which requires clock frequency like 16MHz, can I take one from Arduino?

Or this it too high frequency to travel to neighboring board?

Yes but you need to know what you are doing.  You will need a clock driver and possibly a clock receiver depending on the devices you select.  Then you need to modify both boards voiding any possible warranty.

The best answer is NO!


NodeMCU does not connect to wifi I'm trying to connect my nodeMCU to my WiFi network but it keeps printing ........ which means is not connecting to the network. Here is my code used to connect to WiFi. Any reason why it isn't connecting to WiFi network?.

#include <ESP8266WiFi.h>

        // Replace these with your WiFi network settings
        const char* ssid = "******"; //replace this with your WiFi network name
        const char* password = "******"; //replace this with your WiFi network password

        void setup()
        {
          delay(1000);
          Serial.begin(57600);

          WiFi.begin(ssid, password);

          Serial.println();
          Serial.print("Connecting");
          while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }

          Serial.println("success!");
          Serial.print("IP Address is: ");
          Serial.println(WiFi.localIP());
        }

        void loop() {
        }

If your WiFi network doesn't have DHCP, then you must set the IP addresses

example:

  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.

If your powering the device via a computer USB port there is a good chance it’s not providing enough power for the wifi.
Try powering fron an external source.


MFRC522 minor problems I'm working on a small project for a presentation. My goal is to read the UID of multiple Mifare Classic cards and compare it to a hardcoded list for different actions. All is well (the reading and comparing part that is) but 2 small problems that I have encountered are:

The first (maybe up to three, since the reader is a little bit on the fast side) read after uploading my code will return a UID of just 0s and a wrong PICC type.
After reading a PICC and then trying to read another, the reader prints the UID / PICC Type of the reader before, which is kinda not helpful when trying to light LEDs based on UID.

Here is my sketch:

/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
  String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
// String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
// byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();
     // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
 String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
 byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}