Drawing a bar graph in a LCD I'm getting my first steps on Arduino and I'm trying to do an exercise where I have to draw a graph bar in a 16x2 LCD that indicates the values read from a vector of 16 integer elements amplified by the value read from a potentiometer (connected to the analog pin A0) during runtime. The graph should change in real-time as I move the cursor of the potentiometer to the left or right.
I have the following code structure:

void loop() {
// Read the 16 vector elements and map then to the screen height ...
// Print out their values multiplied by the value read form the potentiometer, to the serial monitor ...
// Draw a bar for each one of the vector elements (you will have 16 bars in the end)...
// If the graph has reached the screen edge do not amplify it anyfurther. If it has reached the bottom, do the same
//Wait a bit. Start drawing everything from scratch.

So far what I have is:
#include<LiquidCrystal.h>

// Create an LCD object and connect control wires

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int vector[16] = {3, 7, 10, 15, 28, 12, 43, 1, 6, 19, 29, 23, 54, 76, 57, 66};

int value=0;

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

  // Specify the LCD's number of columns and rows

  lcd.begin(16, 2);
}

void loop(){

  value = analogRead(A0);

  for(int i=0; i<16; i++){
    int vector2[i] = map(vector[i], 0, 1024, 0, 20);
    Serial.println(vector2[i]*value);
  }
}

However I'm getting the following error so far:
 In function 'void loop()':
28:25: error: array must be initialized with a brace-enclosed initializer
 exit status 1

Also I can't think of a way to do the last 3 steps of the code structure I have.
I know that if i would want to print a bar like a character I could do:
#include<LiquidCrystal.h>

// Create an LCD object and connect control wires

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte bar[] ={B11111, B11111, B11111, B11111, B11111, B11111, B11111, B11111};

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

  // Specify the LCD's number of columns and rows

  lcd.begin(16, 2);
  lcd.createChar(0, bar);
}

void loop(){
lcd.setCursor(0,0);
cd.write(byte(0));

}

But even this would only print a column in the first row and column and not in both rows and first column of the LCD.
Can someone help me with the error I already have and give me some lights on how to do the last 3 steps of the code structure?

First off you're going to need to define some custom characters. There's examples for how to do that.  You want characters that gradually fill up from the bottom to full, such as:
▁ ▂ ▃ ▄ ▅ ▆ ▇ █
Now, you have 8 lines per character and two lines of characters, which gives you a possible drawing range of 0-16. So you need to map your maximum range into that 0-16 span.
Finally you want to create a function to draw a single bar. This will take two parameters - the position of the bar (x) and the height of the bar (y). A simple little bit of mathematics later and you can work out what to print in the upper and lower characters.

If the value is = 0:

Both top and bottom are spaces

If the value is <= 8:

The bottom character is the one with the same number of lines as the value
The top character is empty.

If the value is > 8:

The bottom character is the one with all 8 lines filled
The top character is the one with the value - 8 number of lines filled.

So you may end up with something like (note - untested):
const uint8_t bars[8][8] = {
    { 0, 0, 0, 0, 0, 0, 0, 0xff },
    { 0, 0, 0, 0, 0, 0, 0xff, 0xff },
    { 0, 0, 0, 0, 0, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff },
};

void setup() {
    // other stuff, like setting up the LCD...

    for (uint8_t i = 0; i < 8; i++) {
        lcd.createChar(i, bars[i]);
    }
}

void drawBar(uint8_t x, uint8_t y) {
    char top, bot;

    if (y == 0) { // Both spaces
        top = ' ';
        bot = ' ';
    } else if (y <= 8) { // Bottom has bar graph, top is empty
        top = ' ';
        bot = val - 1; // Characters start at 0, so 1-8 is 0-7
    } else if (y <= 16) { // Bottom is full, top has bar graph
        top = (y - 9); // Characters start at 0, so 9-16 is 0-7
        bot = 7;
    } else { // Overflow - both top and bottom full
        top = 7;
        bot = 7;
    }

    lcd.setCursor(x, 0);
    lcd.write(top);
    lcd.setCursor(x, 1);
    lcd.write(bot);
}

void loop() {
    // your stuff in here
}

Then to draw a bar you just call drawBar 16 times:
for (uint8_t i = 0; i < 16; i++) {
    uint8_t y = <your calculation on vector2[i] here>
    drawBar(i, y);
}

If you've done it right you should end up with something like:
▁█ ▄ ▆█▇   ▃ ▃▇
██▃█▇███▅▆▇█▆██▃


Hardware/software serial for HC-05 can anyone please tell me the whole difference between hardware and software serial for the HC-05.
I read UART,USB cable, serial and I was like really confused
so what is the difference and advantages between both?
thank you...

Hardware vs Software Serial: Most microcontrollers/Arduinos have at least 1 hardware Serial interface. That means, that for this Serial interface the actual communication protocol (the transmission and receiving of the actual data) is implemented in dedicated hardware inside the microcontroller (which also means there are fixed pins, where you can connect to them on the board). That way you don't need code for doing the complex communication protocol. Instead the main CPU is only involved to handle the received and to-be-transmitted data, which need to be placed in a buffer register. The dedicated hardware then automatically sends and received the data.

As the number of hardware Serial interfaces is limited and fixed for the Arduino board/microcontroller, it happens, that you need more Serial interfaces, than you have in hardware on your board/in your microcontroller. Then you can use SoftwareSerial. That is a library, which handles the complete communication protocol in software, by directly setting and reading the electrical pin states according to the protocol. The advantage is, that you can use this on any digital pins for such an interface. Disadvantage is, that doing such things in software is complex. You can only listen on 1 SoftwareSerial interface at a time and the baudrate is limited (depending on the actual used microcontroller, e.g. it's frequency).
UART vs Serial: UART is the technical term for the used communication interface. Serial is an Arduino term, which is not used that way in other contexts. The real interface type is UART and the Arduino framework just names that Serial to make it simpler.
Connecting over USB cable or pins: Let's take the Arduino Uno as example. It has 1 hardware serial interface. This interface is connected to the pins 0 and 1 (RX and TX), but also internally to an extra chip. That chip handles the USB connection and behaves as a USB-Serial bridge. When communicating with the Serial Monitor in the Arduino IDE, you are actually using this USB-Serial bridge to talk to the microcontroller on the Arduino. But you could also use the RX/TX pins to do that.


Programming an Arduino using Python, rather than C/C++ I am not very skilled with the C Language and I was wondering if there is a way in which python could be used to program an Arduino. This would most likely require a different IDE in order to be able to debug the scripts them self.

It's going to be extremely difficult to get any kind of Python script running directly on the Arduino. The reason is that it's an interpreted language, so you would need the interpreter on-board in addition to the plain text script. There's probably not going to be enough memory for all of that.

Your best bet would probably be finding a way to compile a Python script to native machine code (which is how C/C++ works). I believe there are projects around to do something like that for other platforms, but (as far as I know) none which does it successfully for Arduino yet.

You might find some more useful information on this question at Stack Overflow: Is there a way to "compile" Python code onto an Arduino (Uno).


Expected ')' before ';' token Error Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the Expected ')' before ';' token Error

Here is the code:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i ; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i (&gt);= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

We could really use some help.

Well, for example for doesn't have four parts but three

for (int i = 0; i ; 256; i++) // => for (int i = 0; i < 256; ++i)

Next one doesn't look much better:

for (int i = 255; i (&gt);= 0; --i) // =>  for (int i = 255; i >= 0; --i)

There might be more, but these are really obvious. Like you copied it from some website with some characters translated into the html entities.


ESP8266 as WiFi monitor I'm about to buy two ESP8266 modules. I want them to use as an auto deauth device. The first module will monitor my WiFi router's packet transmission. If a certain device receive loads of packets from my router (which hogs my network) the second module will deauth that device or flood "forged" packets. There will be a threshold so a simple web browsing will not trigger the deauth process from the second module. Btw. My router doesn't support traffic shaping & QoS. Only a different kind of QoS (DHCP & IPP/TOS) which is useless because my ISP doesn't support it.

You're going to face significant challenges with this.

The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.

I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack.  The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).

So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.

Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.


Issue with usbserial for arduino clone I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5

I have sourced the solution from
http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html

Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"

and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution

This is the board:

I bought the board from this site:

http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html

screenshot from the IDE does now show any usbserial

You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:

sudo nvram boot-args="kext-dev-mode=1"

I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.


Parse UNIX-time from char[] I want to parse a large number to sync time on my arduino. For this i send it a string with the current time in Unix time format wich looks somethink like this:

  1535441277

For this I just call a php script wich echos the time() function.

But with  string.toInt()I'm unable to parse it. I suppose the number is too large for an int or a long. But I can't put it directly into the setEpoch() method from the RTCzero libary because it accepts as input datatype only uint32_t. So how can I parse large numbers on a system where double isn't implemented. And I don't just try to parse the entire HTTP-Response. I iterate thru the response and at the relevant line I write all the chars into a char-Array. I also have removed the \r and \n chars.

On 32 bit systems, uint32_t is usually the same as unsigned int and unsigned long. You should be able to parse the number using strtoul(), which is quite standard and returns an unsigned long.


Digital Comparator with ATTiny85 doesn't behave as expected Here is my schematic:

I've removed the resistors from the LEDs to make it smaller.
The 1 and 2 on the left are outputs from the arduino (which supplies the VCC and ground).

These 1 and 2 are HIGH or LOW and I want the leds to turn on according to this table:

┌───────┬────────────────────┐
│ INPUT │ OUTPUT             │
├───┬───┼──────┬──────┬──────┤
│ A │ B │ Led1 │ Led2 │ Led3 │
├───┼───┼──────┼──────┼──────┤
│ 0 │ 0 │ 1    │ 0    │ 0    │
│ 1 │ 0 │ 0    │ 1    │ 0    │
│ 0 │ 1 │ 0    │ 0    │ 1    │
│ 1 │ 1 │ 1    │ 0    │ 0    │
└───┴───┴──────┴──────┴──────┘

And this is the code I am using with the ATTiny85

const int pinA = PB3;
const int pinB = PB4;
const int pinOut1 = PB2;
const int pinOut2 = PB1;
const int pinOut3 = PB0;

void setup() {
    pinMode(pinA, INPUT);
    pinMode(pinB, INPUT);
    pinMode(pinOut1, OUTPUT);
    pinMode(pinOut2, OUTPUT);
    pinMode(pinOut3, OUTPUT);

    int a = digitalRead(pinA);
    int b = digitalRead(pinB);

    if (a == b) {
        digitalWrite(pinOut3, HIGH);
    }
    else if (a == HIGH) {
        digitalWrite(pinOut1, HIGH);
    }
    else {
        digitalWrite(pinOut2, HIGH);
    }
}

With this set up, I get this output:

┌───────┬────────────────────┐
│ INPUT │ OUTPUT             │
├───┬───┼──────┬──────┬──────┤
│ A │ B │ Led1 │ Led2 │ Led3 │
├───┼───┼──────┼──────┼──────┤
│ 0 │ 0 │ 1    │ 0    │ 0    │
│ 1 │ 0 │ 0    │ 1    │ 0    │
│ 0 │ 1 │ 1    │ 0    │ 0    │ <- See the difference
│ 1 │ 1 │ 1    │ 0    │ 0    │
└───┴───┴──────┴──────┴──────┘

I think it has something to do with the fact that the ATTiny gets powered on if you supply 5v to one of the input pins too and not to VCC.

And yes, I keep restarting the board (by pulling out the VCC pin and seeing the led turn off).

I've also tried connecting A and B to VCC and ground both in all possible positions. Here I noticed that connecting A (or B) to 5v (of the arduino) while VCC is not connected, the board will turn on.

I hope this is enough info.

You have to assign the status of all output pins in each of your "if statement" conditions. Think of it like 'if that happens, I want x, y, & z to be ON, and a, b, & c to be Off'. Unchanging the HIGH status of one output will remain that output HIGH for all conditions. Output pins never change their statuses untill they have an order "your code" to do this. Also you have to replace your code inside a loop function to repeat your code without the need to manually reset your ATTiny.

Assuming LED1 = pinOut1, LED2 = pinOut2, LED3 = pinOut3.
You have to replace "if conditions" in your code by the following:

while( 1 ){
    int a = digitalRead(PinA);
    int b = digitalRead(PinB);

    if ( a == b ) {
        digitalwrite (pinOut1 , HIGH);
        digitalwrite(pinOut2,LOW) ;
        digitalwrite (pinOut3, LOW);
    }
    else if ( a == HIGH ) {
        digitalwrite(pinOut2,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
        digitalwrite(pinOut3,LOW);
    }
    else if ( b == HIGH ) {
        digitalwrite(pinOut3,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
    digitalwrite(pinOut2,LOW);
    }
}

Also according to your application speed requirements, you can add a delay of about 300 ms before reading your digital inputs to allow the user to change the status of these digital inputs.


RFID does not respond after Ethernet.begin(mac, ip) initialization Good day, I have this problem with my simple project. I have a database with all RFID number of employee. What I want to do is to use an rfID to check if it is registered in the database. If it is, it would return a value of 1 else would be a value of 0.

I tried with arduino HanRun Ethernet shield. I was able to get a response from the php web server to the serial monitor. Tried the seeedrfid it successfully get the rfcard number. However, when i tried to combine the two, it would hang on Ethernet.begin(mac, ip) initialization. My code is below.

#include <Ethernet.h>
#include <SoftwareSerial.h>
#include <SeeedRFID.h>

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);

char state = '0';
char c;
byte mac[] = {0x60, 0xF8, 0x1D, 0xBA, 0x1D, 0x52};
IPAddress ip(192, 168, 20, 228);

EthernetClient client;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Serial set up");

  Ethernet.begin(mac, ip);
  Serial.print("My IP Address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  long rfID;
  // put your main code here, to run repeatedly:

  if (RFID.isAvailable()) {
    rfID = RFID.cardNumber();
    Serial.println(rfID);
  }
}

Serial.println(rfID) is not executed unless I remove the Ethernet.begin(mac, ip). Can anybody point me to the right direction?

The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.


Noise on piezo analog read due to Arduino power supply I am making a device that measures temperature and vibrations and records the values onto an SD card. It will be a standalone device.

The hardware used:
- Arduino Uno
- PCF8523 RTC clock
- MAX3186 + PT100 RTD temperature sensor
- Adafruit data logger shield
- Typical bare piezo sensor

For the vibrations, a piezo sensor is used. Because it can produce a signal in two directions, I decided to use a voltage divider to offset the signal from GND. Two 5.1K resistors are connected from the piezo negative terminal to 5V and GND. A 1M resistor is placed in parallel with the piezo sensor. The positive terminal is connector to analog input 0.

The sensor is read 100 times per data point, the maximum and minimum values are stored and the final value is set to be the difference between the two (two times the amplitude).

USB

9V wall adapter

When the system is powered via a laptop USB port, the resting value has a jitter of a few bits. When a 9V wall adapter powers the arduino, the jitter is +/- 30 bits. Any small vibrations disappear in the noise.

USB with piezo

9V with piezo

9V without piezo

I would like some help to find the best way forward.

edit 29-10 17:53 Added better plots

edit 30-10 17:53 Added plots for 2.5V and 3.3V lines

The 9V wall adapter is in most cases a switched power regulator with a high frequency. That's like a radio transmitter direct beside the wire. So there is nothing mystical, when the smooth USB Voltage does not show problems but the
"radio transmitter" does.

There are two ways the power supply can impact: over radio wave or as ripples over the regulated Voltage of your Arduino.

I asked myself, which one it is (or even both)? If you use the extra regulated analog voltage reference (AREF) as the +5V on your Voltage divider, it would be more likely that the problem comes through the air. Then it would help if you activate the shield of the wire by connecting it to GND.

If a rippled supply voltage is the problem, you have to smooth it. Perhaps with a low pass filter (a big Elko between Vcc and GND).

Perhaps you have a solenoid iron core. Then you can wrap the wire to the piezo sensor a few times around it (near the A0 Pin). This technique is often used in computer power supplies to prevent the switching frequencies from escaping to the public power lines.


Use distance sensor to trigger LED strip and stay on while the person is in range I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?

//Tell the Arduino IDE to include the FastLED library
#include <FastLED.h>

//Setup the variables for the HC-SR04
const int trigPin = 9;
const int echoPin = 6;
//Setup the variables for the NeoPixel Strip
#define NUM_LEDS 60 // How many leds in your strip?
#define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
CRGB leds[NUM_LEDS]; // Define the array of leds

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  if (inches <= 38)  {
    for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
      int r = 255 - colorStep;
      // Redness starts at zero and goes up to full
      int b = 255 - colorStep;
      // Blue starts at full and goes down to zero
      int g = 255 - colorStep;
      // No green needed to go from blue to red
      // Now loop though each of the LEDs and set each one to the current color
      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }
      // Display the colors we just set on the actual LEDs
      FastLED.show();
      delay(10);
    }
  } else if (inches > 38) {
    fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
    FastLED.show();
  }
  delay(1000);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second). This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

if (inches <= 38)

That You might want to change. Try using "while(inches <= 38)" and moving sensor calculations to that loop. When ever the distance stays less than You want the light should stay on.


First Arduino Project - Need Advice (powering WS2812B LEDs) I'm making a long LED display made up of 3 (8x32) LED matrices to go inside of a car. I can't seem to find any in-depth guides on this sort of thing. If anybody has examples that they would like to share please do!
The major issue I'm having is power. I'm extremely new to electronics, and I don't understand how these lights can be powered separately, and still be addressably lit by the Arduino?
Parts:
3* LED matrices (8x32)
https://www.amazon.com/gp/product/B088BTXHRG/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
1* Mega 2560
Here's the mock-up schema:

I forgot to draw in a switch, and a power line leading to the Arduino. But let's assume there will be a switch before the resistor and a line that feeds power to the MEGA 2560.
What in this schematic doesn't look or sound right?
Thank you all in advance for your help. This is probably not at all how to go about building circuits, and I'm trying my best to learn. All advice is wanted!

Powering the LED panels
Powering your panels will be your greatest challenge!
These LED panels are powered by a single +5V power input per panel and do not need a resistor in the power supply path (they actually need a very low resitance path). You do need a good quality +12V DC -> +5V DC power supply (or multiple, as explained below).
Since 3 x 256 RGB LEDs require a large amount of power when they're all lighted at the same time (something like 60mA * 768 =~ 46A), the power supply should be able to accomodate that. It might be better to use three individual, smaller (~15A) power supplies. You could opt for power supplies smaller than 15A, but you should ensure that all LEDs will never light up at full intensity at the same time.
For supplying power from a 12V car battery, you could use high quality 12V DC to 5V DC buck converters (they're efficient). Use good quality cable with a diameter large enough for transporting the large currents necessary. If you need connections in the path of the power supply, make sure they are good quality as well. To reduce losses in long stretches of wire, you should place the buck converter(s) near the LED panels.
Connecting the data lines
The color and intensity of Individual LEDs is controlled via the data input coming from your Arduino and it only needs one input to control all 768 LEDs. The first panel's "data out" should be connected to the next panel's "data in" and so on, like your drawing.
Software
I recommend you look up the FastLED library and some of its examples to get familiar with controlling large amounts of addressable RGB LEDs. There are many good examples and interesting projects out there.


C3 not declared in this scope when running MIDI example code I'm trying to run the MIDI example from Arduino.CC in Arduino Studio.

I am using an Arduino Leonardo, which has USB HID capabilities. I have installed the library as mentioned:

When I press the compile or upload button, it says:

'D3' was not declared in this scope

What's wrong? How do I fix this?

The pitches for the notes are taken from pitchToNote.h. In there you can see definitions for the notes like:

#define pitchC3  48

It seems that the names were changed from C3 to pitchC3.

I am not 100% sure, but my guess is that this was done to avoid conflicts between the note A3 and the analog input A3 (and silimar).

So, in line 25 of the example code, add pitch for all notes:

const byte notePitches[NUM_BUTTONS] = {pitchC3, pitchD3, pitchE3, pitchF3, pitchG3, pitchA3, pitchB3};


Teensy4.1 with 2x 8MB PSRAM Chips: external_psram_size=0 but EXTMEM char[] works as expected? So I got 2x PSRAM chips from PJRC with my Teensy4.1 and soldered them on (it's a hideous job as I lost my tips) but it's all tested with a multimeter and the connections are solid.
I ran the memtest sketch from here compiled in both Teensyduino and PlatformIO:
https://www.pjrc.com/store/psram.html
Aaaaand external_psram_size is reading 0 for both cases. Setting the memory size manually in the program also fails (even with 8MB).
However... EXTMEM vars work as expected. I'm not sure how the mem addressing actually works with the provided memtest program, either - it certainly doesn't seem to use EXTMEM anywhere.
Here's my memory tester (run to crash):
EXTMEM char bigBuf[10000000];
//char bigBuf[10000];
int c = 0;
void setup() {
  c = 0;
}

void loop() {
  bigBuf[c] = 'a';
  Serial.println(bigBuf[c]);
  Serial.println(String(c));
  c = c + 1000;
  delay(1);
}

Output with EXTMEM char[]: (as expected overflowed until 16MB)
a
0
a
100
...
a
16777100
a
16777200

Output with internal mem char[]: (as somewhat expected overflowed at 512K - max of RAM1)
a
0
a
100
...
a
488081
a
489081

Anyway, I'm glad EXTMEM works.. But can someone explain what's going on with the provided memtest? I admit I didn't read it over very well, but I thought that PSRAM could only be accessed via EXTMEM; how is it addressing otherwise?

I'm afraid your test program doesn't work as you intended. I tested it with a T4.1 without RAM soldered on and it gives the same result as in your question.

You didn't declare your array volatile. Thus, the compiler can (and probably will) simply optimize the reading back away.
Even if you declare the variable volatile the processor reads back the value from the cache line, i.e. you always get the correct value back, even without any external RAM.

Here a simple test program showing the effect. It always switches the LED on, even without external RAM soldered on the board.
EXTMEM volatile int test;

void setup()
{
    pinMode(13, OUTPUT);

    test = 42;
    if(test == 42)
    {
        digitalWriteFast(13, HIGH);
    }
}

void loop(){
}

Here the disassembly of the setup function. It clearly shows that the processor tries to store 42 in the (non existing) external RAM and reads it back from there. Obviously the read back value comes from the cache line.
(comments added by me)
void setup()
{
      7c:   push    {r3, lr}                         // pinMode code
    pinMode(13, OUTPUT);                             //
      7e:   movs    r1, #1                           //
      80:   movs    r0, #13                          //
      82:   bl  160c <pinMode>                       //-------------

    test = 42;
      86:   ldr r3, [pc, #20]   ; (9c <setup+0x20>)  // load r3 with address of 'test' (0x70000000, stored at 0x9C)
      88:   movs    r2, #42 ; 0x2a                   // load r2 with #42
      8a:   str r2, [r3, #0]                         // store content of r2 at address stored in r3. i.e., store #42 0x7000'0000 (EXTRAM)

    if(test == 42)
      8c:   ldr r3, [r3, #0]                         // volatile forces the compiler to read back 'test' (store it in r3)
      8e:   cmp r3, r2                               // check if equals r2 (contains #42)
      90:   bne.n   9a <setup+0x1e>                  // goto 0x9A if not equal

CORE_PIN13_PORTSET = CORE_PIN13_BITMASK;             // digitalwritefast code (next 3 lines)
      92:   ldr r3, [pc, #12]   ; (a0 <setup+0x24>)  // ...
      94:   movs    r2, #8                           // ...
      96:   str.w   r2, [r3, #132]  ; 0x84           // -------

      9a:   pop {r3, pc}                             // return from setup()

      9c:   .word   0x70000000                       // Address of 'test'; EXTRAM starts at 0x7000'000
      a0:   .word   0x42004000                       // Address of GPIO register for LED


Is it possible to use Arduino PWM for audio within a PAM8493 amplifier? I've seen some projects using PWM for playing audio files, and it seems like it needs an amplifier, otherwise the sound is very low.

I already made a project using a DFPlayer and PAM8403, but now I need more control over the files in the SD Card which is not supported by the DFPlayer library, so it seems like I need to use PWM and a SD Card module, instead of a separate audio module.

My questions are, can I simply connect the PWM output to the amplifier (PAM8403) and I will be able to control volume (using the programming language) and have a good quality sound?

Are you using a basic Arduino board (not I2S) and a sampling frequency of 8 kHz or 16 kHz? That could interfere with the default switching frequency of 260 kHz.

My suggestion is to use a low pass RC filter.
You might have to lower the signal level from the Arduino.
The PAM8403 requires a series capacitor and resistor at the input (those are probably already on the amplifier module).
In the end you probably need a voltage divider with a capacitor to ground for each channel.

I don't know if your PWM library has volume control. The TMRh20 has a function to set the volume.

The overall quality will be reasonable, but not very good. There are MP3 shields that can play mp3 files from a SD memory card. Those have better quality.

[ADDED]
I think I have misunderstood your question. Sorry. I'm still not sure that I understand your question now.

Wiki of DFPlayer Mini: DFRobot:DFPlayer Mini
Code on Github for DFPlayer Mini: Github:DFPlayer Mini
The PAM8403 has no volume control, you need to adjust the audio signal that is going to the PAM8403 module.
The DFPlayer Mini code has functions for volume, volumeUp, volumeDown and readVolume. However, it does not seem to have a function to select a specific file.

The Adafruit Music Maker shield is in two versions, one has an amplifier onboard: Adafruit:Music Maker MP3 Shield for Arduino w/3W Stereo Amp - v1.0. With that shield, you can play a file by its name. It can also set the volume. I suppose that is what you want ?


random soft wdt reset while request i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some serial.println lines) and i see i get soft wdt reset right there in http.post.

i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.

do you have any idea what cause this problem?

Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused
So the only thing as of now I can recommend
There is an issue with bearssl:

It's a WDT error caused by an extended SSL negotiation.

Change the core frequency to 160MHz (if not already done) and try again.
Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess


Fastest Communication from NodeMCU to Arduino Nano For one of my projects, I need to transmit data from NodeMCU to my Arduino Nano, in real time, I used S-Bus, but it quite unsatisfies me, as, slight latency is taking place.
I am transmitting a JSON file, with 4 signed 16 bit integeres.
Now,I need to know, what is the fastest and most reliable way to transmit data from NodeMCU to an Arduino Nano. Any detailed description, or even suggestion will be very much helpful. Thanks in advance !

If it comes to speed and reliability you have to choose an interface that is handled in hardware on both sides. For the arduino nano you have the following options (nodeMCU supports all of them):

UART:

not very fast (order of 10kbit/s), but it's full-duplex (asynchronous communication in both directions)
implementation is trivial due to Serial.h
long distance (order of meters)

I2C:

not very fast either (order of 100kbit/s), but not full-duplex
implementation is straight forward because both slave and master are implemented in arduino library
only over short distance (order of cm)

SPI:

quite fast (>1Mbit/s), full-duplex
implementation might require some experience (as far as I know, slave mode is not supported by SPI.h)
long distance (order of meters)

Which of those is the best option still depends on your specific requirements, but personally I like SPI very much because it is very fast and stable.


Is it possible to program/flash ESP8266MOD(07) With Arduino UNO i am new to ESp and yesterday i received my ESP8266MOD, i don't have FTDi connector with me right now(it's on the way).

Is it possible to flash ESP with Arduino UNO?

Regards,
Ben

Yes you can.

Take a look at this detailed guide.

The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:

You'll probably want some buttons to facilitate the flashing process:


Day-night powered Arduino What should I do to have an Arduino Pro Mini 5V (clone) powered by a 5V solar panel during the day and by battery during night which will be charged during the day by the solar panels.

is there any guide out there?
is it possible with the 5V version of Arduino Pro Mini or will I have to buy the 3.3V
I prefer to make the circuits by myself rather than buying them (for example: the charging circuit.)

This would be better answered on Stack Exchange Electrical Engineering.

Also see this question and answers. This is not quite the same and the answers there are OK but less than complete or correct, but it adds to the resource available.

You need a battery charging controller, a PV (solar) panel capable of producing somewhat more than maximum battery voltage and enough energy to operate your circuit and a battery with enough voltage to operate the device and enough capacity to store the energy.

Current drain will vary with total circuit. You can measure this will a milliammeter. I'll assume that 50 mA continuous will be enough. Less or much less may suffice. I have a pro mini clone operating at 20 mA on 5V at present and with due care you may be able to operate one with less or much less current depending on application and what your circuit needs are.

Looking at solar current needs at present, the average solar current needed is about Icircuit x 24/SSH mA where SSH = average sunshine hours per day. eg if you had 4 hours of sunshine per day but want to run the circuit for 24 hours a day the sun must provide (24 hours per day)/(4 hours of sun) = 6 x as much current as the circuit needs on average. So if your circuit needs 50 mA continuous the PV panel must provide 6 x 50 mA = 300 mA for 4 hours per day. You will see below that this is not a trivial amount.

Sunshine hours per day may be found for sites worldwide using the excellent www.gaisma.com The average sunshine hours per day for Iráklion may be found at that link and other locations in Greece can be found here but will probably be similar.
For Iráklion the SSH may be found in the 1st line of the 4th chart.
Average hours/day of equivalent full sunshine = kWh/m^2/day = a peak of 8.53 hours in June and a low of 2.08 hours in December.
Wow!
I think that is about as sunny a place in Summer as anywhere on earth not in the polar regions.  In Winter it gets about the same SSH as in my city. You can calculate PV sizing for peak summer - but if you want year round operation you should use the worst case winter month and add a bit for bad days.
For Iraklion us say 2 SSH per day so the panels needs to provide 24/2 = 12 x winter average load. So per 10 mA of load yo need 120 mA of panel and if the mean load is 50 mA you need 12 x 50 = 300 mA panel output.

Battery voltage needs to be > 5V at all times.
An easy cheap available starting solution is to use a 6B lead acid battery.
These are easyish to charge and provide a relatively stable operating voltage.
Vmax_charge is about 7V so an 8V or 9V PV panel is "about right". 9V is a common voltage for hobby applications. An alternative is to use a 12V panel. this is probably more suitable as they are widely available and cost per energy out is often lower. This wastes MOST of the panel output but still MAY be the cheapest option in many cases. (A 12V x 600 mA panel is rated at about 18V x 0.6A ~= 10 Watts. Actual Arduino load = 50 mA x 5V x 12:1 = 3 Watts)

At 50 mA load you need 24/2 x 50 mA = 600 mA PV output in full sun.
PV panel sizing is not as may be expected. It is easiest to get a panel that makes at least enough voltage and enough current. This is because panel RATED voltages are usually higher than the voltages they are used at. eg 12V system PV panels are usually rated at 18V max power voltage- so an 18W panel provide 18V at 1 A BUT if attached directly to a 12V battery the input to the battery = 12V x 1A = 12 Watts. There are ways around this but at first, just concentrate on panel mA.

So, you "need" a 600 mA panel for a 50 mA load.
Or a 60 mA panel for a 5 mA load.
Or a 6 mA panel for a 0.5 mA load.
Obviously, reducing load current is going to help panel sizing.
So knowing what your application really needs is essential.

Batery is easier.
If you use 6V lead acid then for one day you need.
Hours x load = mAh.
Here load=24 hours. mA = 50 in this example.
mAh = 24 x 50 mA =  1200 mAh = 1.2 Ah. This is the capacity of about the smallest LA battery commonly available. In practice you want to discharge your battery by only a small % of its actual capacity so use a 2.4 Ah or 3.5 Ah or larger. 7Ah is not vastly dearer and will last far longer and will have several days of reserve capacity for bad weather.

Charging can now be discussed - but I'll stop here and see what is said about the above. We can add charging and other detail if it seems useful to do so.

An easy battery to use is 2 x LiIon or LiPo cells in series.


Multiple timers with different frequencies I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?

Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.

#include <TimerOne.h>

#define PIN_RED 52
#define PIN_GREEN 50
#define PIN_BLUE 48
#define PIN_YELLOW 46

#define N_LEDS 4

float freqs[N_LEDS] = {1, 2, 3, 4};
int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

long int usec_to_invert[N_LEDS];
long int full_usec_to_invert[N_LEDS];

boolean led_states[N_LEDS];

int who_is_next()
{
  int next_to_invert = 0;
  for(int i = 0; i < N_LEDS; i++)
  {
    if(usec_to_invert[i] < usec_to_invert[next_to_invert])
    {
      next_to_invert = i;
    }
  }
  return next_to_invert;
}

void process_timer()
{
  int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
  long int time_past = usec_to_invert[to_invert_now];

  for(int i = 0; i < N_LEDS; i++)
  {
    usec_to_invert[i] -= time_past;
  }
  led_states[to_invert_now] = !led_states[to_invert_now];
  digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
  usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

  int next_to_invert = who_is_next();
  long int time_to_pass = usec_to_invert[next_to_invert];
  if(time_to_pass <= 200)
  {  // The interrupt processor should finish work
    Timer1.setPeriod(200);
  }
  else
  {
    Timer1.setPeriod(time_to_pass);
  }
}

void setup()
{
  Serial.begin(115200);
  for(int i = 0; i < N_LEDS; i++)
  {
    pinMode(pins[i], OUTPUT);
    led_states[i] = false;
    full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
    usec_to_invert[i] = full_usec_to_invert[i];
  }

  int next_to_invert = who_is_next();
  Timer1.initialize(usec_to_invert[next_to_invert]);
  Timer1.attachInterrupt(process_timer);
}

void loop()
{
   delay(1000);
}

My suggestions would be:

Implement a class that handles the queue and timer settings and uses callbacks.
If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
DO NOT wait in the ISR "process_timer()", since you might lose other interrupts! (for the Serial communication, for example)
is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or

use a total overkill system for this situation, such as my multitasking-library arduOS that also covers a some other things.


How useful could the Arduino Yun be in computer vision in a robotics project? I've recently ordered an Arduino Yun and several other components to begin on a small robotics project (based on an old 4x4 RC Truck).  Although not mandatory for what I'd like to do, I was wondering how feasible it would be to mount a small camera or two and write some software for the Linux portion of the Yun to do basic image/video analysis such as face detection and computer vision based path finding?

Mostly this is a question about the processing power capabilities of the Yun.  Has anyone had any luck doing simple image analysis/recognition on this processor?

(Also, if anyone with 150+ rep could edit this to create and add the "computer-vision" tag that would be great)

It probably has enough memory and speed to run basic object recognition software, but I there's a better solution, and that's to do your image capture and your object recognition with another device, and use the Arduino to act on the incoming data in some way. That would give you enough juice to do object tracking or searching. I plan to do this for my copter gimbal hopefully to be able to track objects on the ground, like criminals running from the cops for example.

This product will work great for that. Since you need a camera anyway, I think this is a pretty good deal... http://petapixel.com/2013/09/01/pixy-low-cost-camera-recognizes-follows-objects-color/

Can be purchased here: http://www.adafruit.com/products/1906

AdaFruit has tutorials to help you get started.  (Computer-vision doesn't exist as a tag right now and I can't create it, but I tried, sorry)


Can't power HC-05(5v) with Arduino Pro mini (3.3v)? I am trying to use HC-05 (5V) with Arduino Pro Mini (3.3v) but I have had little success.

I am using a coin cell to power the pro mini which powers it on and is working fine.

But, my HC-05 doesn't power on. I am trying to power it externally using two 3.7v Lipo-batteries that gives a total of 7.4v but I have tried numerous changes and nothing seems to work.

Circuit Diagram attached below.

Also, HC 05 has an onboard regulator for levelling it to 3.3v

Please Help!!!

It seems like 7.4V DC is greater than the 5V regulator input range on the HC-05.

For example, in the Core Electronics tutorial for the HC-05 (the tutorial PDF calls it a JY-MCU. I can't find any major differences), the pinout table says the voltage should be from 3.6V to 6V DC:

These same values are confirmed by a back-of-the-circuit-board photo from arduino-info.wikispaces:

Components101 says the range is 4V to 6V.

Unfortunately your coin cell voltage is too low. That leaves you with the following options to drop your voltage (if you must use the 7.4V DC battery). Your choice will probably depend on the Wh capacity of your battery, and how efficient you need the voltage drop circuit to be.

Zener diode (few components, inefficient use of power)
Voltage divider with resistors (few components, inefficient use of power)
Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
Switching regulator (many components, efficient use of power (because it does not use a resistor to drop the voltage)

Further details on each of these options are at Lower Voltage Methods Other than Voltage Dividing.


Data Logging GPS with Arduino I am working on a project for my final in a first year programming course at my high school. I would like to make an Arduino based data logging device that I can bring with my on the mountain biking trails around where I live to create a map. I have found a lot of great sources online but I do not have a small budget. I have an Arduino Uno and a breadboard. My first question is whether it is easy to interface between an Uno and my phone for data logging, or if it would just be easier to buy a microSD card shield? And I need help finding a GPS unit. I have no preference and size is not really a problem. I just need to know how to interface with the Uno. Also if you have any links to other sources I can use that would be greatly appreciated!

I've been looking at the same problem, and there is a lot of new stuff now that may still count as a DIY project, but cut out a lot of the leg-work.

On kickstarter there are a lot of new boards that can make it easy:
Here is a ready to go GPS tracking band:
https://www.kickstarter.com/projects/blipperbands/blipper-bands-safety-wherever-you-go?ref=nav_search

Spark-IO has a board that gives you 20,000 messages per month, so you could use it instead of a cellphone to send out the data.
https://store.particle.io/?product=particle-electron

U-Blox makes gps higher-end consumer GPS units that are used in autonomous drones.
There are also a lot of instructables that show how to do the GPS datalogging with while building a drone. These would be small enough and light enough to use while cycling.


SoftwareSerial problems Hi we are using an Arduino Micro and working with a Bluetooth device and a Rfid Scanner from Sparkfun(ID-20 LA). For that we implemented 2 SoftwareSerial objects and the Serial port for the Serial Monitor. If we use one SoftwareSerial object and the normal Serial everything works fine. For example we can send and receive things over Bluetooth. But when adding another SoftwareSerial object( Rfid then ) One of them doesn't work.

Starting with the Rfid SoftwareSerial ends up to the same result.

We've also already tried to change the ports and so one.

Every help is appreciated.
Thanks in advance.

The Code ( this is already the third programm nothing has changed )

#include <SoftwareSerial.h>

SoftwareSerial rf(11, 12);
SoftwareSerial bt(8,9);

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

}

void loop() {
  if(Serial.available())
  {
   while(Serial.available())
     Serial.write(Serial.read());

   Serial.println("");
  }

  if(rf.available())
  {
   while(rf.available())
     Serial.write(rf.read());

   Serial.println("");
  }

  if(bt.available())
  {
   while(bt.available())
     Serial.write(bt.read());

   Serial.println("");
  }
}

Taken from http://www.arduino.cc/en/Reference/SoftwareSerial:

Limitations

The library has the following known limitations:

If using multiple software serial ports, only one can receive data at a time.

If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. AltSoftSerial overcomes a number of other issues with the core SoftwareSerial, but has it's own limitations. Refer to the AltSoftSerial site for more information.

If you look at SoftwareSerial's code, you'll understand the limitation:

/* static */
inline void SoftwareSerial::handle_interrupt()
{
  if (active_object)
  {
    active_object->recv();
  }
}

Basically, the code waits for an interrupt to detect state changes on the pin, and directs it to the "active" serial object.

Hope this helps.


Is this a good function for I2C receive? I'm trying to fix my I2C code:

Is the following function correct because it has multiple returns. I don't know if that would work.

uint8_t I2C_rx(uint8_t ack_rx)
{
    uint8_t i;
    if (ack_rx)
    {
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); // sending ACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
    else
    {
        TWCR = (1<<TWINT)|(1<<TWEN);           // sending NACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
}

No problem with multiple returns but it could be reduced to:

uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

or

uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

Cheers!


Use IR remote with arduino I would like to use the IR remote with Arduino to turn on a LED and turn off the same LED when I push on the remote.

That is to say :

If I push on 1 I would like the LED turn on
If I push on 2 I would like the LED turn off

Here is my code :

#include <IRremote.h>

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

const int L1 = 13;

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(L1, OUTPUT);
}

void loop(){
  if (irrecv.decode(&results)){
        unsigned int value = results.value;
        Serial.println(value);
        irrecv.resume();
        if(value == 12495){
        digitalWrite(L1, HIGH);
        delay(1000);
        }
        else if(value == 6375){
        digitalWrite(L1, LOW);
        delay(1000);
      }

  }
}

But the problem is when I push on 1 I just see the LED turn on but very quickly the LED turns off then whereas I don't push on the button 2.

Could you help me please?

This line of your sketch irrecv.blink13(true); tells the IRrecv object to flash the LED on and off when an IR signal is received. boarddefs.h in the IRremote folder has pin number 13 defined as the default BLINKLED. The code you have written in loop() is trying to do something different with the same LED. I would remove this line irrecv.blink13(true); then try your sketch again. Once the LED is working correctly, try removing both of these lines delay(1000);.


Linker error when trying to use functions in separate header and source files It is my first day of working with Arduino (it is a Due). I want to read from TMP102 through I2C. I wrote some code and it works just fine. But now I want to separate the TMP102 code from the main source code. But I get linker error:

  sketch_jun15a.ino.cpp.o: In function setup':
  C:\Users\Saeid\Desktop\sketch_jun15a/sketch_jun15a.ino:62: undefined
  reference totmp102_allocate(int)' collect2.exe: error: ld returned 1
  exit status

My code is at the moment consist of 3 files:

tmp102.h

#ifndef TMP102_H
#define TMP102_H

//TP102 sensor struct
typedef struct TMP102 {
  int   address;
  float celsius;
  float fahrenheit;
} tmp102_t;

tmp102_t* tmp102_allocate(int address);

void tmp102_init_struct(tmp102_t * t, int address);

#endif

tmp102.c

#include "tmp102.h"

tmp102_t* tmp102_allocate(int address) {
  tmp102_t* t = (tmp102_t*) malloc(sizeof(tmp102_t));
  if(t) { //allocation success
    tmp102_init_struct(t, address);
    return t;
  } else {
    return 0; //null pointer
  }
}

void tmp102_init_struct(tmp102_t* t, int address) {
  t->address = address;
  t->celsius = 0.0;
  t->fahrenheit = 0.0;
}

and here is the setup function of the sketch:

#include "tmp102.h"
void setup(){

  //setup TP102 sensors
  tp_1 = tmp102_allocate(72); //error is here
  tempSensors[0] = tp_1;

  //rest of stuff...

}

I think there is no mistake in the code. There is also no option in the Arduino IDE so that I can meddle with the compiler/linker options.

All the files are inside the sketch folder. I created these files using the drop down button in the IDE...

This is talked about here.  Evidently, the C++ compiler changes names of *.c files when compiling.  Try changing the names of your files from *.c to *.cpp so that the C++ compiler does not change the names. Then recompile.


Opamp for amplifying 1V signal voltage to 2V I'm doing my first electronics project where a signal that varies between -1 to 1 V is going into an analog pin on the Arduino. The amplified signal has to be read as fast as possible by Arduino. The source signal is at 60 Hz.

Will this LM324 be a suitable 4-channel opamp for my needs? How concerned should I be about the 2 mV input offset and 20 nA input current bias?

To make full use of the 10bit ADC, would you recommend using an opamp with gain of 2 and biasing the signal by +2.5V? If so, will it be better to create the bias using a potential divider across +5V and GND, or using a 2.5V voltage regulator?

Or would it be better to set AREF to 2V and bias the signal by +1V? In this case, will it be better to use a 2V voltage regulator, or a voltage divider across Arduino's 3V3 and GND using 20M and 33M resistors?

A 2mV offset voltage will become a 4mV error after amplification. You haven't shown the schematic for your amplification, but the current bias will also become error after amplification.

That LM324 variant is surface mount, but there are other LM324 variants in a DIP package, which will work fine in a breadboard.


Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space? In order to allow bigger user program size, is it possible and advisable to reload Pro Mini with the boot loader originally designed for UNO. This will save 1.5 KB flash space (UNO boot loader is 0.5KB, Pro Mini is 2KB).

Using a smaller boot loader is an 'intermediate' step to get more space while still enjoy the easy benefit of the Arduino IDE and many library/code example. Of course, ultimate step is to remove all boot loader (only small saving of 0.5KB if above is possible) and switch to ATmel development environment, ATmel studio, which is complex but programmer has full control of everything.

Did I miss anything in the followings?

I tend to believe that it is possible as

a) same ATMega328 chip is used in both board

b) Pro Mini is essentially cutting UNO into two halves, the MCU and the USB/Serial converter now use external USB to Serial converter

If the Pro Mini board is reloaded with UNO boot loader, how should the boards.txt file be edited to reflect the changes so that the IDE will handle it correctly?

Many thanks in advance

You can just flash the newest optiboot_atmega328-Mini.hex. That one should also be only .5k in size, as it starts writing at the same address (7E00).

If you divide 7E00 by two you get 3F00 (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)

3F00 is exactly the start of the Boot Loader Flash Section when you  have selected a 256-words Boot Size (page 291 of the datasheet). 256-words is the 0.5kb you want.

Just make sure you have the BOOTSZ1, BOOTSZ0 fuses set to 1

As for the boards.txt. I think you only need to change mini328.upload.maximum_size=28672 to mini328.upload.maximum_size=32256.


How to do run time calibration for MPU9250? Does anyone know how to do the run time calibration for MPU9250 ?

I used this script to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. This guide explains how to calibrate the MPU9250's magnetometer.


analogRead() takes >400 us on Arduino Zero but ~100 us on Uno, why? I've been trying to figure out why the analogRead() function takes about four times as long on an Arduino Zero than on an Uno, when the Zero has a faster clock than the Uno.  Arduinos website says that it should take around 100 microseconds, and it does on the Uno, but it takes a little over 400 microseconds on the Zero. To time it, I've been setting a digital pin high immediately before the function call and low immediately after and measuring the period on a digital osscilloscope.  I'm just trying to test analogRead, so I'm not doing anything else in this code.  I've tried putting the ADC in freerun mode, and it trims ~15 us off of the ~415 us it currently takes.  I've also used the on-chip debugger to look at the disassembly, and the line that takes too long is always the line waiting for the conversion to complete.  I was also wondering if other ARM-based Arduinos (like the Zero) take over 100 us.  Thanks!

int   sensorPin = A1;
int      ledPin = 11;
int sensorValue = 0;

void setup() {
  analogReadResolution(12);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin,HIGH);
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin,LOW);
}

Arduino is universal platform, lot of wrappers to hide real hardware and it is slow. For example digital write is about 100times slower than direct access to hardware.

For example for AVR Mega328p based Arduino analogRead looks like (without macros):

int analogRead(uint8_t pin)
{
    uint8_t low, high;

    if (pin >= 14) pin -= 14; // allow for channel or pin numbers

    // set the analog reference (high two bits of ADMUX) and select the
    // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
    // to 0 (the default).
    ADMUX = (analog_reference << 6) | (pin & 0x07);

    // start the conversion
    sbi(ADCSRA, ADSC);

    // ADSC is cleared when the conversion finishes
    while (bit_is_set(ADCSRA, ADSC));

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

    // combine the two bytes
    return (high << 8) | low;
}

There are no extra function calls, no much extra actions and ADC is enabled in the startup code (as most of hw).

On the other side there is ARM based arduino with SAM3X8E:

uint32_t analogRead(uint32_t ulPin)
{
    uint32_t ulValue = 0;
    uint32_t ulChannel;

    if (ulPin < A0)
      ulPin += A0;

    ulChannel = g_APinDescription[ulPin].ulADCChannelNumber ;

    static uint32_t latestSelectedChannel = -1;
    switch ( g_APinDescription[ulPin].ulAnalogChannel )
    {
        // Handling ADC 12 bits channels
        case ADC0 :
        case ADC1 :
        case ADC2 :
        case ADC3 :
        case ADC4 :
        case ADC5 :
        case ADC6 :
        case ADC7 :
        case ADC8 :
        case ADC9 :
        case ADC10 :
        case ADC11 :

            // Enable the corresponding channel
            if (adc_get_channel_status(ADC, ulChannel) != 1) {
                adc_enable_channel( ADC, ulChannel );
                if ( latestSelectedChannel != (uint32_t)-1 && ulChannel != latestSelectedChannel)
                    adc_disable_channel( ADC, latestSelectedChannel );
                latestSelectedChannel = ulChannel;
                g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_ANALOG;
            }

            // Start the ADC
            adc_start( ADC );

            // Wait for end of conversion
            while ((adc_get_status(ADC) & ADC_ISR_DRDY) != ADC_ISR_DRDY)
                ;

            // Read the value
            ulValue = adc_get_latest_value(ADC);
            ulValue = mapResolution(ulValue, ADC_RESOLUTION, _readResolution);

            break;

        // Compiler could yell because we don't handle DAC pins
        default :
            ulValue=0;
            break;
    }

    return ulValue;
}

As you can see there is little bit more actions to do single measure using HAL (Hardware Abstraction Level) so you have another level of abstraction here.

If you want faster actions, you can access hw directly, or use HAL and skip unnecessary steps. It would be much faster then.


backup battery for FeatherWing DS3231, RTC I am working with slightly modified example code for the Adafruit FeatherWing DS3231 RTC (real time clock) board. The DS3231 chip itself is from Maxim. Since the cell is described as a "backup battery" a literal interpretation suggests that you don't need the backup battery in order to operate the board if the board itself is powered and you don't mind that the device cannot remember the time when board power is lost. I might be taking the term "backup battery" too literally since it doesn't seem to work.

The Adafruit (Arduino) code:

> #include <Wire.h>
> #include "RTClib.h"
> RTC_DS3231 rtc;
> void loop()
>{
>     rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
>     DateTime now = rtc.now();
>     Serial.print(now.year());
>     Serial.print(" ");
>     Serial.print(now.month());
>     Serial.print(" ");
>     Serial.print(now.day());
>}

The output is:

2165 165 165

The Maxim datasheet says this about the VBAT line which is the line between the DS3231 chip and the missing backup battery:

  Backup Power-Supply Input. When using the device with the VBAT input
  as the primary power source, this pin should be decoupled using a
  0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required.
  If VBAT is not used, connect to ground.

So I connected it to ground and it makes no difference. I can't buy a battery until tomorrow morning. Can somebody please confirm that the backup battery is actually essential. EDIT: I installed a battery and it makes no difference.

Aside: A good reason for not having a backup battery if possible is to have fewer user serviceable parts.

The problem was a bad connection for one of the serial lines.

I found the solution at this link.

The battery is not necessary to make this work.


I think I can see the problem - although I have no way to test it.

According to Wikipedia:

  When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.

Here's my attempt at your loop() which I hope will at least get you started:

void loop()
{
    // Wait for strobe to go LOW, indicating a character is ready
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };

    // Strobe is now LOW - a character is ready.
    // Pull BUSY to high
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, HIGH);
    digitalWrite(led, LOW);
    digitalWrite(nAck,LOW);

    // Print the character
    ProcessChar();

    // Return BUSY to low again
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, LOW);
    digitalWrite(led, HIGH);
    digitalWrite(nAck,HIGH);

    // Wait for the strobe to go HIGH again
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };
}

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state.  I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.


compare char receive from Slave writer to Master reader with I2C Im trying to send data from slave (writer) to master (reader) then compare it to declared 'char p[]' to turn on the lights but somehow i cant make it work.

////master reader

    #include <Wire.h>

int LED = 13;
char p[] = "YES...";

void setup() {
  pinMode(LED, OUTPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

}

void loop() {
  Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c= Wire.read(); // receive a byte as character

  Serial.print(c);         // print the character

  if(c == p){

  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)

    }else{

  digitalWrite(LED, LOW);   // turn the LED on (HIGH is the voltage level)

          }

  }

  delay(1500);

Slave

//////////////     Slave       ///////////////////////

    #include <Wire.h>

const int pingPin = 8; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 9; // Echo Pin of Ultrasonic Sensor

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8

}

void loop() {
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(1500);

if( inches <= 4){

  Wire.onRequest(requestEvent); // register event
   Serial.print("Obstacle detected");
   Serial.println();
  }
  else
  {

  Wire.onRequest(requestEvent1); // register event
   Serial.print("Nothing Detected");
   Serial.println();

    }

}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {

  Wire.write("YES..."); // respond with message of 6 bytes
  // as expected by master
}
void requestEvent1() {

  Wire.write("NO...."); // respond with message of 6 bytes
  // as expected by master
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

Improve you indentation.
If you want to compare two strings use strcmp function for that.
Your master part has some brackets left in your void loop() function, correct them.
In I2C you are receiving one byte at time. You should receive data till the last byte in received.
You should have some identification in your message, which is you are sending from slave to master indicating that this is last character. It helps you come out of Data reception loop in Master side.


TSX0108 logic level converter not working Am trying to setup logic level converter with arduino for eps8266 WiFi module. Am using this logic level converter but it’s not working not sure what am doing am not getting any output.

My circuit

Red wire : 3.3v power source
Orange wire : 5v power source
Blue wire : ground.
Yellow wire : arduino TX1 on B2
White wire : output on A2

Multi meter it red wire : 3.3 v showing on display

Multi meter it orange wire : 4.68 v showing on display

Multi meter it yellow wire : 4.36 v showing on display

**Multi meter it white wire : no voltage showing on display ??? **

Update : have set OE pin to enable and swapped red and orange. Still no output for yellow wire

When the output-enable(OE) input is low, all outputs are placed in the high-impedance (Hi-Z) state.  You must connect the OE pin to logic high to enable the outputs.


How can I get ultra clean dc wall power for my arduino project? I'm doing an rfid project that requires a read range of at least 5 inches or about 13cm.  I'm using a nano with a usb port, a rfid reader from priority 1 design and a large antenna. The problem I'm running in to is that when I power the project from the usb port I get a pretty decent read range of 11-13cm. But when I power the project from a DC power supply the read range drops considerably.

After a lot of testing with various power supplies I believe that all my power adaptors are dirty enough to cause rf interference and reduce the range.  Powering the project with a 9v battery and a 5v power regulator gives me really good range: 18cm with the largest antenna.  But I need plug in power.

So how can I power this project in a way that gives me ultra clean power?

I tried that same 5v regulator with a 5v adaptor and still had short read range.
Someone suggested adding a smoothing capacitor between V+ and Gnd but I wouldn't know what size.  I'm not an EE - I'm just a coder with a soldering iron.
Is there a better power supply I can get?

[EDIT] Also just FYI, when I connect even only the ground wire the the computers USB port I get a much farther read range. So..

Could it be a case of needing to ground the circut better as the switching power supplies only have 2 prongs and probably no real "ground". (Or am I making stuff up?)

[EDIT 2] What about a rechargable situation where my wall adaptor keeps a litium charged and the litium supplies clean power to the circuit?

Also I now know that I can charge my whole circuit with anything from 5 to 12 volts. In fact it would be better to have more in the 7 to 12 range than strictly 5v.

[UPDATE 3] Since this project is in my wall I was able to ground essentially to "earth" and that cleared up the noise. See this question as well: https://electronics.stackexchange.com/questions/230024/grounding-dc-project-to-clean-rf-noise

This is what I use, although admittedly not in your application. I run it from a 12V wall adaptor and adjust the output voltage to suit my requirements. The input should ideally be at least a couple of volts above the output(depends on current and temperature at 25degC and 20mA it's > 1.6V and 1.5A at the same temp it's > 2.7V).

Another alternative if you want to really go to town would be to repurpose an old computer ATX or similar PSU. There are plenty of guides out there and it's a straightforward job.


Set Arduino digitalRead reference voltage I wanted to know if the reference voltage for the digitalRead() function could be set to a particular voltage, either with an external reference or internally.

In the Arduino reference under the constants heading they have mentioned that they use 3V as reference for the boards I'm using (an Arduino Uno R3). But I want to change it to be a little lower.

Is it possible and if so how?

You could try not digitalRead, but analogReadVoltage. Analog Read Voltage

From Arduino examples:

/*
  ReadAnalogVoltage
  Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

 This example code is in the public domain.
 */

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}


How to implement elapsed millis as the timer for my motor spinning time? I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

#include <elapsedMillis.h>
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{

  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);

   lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");

}

 void loop()

{

  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");

  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
   lcd.print("sec");

  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");

   if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
        && stage3time > 0 )

   {

    if(timeElapsed <= 1000*stage1time)

    {

     myservo.write(stage1speed);

     }

    if(timeElapsed <= 1000*stage2time)

    {

     myservo.write(stage2speed);

     }

    if(timeElapsed <= 1000*stage3time)

    {

     myservo.write(stage3speed);

     }
  }

}

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
           int value = atoi(buffer);  // Convert to an integer
            break;
        }

    }
    return atoi(buffer);
    }

delay() is only the tip of the iceberg. The problem with delay() is
that it is a blocking function: nothing else can be done during the
delay. If you want to control your motor and at the same time be
responsive to the user, you must avoid blocking your program. This means
not only getting rid of delay(), but also getting rid of any blocking
function.

Here your problem is on getTheNumber(). This function blocks until the
user is done typing the number. Try to rewrite it in a non-blocking
fashion. For example, it could return -1 on every call as long as the
user is not done typing the number. On the first call after the user is
done it would return the valid value. If you manage to write everything
non-blocking, then you loop() will restart very often, and the program
will work with no significant latency.

As for managing the servo stages, simplest thing  would be to write a
finite state machine. I would write it with four states: IDLE,
STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 →
IDLE would be time-based, using the elapsedMillis object to track the
time spent in each state. The transition IDLE → STAGE1 would be
triggered by the user input.

static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
switch (state) {
    case IDLE:
        if (userRequestedToStartAgain()) {
            myservo.write(stage1speed);
            state = STAGE1;
            timeElapsed = 0;
        }
        break;
    case STAGE1:
        if (timeElapsed >= stage1time) {
            myservo.write(stage2speed);
            state = STAGE2;
            timeElapsed = 0;
        }
        break;
    case STAGE2:
        if (timeElapsed >= stage2time) {
            myservo.write(stage3speed);
            state = STAGE3;
            timeElapsed = 0;
        }
        break;
    case STAGE3:
        if (timeElapsed >= stage3time) {
            myservo.write(idleValue);
            state = IDLE;
        }
        break;
}


OV2640 with 18 Pins - No XLCK System Clock I'm trying to connect an OV2640 camera module to a microcontroller.

This camera module has only 18 pins as seen in this schema:
https://imgur.com/a/SGpfrXt

Here an image of the module:
https://imgur.com/a/7MOIDwi

These pins are on the module:

3.3V
GND
VSYNC
SCL
SDA
HREFF
D0 - D7
DCLK
PWDN
NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.

I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.

Could anybody help me connect and get a signal?

In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS.
Regards


No Matching Function for call to Ultrasonic:Ultrasonic(int,int) Good Day! I am trying to code the distance of Ultrasonic Sensor but the problem is it gives me this error. Any idea? Please help.

#include <Ultrasonic.h>

// HR-SC04 SENSOR
#define TRIGGER_PIN   5
#define ECHO_PIN      6

Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

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

// Global variables
int lastDistance = 0;
int thisDistance = 0;

void loop()
{
  // Copy over last distance
  lastDistance = thisDistance;

  // Get new this distance
  thisDistance = ultrasonic.Ranging(CM);

  if (outlierCheck(lastDistance, thisDistance)) {
    Serial.println("Outlier found: " + String(thisDistance));
  } else {
    Serial.println(String(thisDistance) + " cm");
  }

  delay(10);
}

// Check for significant jumps and outliers in sensor reading
bool outlierCheck(int lastDistance, int thisDistance) {

  // if the difference between measures is greater then 20cm, outlier found
  if ((lastDistance - thisDistance) > 20) {
    return true;
  } else {
    return false;
  }
}

You are very likely to have confused the libraries.

When using your code with the library at https://github.com/JRodrigoTech/Ultrasonic-HC-SR04, the code compiles perfectly fine. The constructors match up with your code.

//Constructor 1
Ultrasonic(int TP, int EP);
//Constructor 2
Ultrasonic(int TP, int EP, long TO);
//methods.. (used in your source)
long Timing();
long Ranging(int sys);

I think you have installed this Ultrasonic library: https://github.com/ErickSimoes/Ultrasonic. It has the same header file and class name but the class is constructed differently

//Constructor 1
Ultrasonic(uint8_t sigPin) : Ultrasonic(sigPin, sigPin) {};
//Constructor 2
Ultrasonic(uint8_t trigPin, uint8_t echoPin, unsigned long timeOut = 20000UL);
//Note that a constructor with only 2 arguments is not directly visible

You should go into the Arduino IDE and uninstall your current "Ultrasonic" library from the library manager. Then download the zip file from the first given github repository and add that ZIP file to your libraries.

Alternatively of course, you can use the second library and its correct example code.

Also note that your Arduino IDE 1.0.6 is extremely outdated, current one is 1.8.5


Serial characters are corrupted I try to send an "a" string via serial with

Serial.println("a");

and I receive "Oy=" in Ascii or {4F}{79}{3D} in Hexa.

Where should I start investigating? What could be wrong?  Baudrate is 9600 on all sides.

PS: I suspect the cable. Any hints how to check it?

On your setup function

Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
while(!Serial);//<-- wait for Serial to be ready

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates


How to move a servo quickly and without delay function Im trying to move a servo from one place to another while using the typical for loop you find in the servo's library example.
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
  servo1.write(pos1);
  delay(15);
}

for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
  servo1.write(pos1);
  delay(15);
}

The thing is that while this does work, I want to be able to move the servo a little quicker but I cant use the delay function because of some connectivity issues with another library named BLYNK. How could i move the servo from lightOFF to lightON the quickest way possible without the delay function? Sorry for my grammar i'm not a native english speaker. Thank you!

The quickest way possible from LightON to LightOFF is simply servo1.write(lightOFF); without loops or delays, in one go; no need to do it degree by degree. For example:
int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1++) {
  servo1.write(pos1);
  delay(15);
}

servo1.write(lightOFF);

If you want it to move a few degrees every loop and do other things in the loop while it moves, you can time it with millis() instead of delay(). The code below should move the servo 5 degrees every 0.5s:
int moveTime = 500; // Move every 0.5s
unsigned long int startMillis = 0;
int position = lightOFF;
int step = 5; // Move 5 degrees

void loop() {
  if (millis() - startMillis >= moveTime) {
    servo1.write(position);
    if (position <= lightON) {
      position = position + step;
    }
    startMillis = millis();
  }
  // Do other things
}

Untested and incomplete, but you get the idea.


Why is this failing after 3 iterations? I simply cannot figure this out, why is this failing after 3 iterations? Other than that, what better way is there to do this? Thanks!

#define rotary_encoder_topic  "/rotary/encoder"
#define remote_button_topic  "/remote/button"
#define remote_2x_toggle_topic  "/remote/2xtoggle"
#define rotary_button_topic  "/rotary/button";
char* devices[] = { "ledrpi", "lamprpi", "mediaroom" };
int currentDevice = 0;

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

void incrementCurrentDevice() {
  currentDevice++;
  if (currentDevice >= sizeof(devices)) {
    currentDevice = 0;
  }
 Serial.println(concatenateChars("Switched device to: ", devices[currentDevice]));
}

char* concatenateChars(const char* one, const char* two) {
  char result[150] = "";
  strcat(result, one);
  strcat(result, two);
  return result;
}

void loop() {
  Serial.println(concatenateChars(devices[currentDevice], remote_2x_toggle_topic));
  incrementCurrentDevice();
  delay(1000);
}

As Jaromanda X pointed out in the comments, sizeof(array[0]) (size of first element) will not return the size of the literal strings, but the size of a char pointer.

It doesn't work (whatever that means for you), because sizeof(devices) doesn't return the number of entries in the array, but the size of the array in bytes, e.g. something like (following is wrong: 24 (1 byte per character plus 1 byte with the concluding null character for each string) ) 6 (The size of a char pointer is 2 bytes on most microcontrollers; I'm not sure, if this is the same for Node MCU). So after 3 iterations (which can use the string literals in the array) currentDevice doesn't go back to zero, but counts further. With the access to the array with exceeding index you are accessing memory, that doesn't belong to the array anymore (e.g. random data).

There is no native function, that gives you the length of an array. But it can be calculated with sizeof(array)/sizeof(array[0]), which is the size of the array in bytes divided by the size of one element in bytes. In your case you would have an array size of 6 and an element size of 2, resulting in a calculated element count of 3, which is correct.

Another simple solution, which is easier to understand for beginners, but not as flexible, is to set a constant or define, that contains the size of your array. You can then use it in your code, whenever you need the size, including, when you define the array.


Controlling multiple fans using arduino uno I'm kind of new on the field of Arduino. Although I have a question concerning multiple fan connection on 1 arduino PWM pin. The goal is to connect around 8 to 16 fans on 1 arduino  pwm header pin and control their speeds separately using a potentiometer. As I seen it can be achieved by using transistors. The question is are there any limitations on how many fans can I connect and control seperatly using tranzistors? Can I for example use 16 transistors and control 16 fans seperatly ?

Thank you for your answers in advance

One PWM pin can control only one fan (or one group of fans). You can't have one PWM pin outputting different values to different fans, since one pin can only have one value. (Yes, there are ways of multiplexing it through time slicing but that is both hard and not a good idea).

You need one PWM per fan if you want individual control of each fan's speed. That means a maximum of 6 fans on an Arduino.

To get more you would either have to use software PWM (which can introduce jitter which may not be a problem with simple fans), or an external PWM controller.  Or add more Arduinos.

If all you want is potentiometer control of the fans you can do it without using an Arduino. A pair of op-amps (it can be a single dual op-amp chip), one acting as a triangle wave oscillator, and the other as a comparator, will generate PWM for you.  Here's an example:

  Image by ElectroBOOM (watch his videos sometime, they're hilarious)


Which GSM-shield is most efficient for GPRS communication? I tried Google, I tried a bunch of forums and I searched here. This question needs a final answer:

Which GSM-shield is most efficient for GPRS communication?

Since Arduino is the amateurs best friend for home automation and IoT, an "efficient" shield has a very low power consumption.

I am currently developing a system that collects some data from different sensors at a place far, far away, with limited access to power (e.g. it has a very small solar panel and a battery). It is also in pocket-size which makes a car battery a bad option.

Anyway, this specific device reads these sensors every 20 minutes, and if there's a deviation since the previous reading it starts the GSM module to send the new data to my API.

SMS and call features are of absolutely no interest at all.

Since these GSM-power-absorbing-current-eating-devils really like power I must think outside the box and compare different alternatives. So besides the primary question in this post, is there any way you can limit the power consumed, for example by limit the connection speed or anything like that? I'm using a M590 module at the moment, and that beast can eat around 2A if it's hungry.

Thanks in advance :)

GSM, by its very nature, is power hungry.  Even the most "efficient" one will blow your power budget many times over.  Since everything on GSM goes down the same digital transmission channel there would be no real difference between one with call and SMS and one without. It's all just data at the end of the day.

That said, the most efficient GSM module is one that consumes absolutely now power. And that is, at least for most of the time, perfectly possible.  By making the Arduino control the power supply to the GSM modem it can be literally turned off until an update is needed to be sent. Worst case that is on for maybe a minute (give it time to register on the network and what have you) and then off for 19 minutes. That's only on for 5% of the time - less if there isn't a change since the last time, of course.


Arduino measuring high-voltage electric fence I would like to know if someone has experience with measuring high voltages using an Arduino.
I know you can use resistors to lower the voltage, however.
I want to be able to measure the pulses of an electric fence used to prevent farm animals from escaping. These pulses are high-voltage and will not always be a similar voltage. I want to read these voltages, to scan for differences.
So, I wondered if someone has done something like that, and if the Arduino gets weird when it gets a voltage above 5V at a low amperage on its analog port.
--here some possible solutions for those wanting to know the answer--
-mostly based on comments and answers below-

Using resistors as a voltage divider while keeping an eye on the maximum spark gap distance and capacitive coupling.
using a transformer/coils to reduce the voltage.
using a high voltage probe to measure it.
using neon bulbs or other light sources to measure it.
charging a capacitor and measuring discharge time with high resistance(only works for the total power)

-this list is meant as a summary of what is discussed further ideas and solutions are still welcome-

You are talking about measuring 2kV to 10kV pulses, with about 1J to 5J of energy per pulse.
The maximum current may be very low, but the voltages you want to measure are very high, and will very probably damage your Arduino without proper measures.
You will at least need a voltage divider to reduce the voltage the Arduino sees to 5V (or 3.3V for some Arduinos) to be able to make a measurement with the Arduino's ADC.
The voltages are high enough to bridge a fair distance with a spark; they could well bridge a physically small resistor or the distance between two connections on your breadboard or PCB.
To be honest, I think you shouldn't go anywhere near such voltages with an Arduino, unless you know exactly what you are doing when preparing the signal for an Arduino's ADC pin.


How to flash a NodeMCU (ESP8266) with an external FTDI programmer? Hi my USB to UART bridge (CP2102) seems to be broken on one of my NodeMCU Dev Boards with ESP8266.
It seems to be just that specific board since all other boards that I have can be flashed without problems.
I have a FTDI Programmer like this one:
FTDI Programmer
Now I would like to flash the Nodemcu using the FTDI programmer but I'm not sure how to wire it up.
I know that those programmers cant power up the ESP8266 by itself thats why I would use a micro USB cable that doesnt have a data wire to power up the nodemcu.
This is how I would wire everything up:

Is this the correct way to wire up the programmer with the nodemcu? I want to be sure that nothing is going to mess up with the nodemcu or the programmer.
NodeMCU       FTDI
GND    ---->  GND
RX     ---->  TX
TX     ---->  RX

Assuming your FTDI Basic is the 3.3V version, then yeah that will work fine provided you that manually reset the board yourself and enter the boot-loader using the buttons.
If you're independently powering the boards you may want to insert some series resistance in the RX and TX connections in case your signal receiving end is not powered while the sending side is.  In short you don't want the TX signal from one of your devices (boards) trying to power the receiving device (board) through its protection/clamp diodes.
In regard to comment about resistor value:
The value of the resistor depends on what you can get away with in terms of its effect on the signal and how much current is allowed through the clamp diodes on the other board.  A couple of Kbyte is probably sufficient, better than nothing in any case. Use a bit more if you can and still get a reliable signal through.  If you have the boards both powered before you connect them and you're careful about connecting them, then there's no opportunity for that.  It may also just be that they're robust enough that you don't need them at all.  I usually put some in though.  The second reason which I didn't state above is just that it protects you from being outright stupid and accidentally connecting them to the wrong thing; wrong signal, or to VCC or GND on the other side.


Arduino digitalWrite 1 or 0 instead of HIGH or LOW Is it ok to use

digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH)

or

digitalWrite(pin, 0) instead of digitalWrite(pin, LOW)

I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way

digitalWrite(pin, EEPROM.read(1))

Yes, that is fine.  LOW is 0 and HIGH is 1.  digitalWrite() sets the output to off if it receives a 0 and on if it receives anything of 1 or more.

That means that these are all equivalent:

digitalWrite(pin, HIGH);
digitalWrite(pin, 1);
digitalWrite(pin, 69);

It's especially useful when you are examining a variable for, say, a certain bit being set:

digitalWrite(pin, bytevar & 0x80);

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.


Problem with connecting pins on an Arduino board with an L239D shield I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?

PS: I have the same board as shown in the picture

That's a common problem that has many solutions.

The cheapest way is to solder the wires directly as many comments said. Though this is quite dirty, it should work for you.

The more professional way is to use these Arduino stackable header. They can even let you have a shield on top of your shield. This is the best choice in my opinion.