How to solve the white blocks on LCD keypad display? I have just bought my first Arduino (a Mega 2560 R3 clone by ELEGOO), and I got a cheap LCD display to go with it. I cannot for the life of me get it to display anything other than a row of white blocks (although I uploaded a different sketch that I change the numbers of one of the ports and now it shows the top 3 blocks of the second row as white as well).

When I read the notes on the example LCD sketch "Display" it says the following:

The circuit:

LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD VCC pin to 5V
10K resistor:
ends to +5V and ground
wiper to LCD VO pin (pin 3)

However, when I plug my display into the Arduino the pins don't seem to go into the same ports and there is no other way of fitting it in. For reference my pins go:

LCD - Mega2560

 VSS - AREF,
 VDD - GND,
 V0 - 13,
 RS - 12,
 RW - 11,
 E - 10,
 D0 - 9,
 D1 - 8,
 D2 - 7,
 D3 - 6,
 D4 - 5,
 D6 - 4,
 D7 - 3,
 D8 - 2,
 A - 1-TX,
 K - 0-RX,

 RST - RESET,
 5V - 5V,
 VIN - VIN,
 A0 - A0,
 A1 - A1,
 A2 - A2,
 A3 - A3,
 A4 - A4,
 A5 - A5,

I am not sure what to do any assistance you can provide would be greatly appreciated.

Liam

The words you use to describe the parts of the display and which sketch you are using need to be more precise.

Regarding the part you linked to in your question, the dark blue part is the LCD (Liquid Crystal Display).  Not many buy just this part.  It is too hard to use.

Under it is a green board with the commonly found Hitachi LCD Controller.  This is what most people buy and call the LCD. Many Arduino sketches are written for the Hitachi LCD Controller. While you could connect this type of board directly to an Arduno, you would have to make a special cable which must follow the pin assignments in the particular sketch you are using!

Finally, the darker board beneath the green board appears to be an Arduino shield.  Normally Arduino shields adapt what ever circuit happens to be upon the shield to the Arduino Uno pins and form-factor.  However, again, you mush use a sketch which which follow the pin assignments for the particular shield!

Armed with this knowledge, you should be using/looking-for a sketch specific to your Arduino shield. I suspect you are using the wrong sketch and this is resulting in "white blocks" on your LCD display.

Other considerations:

It is possible your contrast in incorrectly set.  Identify if this control is available on the shield you are using and consider adjusting it.
Is the shield plugged in correctly?  Check to make sure all the pins are connected to the Arduino.  Most shields are designed specifically for the Arduino Uno form factor.
If you are still having problems, consider buying everything (the Arduino Uno and the LCD shield) from one specific well known vendor which can supply support through direct contact or forums.  Usually a good vendor will provide support especially if they provide all parts of a project.

Other approaches:

You should find a sketch which works with your LCD & Buttons Arduino shield.  However, as you have figured out the paths between the Arduino and the Hitachi like LCD Module you might try using the LiquidCrystal Library.  When this library is instantiated, the pins of the Arduino which are to control the Hitachi like LCD module are passed as arguments.  Using the information in the question, it is likely the instantiation should look similar to this:

LiquidCrystal(12, 10, 5, d5, 4, 3)

...Note, you are missing "d5" in your question.  So the above is likely not correct.  Also, from your description, the Arduino appears to control contrast ("V0" pin) for this shield.  As the LiquidCrystal library does not appear to support this, you may need to create additional code to control contrast.


Getting 0 cm from ultrasonic sensor when nothing is in front My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:

Ping: 144cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 105cm
Ping: 105cm
Ping: 94cm
Ping: 0cm
Ping: 378cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 106cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 250cm
Ping: 0cm
Ping: 108cm
Ping: 0cm
Ping: 108cm
Ping: 0cm

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:

#include <NewPing.h>

#define TRIGGER_PIN  A5
#define ECHO_PIN     A4
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

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

void loop() {
  delay(1000);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Because  of these 0s my robot is making turns which are not expected.

Any idea why this might happen ?

The documentation for the NewPing library states:

  Constructor

NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

  max_cm_distance is optional [default = 500cm].

Then:

  sonar.ping_cm(); - Send a ping, returns the distance in centimeters or
  0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.

Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.


Android, Raspberry, Atmega, SQL communication Hej there,

I have a small project at home and I'm curious if people have some advice/idea for me. Because I'm not sure if the communication between the different devices is the way to go.

This is my current setup:

I have a Android application running on an Android device (tablet). This Android device can communicate with a MySQL server with a json/PHP. The Android device is receiving data from the database but also writing data to it. The MyQL/web server is running on a Raspberry.

The second device is an atmega328p microcontroller(http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126) that is sending temperature/humidity to the MySQL server on the Raspberry. The ATmega is communicating through a 433 MHz chipRF(MX-05V). The Raspberry also has a 433 MHz chip RF(MX-05V) that is receiving this data and writing it to the MySQL server.

So actually the ATmega is communicating with the Raspberry and the Raspberry is communicating with the MySQL server.

It is working properly but I'm not sure if this is the way to go. So my question, what are you thoughts of this setup, what would you do different and why?

Thanks, Matthijs

If I understand correctly:

You have a Pi hosting MySQL and a web server.
A Mega writes temp/humidity data to the server.
An android device reads data from the web server.
The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go?
What you have is a tried an tested design, a central server responsible for collating at serving the data.  My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that.  What happens if you want to add a second Mega to report a different sensor?  You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more.  I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.

You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.

But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.


Cannot compile code from Arduino WIFI shield example I'm trying to launch the piece of code in this Wifi example:
https://www.arduino.cc/en/Reference/WiFiConfig
via Arduino.cc online editor, but I'm getting those errors:

/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:87:24: error: 'PINS_COUNT' was not declared in this scope

and

/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:97:15: error: 'NINA_GPIO0' was not declared in this scope

Do someone has an idea of how to solve this?

Those kinds of errors are usually caused by the selection of an incorrect hardware in the IDE.

Choosing a correct board in the IDE will solve the compilation issue.

Since you said that you used the Arduino.cc online editor, I pasted your code into the editor.

You did not say which Arduino board or which WiFi module you are using, so I chose Arduino Uno WiFi board as a starting point.

Compiling the code produced the same errors as in the post.

Next I chose Arduino Uno WiFi Rev2 board, and compiled without errors.


Sending Analog Data with and IR LED This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.

Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.

[EDIT]

This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino with IR and not anything else.

Seems to me you first need to establish a protocol.  Could just be a simple one you make up,  with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...

As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.

Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.

But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.

Thinking about it there must some libraries out there already.
Or entirely completed projects to study.

Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.


Mixing analog reads with raw port reads I'm reading two digital inputs and one analog input. For [reasons] I must use A0 and A1 as digital ins, and A2 as an analog in.

I'm uncertain about how the Arduino hardware deals with mixing analog and digital inputs on the same port. For speed, I'm reading like this:

 uint8_t raw = PINC;
 boolean digitalA = (bool)(raw & 1);  // read A0
 boolean digitalB = (bool)(raw & 2);  // read A1
 int analogC = analogRead(A2);

Will the raw reading of the port interfere with the analogRead in any way? I did see a caveat about mixing A & D, but it only had to do with noise introduced in the analog ins when doing digital outs. Would reading analog first minimize that?

What you are trying to do is perfectly safe. In fact, you reading PINC
will have no effect whatsoever on the input circuitry. You are just
reading an I/O register and, whether you read it or not, this register
is updated on every clock cycle from a set of comparators that monitor
the pin voltages.

Just for completeness, I should mention that it is possible to disable
the comparators that update the register. The Atmel datasheet recommends
to disable them if you want the lowest possible ADC noise. If you follow
that recommendation, then reading PINC will just return zero. The
Arduino core library does not disable them: the input comparators are
thus always active, and you can get a meaningful value by reading that
digital input register.

Edit: You can selectivly disable the input comparator on the pin
A2 by issuing DIDR0 |= _BV(ADC2D);. But that is only useful if you
really need to maximize the accuracy.


MEGA 2560: Simple program - One analogWrite turns off the other I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)

I have an Arduino MEGA 2560 and a red LED connected to pin 4.

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  0);
  analogWrite(RED,  100);
}

void loop() {

}

This code lights up the red LED.

However, when I write 1 to the GREEN pin analogWrite(GREEN,  1), the red LED goes off. I'm expecting the red LED to stay on.

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  1);
  analogWrite(RED,  100);
}

void loop() {

}

The red LED stays on when both written values are the same, e.g.

  analogWrite(GREEN,  25);
  analogWrite(RED,  25);

I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.

#define RED 4
#define GREEN 2

void setup() {
  // GARBAGE BEGIN ===
  unsigned long t = millis();
  const unsigned long period = 10;
  float progress = float(t % period)/period;
  float r = progress * 0;
  // GARBAGE END ===

  analogWrite(GREEN,  100 + r);
  analogWrite(RED,  50 + r);
}

void loop() {

}

Update: Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to __attribute__((optimize("-O0"))) void setup() { fixed the issue. -O1 also works, but -O2 fails.

As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line

 void setup()

with

 void setup() __attribute__((optimize("-O0")));

// also -O1 works the default -Os and -O3,-O4 not

Actually the problem is not the IDE version but the included AVR boards package version.  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.


Print unsigned long long in ESP8266 I need to print an unsigned long long variable:

unsigned long long t = 1559072327000ULL;

I have tried the following:

Serial.println(t); // call of overloaded 'println(uint64_t&)' is ambiguous

char[18] buf;

sprintf(dt, 18, "%lu", t); // Prints 4294165848

snprintf(dt, 18, "%lu", t); // Prints 126

vsnprintf(dt, 18, "%lu", t); // cannot convert 'uint64_t {aka long long unsigned int}' to '__gnuc_va_list {aka __va_list_tag}'

Any suggestion?

Okay, I figured out... this two prints the right number:

sprintf(dt,"%llu", t);
snprintf(dt, 18, "%llu", t);


GSM library , sendSMS, string instead of char I used the GSM library that comes together with arduino 1.
Specifically the sendSMS part.

I managed sucesfully to send SMS.

Now the thing is, inside this library the SMS to send is stored in a char variable:

char txtMsg[200];

My question is, are you able to send the SMS, but store the message not in a char variable, but as a String?

I would test it myself but now i only have one SIM card, and for some reason my network is blocking it (that is another thread to be started btw)

OK, i found access to SIM card and tested this myself.
I can confirm it's working!

So, if anyone wants to use the standard GSM library for SMS, you can use both chars and strings.


Powering an Arduino with more than 5 V Last time, when I supplied 12 V from a power supply to the Arduino's 5V pin, it blew up. This time I'm going to use an adapter. Why does an adapter with a 12 V input not blow an Arduino up, as in the previous case?

Or, should I have supplied 12 V to Vin pin, instead of the 5 V pin?

Edit: Sorry for saying 12V input, it is written 12V output and I meant a power adapter that is plugged into wall.

First of all you should read the tech specs for Arduino Uno here:
https://www.arduino.cc/en/Main/ArduinoBoardUno

You will find this important information about power supply:

Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limit)   6-20V

From documentation also:

Vin. The input voltage to the Arduino/Genuino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

5V pin.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So answering you question: yes you should have supplied 12v on Vin. Not on 5v.

  Why does an adapter with 12V input not make the same blown up for arduino like in the previous case?

Because you are pluging 12v in the correct input, the 7-12v jack.

Another important link to read:
http://playground.arduino.cc/Learning/WhatAdapter


Is there some better documentation somewhere for Arduino classes and API's? For example, it looks like Serial extends HardwareSerial, which extends Stream, which extends Print. But I don't think you can figure this out by reading the reference documentation on https://www.arduino.cc/ and it doesn't appear that you can easily navigate the class hierarchy in the Arduino IDE. They seem to go out of their way to hide the class hierarchy?

I guess I'm spoiled by modern languages that have automatically generated documentation, but it seems like there should be a more complete reference somewhere?

What I did/do when loading a new core is generating a doxygen visualisation help class hierachy in HTML. Although most of the core libs have no detailed doxygen documenation the dot/graphviz solves the problem without installation of other IDEs (which also have their specific problems, or need a lot of learning). As an added bonus I can document my source code in a clean and transparent way available in most IDEs and OS.


Does setting a value always mean setting a Arduino pin? One thing that always confused me was why we use int or other commands to set the variables to have pin numbers as if those commands were always restricted to pin numbers only. For example
int ledPin = 13;

Does putting a random number in place of 13 that isn't a pin number cause an error? Right now I haven't checked yet.
I've only begun to realize that if you want to use variables in relation to pins or push buttons you have to set values first and then do associated functions like digitalRead. The commands like int are not like in other programming languages where you can set any values and do mathematical computations. I know it might seem obvious to someone who is used to Arduino, but this perspective is something that helped me grasp things better. Before that, I totally could not understand how things worked because of being confused with how int or other similar variables worked.

Note that this is just a C/C++ integer declaration, assigning a value to a variable, like any variable (irrelevant if it is for pin numbers).
You don't have to use a variable, there are similar variations:
Variable
int pinNumber = 13;

in begin:
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, HIGH);

Const
Preferably I like to use a const:
const int PIN_NUMBER = 13;

Or even better, since it always is a low value:
const uint8_t PIN_NUMBER = 13;

And use it with capitals.
pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

#define
#define PIN_NUMBER 13

pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

The reason variables are used, is that when you want to use another pin number, you only need to change it in one place, making the sketch better maintainable/adaptable.
I don't know what happens when you give an illegal number (you can try it out yourself).


Using Arduino UNO as FTDI so , just bought some pre-bootloaded ATmega328(p/pu) to which I need to upload sketches on a breadboard using uno TX and RX pin as FTDI
Here is what I am to do.

I connected Uno GND and Reset .

Arduino Tx to Standalone Atmega Tx

Arduino Rx to Standalone Atmegaa Rx

Connected Crystal , capacitor to standalone pin 9, 10 (XTAL) then grounded it with 2 coupling capacitor.

Standalone vcc to arduino 5v
Standalone GND to Uno GND

Is it possible to do what I need to or i need to buy some USB to TTL devices from the Amazon again?
Thanks for your precious time...

https://youtu.be/EoHD0m3uUhA. Ig this should do it. There are many more tutorials on YouTube to achieve this.


Arduino Ping sensor with NewPing library I was trying out the NewPing library (the main example sketch) and when I compile it and check the serial monitor, it seems like it works for about 10 seconds, then instead of giving distance values it just writes out random characters. The only thing I can think of is that my sensor is bad. Any suggestions before I get another Ping sensor? I'm unsure if the same thing will happen.

The main example sketch has this:

  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

Your serial monitor is set to 9600 baud (bottom RH corner). Change that to match the setting in the sketch.


100 hz Square Wave of 50% duty cycle in digital pin 3 and verifying with pin 4 I am stuck on this for a while, I am trying to generate a 100 hz square wave with 50% duty cycle in pin 3 and trying to verify it with wire at pin 4; I am getting 64000 but not 100 in serial monitor.

#define LEDPIN 3

uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare
noInterrupts(); // disable global interrupts
// TIMER 1 for interrupt frequency 100 Hz:
cli(); // stop interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 19999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
//TCCR1A = 0; // Timer/Counter Control Register 1A
//TCCR1B = 0; // (both control registers need to be configured)
//// set compare match register to desired timer count:
//OCR1A = 15624; // Output Compare Register 1A (i.e., for channel A)
//TCCR1B |= (1 << WGM12); // CTC (Clear Timer on Compare Match) mode
//TCCR1B |= (1 << CS10); // for 1,024 prescaler; UNO has a 16 MHz clock
//TCCR1B |= (1 << CS12);
//TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable global interrupts:
}
void loop() {
uint16_t val = OCR1A/8;

ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3
//OCR1B = val/2 - 1 ; // 50% duty cycle for pin 4
//uint16_t val2= pulseIn(4, HIGH);
Serial.print(val2);
delay(1000);
Serial.print("\n");

}

You wrote:
uint16_t val2 = pulseIn(4, HIGH);

It makes no sense to call this here, as the timer has not been
initialized. You probably cannot expect anything but a timeout in this
context.
noInterrupts();
cli();

These two are synonyms. No need to repeat yourself. Actually, no need to
block interrupts at all.
sei();
interrupts();

Ditto.
OCR1A = 19999; // = 16000000 / (8 * 100) - 1

This is supposed to fire interrupts at 100 Hz. But if you want a
100 Hz output signal, you should fire the interrupts at 200 Hz
(two interrupts per cycle). Thus:
OCR1A = 9999; // = (16 MHz / 8) / (2 * 100 Hz) - 1

Then,
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

This is configuring Timer 1 for an external clock source. If you
want ÷8 prescaler, you should only set bit CS11. Check the datasheet.
uint16_t val = OCR1A/8;
ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3

This doesn't make any sense to me. Why are you setting ICR1? Why are
you changing OCR1A although it was already configured in setup()?
You can remove all this. Here is the loop() I used for testing:
void loop() {
    Serial.println(pulseIn(3, HIGH));
    delay(1000);
}

And it repeatedly printed 4955, which is quite close to the expected
value (namely 5000).


Can I power a LilyPad with an iPhone lightning port? I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.

If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.

If that's enough for you it could work.


Can one supply an Arduino Zero's VIN pin with 5v? The title pretty much says it all. I know that most Arduinos can do this, but I couldn't find very much information for the Zero. Any help would be very much appreciated.

Yes you can. If you look at the schematics on the Arduino website you can see that the 3.3 volt regulator is connected to the 5 volt regulator. That means that if you feed 5 volts straight into the 5 volt pin it will go through the 3.3 volt regulator to supply the main chip.
Note that this is going into the 5 volt pin not the VIN pin which goes into the 5 volt regulator and would thus require a higher voltage than 5 volts.


NRF24L01 Connection Not Working I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: diagram. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:

EDIT:
Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.

ATTiny Code

#include <avr/sleep.h>
#include <avr/interrupt.h>

// Routines to set and claer bits (used in the sleep code)
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(1000);
  setup_watchdog(6);
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop()
{
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= 5)
  {
    digitalWrite(4, HIGH);
    watchdog_counter = 0;
    payload = 123456;
    radio.write( &payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second
    delay(1000);
    digitalWrite(4, LOW);
  }
}

//Sleep ATTiny85

void system_sleep() {

  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System actually sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out

  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON

}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

Receiver Code

#define CE_PIN 7
#define CSN_PIN 8

#include <SPI.h>
#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

void loop(void){
  if (radio.available()) {

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.println(payload);
    }
  }
}

Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.

I was just researching the exact question and I have some bad news.

The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf)

Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.

There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.

Edit:
If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.


String generator not working as expected I'm trying to build a random string, save it to EEPROM as int, then read it back and output it.
If I give it a predefined string then it works fine. But Something is wrong with the random string generator.

  String output;
  char letter;

  String mystr=""; //"ABCabc123..";
  String characters = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz";
  String numbers = "0123456789";
  String other = "<>!.,()?|=&%¤#";

  // add random characters to empty string
  for(int i=0 ; i < 12 ; i++){
    mystr += characters[random(0, characters.length())];
  }
  // add two numbers, one other and two more characters
  mystr += numbers[random(0, numbers.length())];
  mystr += numbers[random(0, numbers.length())];
  mystr += other[random(0, other.length())];
  mystr += characters[random(0, characters.length())];
  mystr += characters[random(0, characters.length())];

  // loop the string and place one character in each EEPROM address
  for(int i=0 ; i < mystr.length() ; i++)
  {
    EEPROM.writeInt( i,mystr[i] );
  }

  // read the string back from EEPROM
  for(int i=0 ; i < 17 ; i++){
    letter = EEPROM.readInt(i);
    output += letter;
  }

If I run the code output will be "H". Every time.
If I use the predefined string "ABCabc123.." then it works correct.

What am I doing wrong with building the mystr?

Your first mistake is to use String. Don't. Instead use a char array.

char mystr[18]; // Room for 17 characters plus the NULL terminating character

Your string constants should also be char arrays, not String variables. And better to put them in PROGMEM:

const char characters[] PROGMEM = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz";
const char numbers[] PROGMEM = "0123456789";
const char other[] PROGMEM = "<>!.,()?|=&%¤#";

Now filling your target array becomes:

for(int i=0 ; i < 12 ; i++){
  mystr[i] = pgm_read_byte_near(characters + random(0, 50));
}

mystr[12] = pgm_read_byte_near(numbers + random(0, 10));
mystr[13] = pgm_read_byte_near(numbers + random(0, 10));
mystr[14] = pgm_read_byte_near(other + random(0, 14));
mystr[15] = pgm_read_byte_near(characters + random(0, 50));
mystr[16] = pgm_read_byte_near(characters + random(0, 50));
mystr[17] = 0; // Don't forget the NULL...

Your second problem is the use of EEPROM.writeInt and EEPROM.readInt.  Those are for writing integer values, not characters.  Instead just use EEPROM.read and EEPROM.write:

for (int i = 0; i < 17; i++) {
    EEPROM.write(i, mystr[i]);
}

Then to read back:

for (int i = 0; i < 17; i++) {
    mystr[i] = EEPROM.read(i);
}
// And don't forget to terminate the string...
mystr[17] = 0;


Can I close an input? I wan't to build a diversity controller similar to this one.

  A diversity controller is basically a circuit which detects the strongest RSSI Signal of multiple receivers and provides the data signal of that (the strongest) receiver.

As a receiver I use boscam RX5808 receivers.

This receiver can be switchen between 8 channals through a 3 bit output interface. The CH1-3 outputs are active high 5V which got to be pulled to ground.

Is it possible to put these receiver-outputs on an arduino digital inputs, to either put them on ground or not?

How exactly do I implement this in software?

When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground.  It's called a push-pull interface, and looks like this:

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.

They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.

So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.


Where can I get a high-quality ADC (audio digitizer) for Arduino? Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?

Does anybody know where I can find the best options for this?

You are going to need a bigger board.

(96000000 samples/second) * (32 bits / sample) ~= 3 Gigabits/second

A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.

While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.

The highest quality audio recording shield for Arduino I've seen is a modified Wav Shield that can record 8-bit mono files at 44,100 samples per second using the waverp library.


Arduino Pro Mini PWM issue I want to create a small LED strip driver/controller with 2 channels (Cold/Warm white) using Arduino Pro Mini (5V/16MHz). I have connected the parts per the following diagram
I have pins 5 and 6 setup as output, control them via analogWrite, and it all works great on Arduino UNO.
The problem comes with Arduino mini pro. When one channel is set to 255 and the other is 0, the LED strip does light only in one color, which is OK and when I swap the PWM channel's values, the other light color starts to shine. So far so good. When I set both to 0, the strip keeps on shining at about 30% (I don't have a scope, so I can't tell what the pwm signal is doing). Varying the channels' pwm in the range 0-255 does affect the light somehow but it never goes down to a complete off.
Looking at the arduino uno and pro mini I can't see anything obvious that should make them act differently from the hardware perspective so I'm guessing there's a problem in the libraries or perhaps my arduino pro mini (a clone) is somehow messed up.
Has anyone observed this kind of behavior in Arduino pro mini and has a solution for it?
Edit: Added some measurements per @Abel's request. I measured both DC and AC with and without the LED strip connected.
Connecting the LED strip really does mess things up, but WHY? UNO can handle it, but the pro mini can't! I thought mini was basically just shrunk down arduino uno (both have the same SMD version of MEGA328P), but apparently there are some differences.

Thanks to comments I received from several people here I quadruple checked the wiring and eventualy found the problem. My recent Arduino Uno tests were done on a breadboard, but I had the Pro Mini prototype soldered on the prototyping board which has the holes connected in columns on the copper side. I made the cuts in all the necessary places ... but one! That one omission caused a short between pin 6 and the drain from the other channel's mosfet. The problem with these boards is that the parts are on one side and while flipping the board to the copper side, it is too easy to get lost in all the columns and miss something.
The morales of this story are: "Never be too certain about your wiring/soldering" and "Arduino is pretty resistent to my attempts to fry it :)".


Read battery voltage from battery which is powering arduino I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?

I also use a lipo charging module to charge the battery.

Thanks for helping!

You can read the Arduino's supply voltage see here How to measure the supply voltage of Arduino without using an analog pin Alternatively use the internal 1.1V reference and a suitable voltage divider to read the lipo's voltage


Receive Signal from different circuit I am an mid experienced Programmer but I have no clue about electronic circuits. I want my Arduino to do sth if he gets a signal from an external source. The external source has 5V and is 0V or 5V and when it has 5V I want my Arduino to send me a Message, the Code for the Message is no problem, but please help me with the circuit:
The external source is independent and runs on battery and the device has a 2.5mm jack, normally there is an LED attached that lights up, but I want my Arduino to receive the signal. Are there any opportunities for realising this?
Thank you for your help

Unless there are exceptional circumstances you can just connect the two ground connections together. Then the 5V of your other circuit will be the same voltage as the 5V of the Arduino and you can just connect your signal direct to an input.

However, if there are exceptional circumstances (ground isn't really ground, for example) then you can use an opto-coupler to act like an optically-controlled button:

simulate this circuit – Schematic created using CircuitLab

R1 can be replaced by the internal pullup resistor of the Arduino by setting the pinMode to INPUT_PULLUP.

Note that this inverts the logic of the input: a HIGH input signal is detected on the Arduino as a LOW logic level, and vice versa.


Set control register to low in ds3231 rtc I have been using ds3231 rtc module for keep tracking and make alarm along with backup battery. when I used it for first time it worked fine. but now it doesn't keep track my time when the power lose it from main power but I have checked that my battrey is in safe. So I search in lot of forums they said EOSC bit was set high that would be stoped the clock as it stops the internal oscillator. also want to set it into low then only rtc keep track of the time
but in another some forums they instructed that put this following code for set it to low
DS3231 RTC;

  Wire.beginTransmission(0x68);
  Wire.write(0xF);                            // Address the Status register
  Wire.write(0x00);                           //  Zero the Status register
  Wire.endTransmission();
  Wire.beginTransmission(0x68);
  Wire.write(0xE);                            // Address the Status register
  Wire.write(0x00);                           //  Zero the Status register
  Wire.endTransmission();

  RTC.setA2Time( ADay, AHour, AMin, 0x00, true, false, false);
  delay(100);
  RTC.turnOnAlarm( 2 );

in another place showed the following code
// clear /EOSC bit to ensure that the clock runs on battery power
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x0E); // select register
  Wire.write(0b00011100); // write register bitmap, bit 7 is /EOSC
  Wire.endTransmission();

but now problem is that where should I want to place this code and how  to past it in proper manner for keep tracking the time when ds3231 loses power too? please any know about this problem because I finded so many people are strugling with this issue when they come forward to use this ds3231 rtc module. if any body know about how to solve this issue plese consider to share your idea this will definately help full for evryone because there is no one properly answer for this issue

I also have a DS3231 RTC in my robot project.  Here's my complete setup code.  This can be placed anywhere in setup():  I don't think you have to mess with individual registers to get what you want.
    if (rtc.begin()) //02/19/19 this now returns FALSE if RTC doesn't respond
    {
        Serial.println("Found RTC...");
        delay(100);
        bRTCLostPower = rtc.lostPower(); //added 10/17/18
        mySerial.printf("rtc.lostPower() reports %d\n", bRTCLostPower);

        if (rtc.lostPower())
        {
            Serial.println("RTC lost power.  Setting RTC to last compile time");
            rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
        }

#ifdef FORCE_RTC_TO_LAST_COMPILE_TIME
        Serial.println("Forcing RTC to last compile time");
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
#endif

        DateTime now = rtc.now();
        char buffer[100];
        memset(buffer, '\0', 100);
        mySerial.printf("Retrieving Date/Time from RTC with rtc.now() =  %ld\n", now.unixtime());
        GetDayDateTimeStringFromDateTime(now, buffer);
        Serial.print("Date/Time: "); Serial.println(buffer);
        RTC_Avail = true;
    }
    else
    {
        Serial.println("Couldn't find RTC. Real-time clock functions won't be available");
        RTC_Avail = false; //use this instead
    }

    if (RTC_Avail && rtc.lostPower())
    {
        DateTime Comp_dt = DateTime(F(__DATE__), F(__TIME__)); //__DATE__ & __TIME__ are environment variables)
        uint8_t mydayofweek = Comp_dt.dayOfTheWeek();  //returns 0 for Sunday, 6 for Saturday dayOfTheWeek
        int mymonth = Comp_dt.month();
        int myday = Comp_dt.day();
        int myyear = Comp_dt.year();
        int myhour = Comp_dt.hour();
        int mymin = Comp_dt.minute();
        int mysec = Comp_dt.second();
        long unixtime = Comp_dt.unixtime();
        char* dayofweek = (char*)daysOfTheWeek[mydayofweek];

        Serial.print("day of week value = "); Serial.println(mydayofweek);
        Serial.print("day of week value = "); Serial.println(Comp_dt.dayOfTheWeek());

        mySerial.printf("RTC lost power - setting to datetime of last compile %ld (%s %4d/%02d/%02d at %02d:%02d:%02d)\n",
            unixtime, dayofweek, myyear, mymonth, myday, myhour, mymin, mysec);

        rtc.adjust(Comp_dt);
    }


Why does void loop() stop after some samples? I am not getting any compile time error. After some samples of data void loop() stops executing. Please let know what the problem is. Below is my code.

Thanks and regards
Thippeswamy

#include<SPI.h>
float amplitude=1.5;
int freq1=20; int freq2=12;
int k=20;float A= amplitude*k;
int Fs=10550; float sine[5000]; float Fs1=3000;
int i=0;int reg1=1; int reg2=0;
int sample1=Fs/freq1; float sample2=Fs1/freq2;

void setup() {
  int SS=10;
  pinMode(SS, OUTPUT);
  SPI.begin();
}

void data(int reg, int data) {
  digitalWrite(SS,LOW);
  SPI.transfer(reg);
  SPI.transfer(data);
  digitalWrite(SS,HIGH);
}

void loop() {
  for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
    float s=A*sin((2*3.14*freq1*j)/Fs);
    sine[j]=s+190;
    data(reg1,sine[j]);
    if(i<=sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    } else if(i>sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    }
  }
}

float sine[5000]
...
sine[j]=s+190;

A float takes 4 bytes. You are allocating 5000 of them which is 20000 bytes. The Uno has 2048 bytes of RAM. Thus you are running out of RAM and overwriting something you shouldn't be.

As pointed out on the Arduino forum, your for loop which tests for:

i < sample2 || i >= sample2

will always be true. Of course i will be either less than or greater than or equal to sample2.


Newbe needing help with fixed string length im trying to build a bit of test equipment that will talk to some software and it needs to send a fix string. when the voltage changes the string length does as well. i need to cap the results to 4 in length. (sorry for not knowing the correct terminology. this is the output i need -

Where,

X = Flag CP Value
_ = Space
P = Polarity
C = CP Received value
Y = Flag Field Gradient
F = Field Gradient Received value
Z = Flag Contact CP
T = Contact CP Received value

There is also a line feed and carriage return present at the end of each string.
The polarity indicator will only display a minus sign ‘-‘ if the received value is
negative otherwise no assignation will be transmitted. Although the overall string
length is constant the values for each measurement are right justified and hence a
space will be present should the value of the measurement not necessitate the
utilisation of all allocated character spaces.
Sample Outputs

< X -89 Y -1989 Z -1096 >
< X 1039 Y 8 Z 78 >

this is my code so far

#include <Wire.h>
#include <Adafruit_ADS1015.h>

Adafruit_ADS1115 ads1(0x48);     // Use this for the 16-bit version
Adafruit_ADS1115 ads2(0x49);

void setup(void) {

  Serial.begin(9600);

  ads1.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV
  ads2.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV

  ads1.begin();
  ads2.begin();
}

void loop(void) {

  int16_t results01,results02,results03;

  results01 = ads1.readADC_Differential_0_1();
  results02 = ads1.readADC_Differential_2_3();
  results03 = ads2.readADC_Differential_0_1();

  Serial.print("X ");
  Serial.print(round(results01 * multiplier));

  Serial.print(" Y ");
  Serial.print(round(results02 * multiplier));

  Serial.print(" Z ");
  Serial.print(round(results03 * multiplier));

  Serial.println();              // send a cr/lf
  delay(500);
}

Any help pointing me in the right direction would be Amazing.
Thanks in advance

Joe

The printf() family of functions comes handy when you need
this kind of control over the formatted output:

/*
 * Format a number as 5 characters.
 * Returns the string in a statically allocated buffer.
 */
char * format5(int x)
{
    static char buffer[6];  // 5 chars + terminating NUL
    snprintf(buffer, sizeof buffer, "%5d", x);
    return buffer;
}

void setup() {
    Serial.begin(9600);
    Serial.println(format5(15));
    Serial.println(format5(-15));
    Serial.println(format5(-1500));
    Serial.println(format5(1500));
}

void loop(){}

output:

   15
  -15
-1500
 1500


Convert fuel level sender resistance ranges - good Arduino project? I've noodled around with Arduino a bit, worked some tutorials.  I have an engineering & programming background, but electronics isn't my first language.  So apologies if this is a dumb question.
Here's the problem.  I've swapped a 2007 GM engine into an older Toyota Land Cruiser.  I need to make it compliant with the emissions equipment that was originally on the 2007 vehicle.  Most of that is pretty straight forward - catalytic converters, O2 sensors, charcoal canister, purge & vent solenoid valves, a pressure sensor.  The one bit I haven't figured out yet is fuel level.  The evaporative emissions system requires a fuel level input to the PCM (Powertrain Control Module) so it can figure out when & how to run the fuel system pressure test - the one that turns on your check engine light if your gas cap isn't on tight enough.
One solution would be to put in a GM fuel level sender ... but that involves draining the tank, dropping it, maybe cutting new holes, more wiring, etc.  I'm hoping I can fix this in software :)
The GM fuel level sending unit reads 0 ohms empty and 90 ohms full.  The existing Toyota sending unit should be 110 ohm empty and 3 ohm full.
So ... is it a feasible thing to build an Arduino based project that reads the resistance from the Toyota sender (without interfering with the Toyota gauge) and translates that to the range expected by the GM PCM?
I'm thinking something like this is the core of it: https://www.arduino.cc/en/Tutorial/LibraryExamples/DigitalPotControl  But I don't know what I don't know.
Thanks folks - additional information based on responses:
The Toyota sender is definitely a 12V two terminal unit.  Car electrical systems are nominally 12V, but typically are about 13.3V in operation.
The GM sensor is two terminal also.  According to the wiring diagram, one terminal goes to a low reference pin on the PCM and the other goes to a pin on the PCM labeled fuel level signal.
But it doesn't tell you the voltage they're applying on that pin - could be just 5V, other stuff coming out of the PCM is.  I couldn't find a test procedure either.  I'll pin that connector and see what I can measure next time I'm out there.
The fuel level signal is used for two things in the evaporative emissions (evap) system.

The evap vacuum test can only run when the tank is between approximately 1/3 to 2/3 full.
The vacuum test is calibrated against how full the tank is - lower fuel level means more air space in the tank means the pressure will change more slowly then compared to a fuller tank.

The Toyota sensor may be using 12V instead of 5V, which would mean you'd need to use a voltage divider to get it down to the range that the Arduino analog inputs can read.
You will need to find a digital potentiometer that can handle the voltage range that the
GM controller wants to see.  This may be 0-12V, which would be a problem since the AD5206 is only good for 5V.
However, as dandavis implies with his RC filter comment, you may be able to simulate the full 0-12V range with PWM, where the Arduino pin drives a transistor to chop up the 12V, and an RC filter smooths the result for the GM control unit.  That's probably your best approach.
Alternatively, if the GM controller is only looking for a go/no-go level, you can use the
transistor to switch in a simple voltage divider to get the right voltage from 12V.
The sensors are (presumably) just variable resistors (2-terminal) not full 3-terminal potentioneters.  They will most likely be using a series resistor to make a voltage divider, and the control unit (or gage in the Toyota) will reading the resulting voltage. You will want to either find out the value of the series resistor or measure the voltage that the gage sees.  It might already be in the 0-5V range.  The GM control unit may have the series resistor built in (or be using a current source), in which case you should measure the voltage its sensor input sees when you give it the max and min resistance.  This will be good to know when you are trying to drive it with your own circuit,


how to send data to Adafruit Bluefruit Feather (32u4) over bluetooth? Sup yo.

I have my Adafruit Bluefruit Feather all wired up.  It's lovely.  I've got it responding to commands over the USB serial, activating an array of octocouplers.  It's terrific.  Here's the thing though.  I need to talk to it wirelessly.

I can only pair it (MacOS) the Adafruit Bluefruit LE Connect app.  It doesn't show up in my Bluetooth preference pane.

$ ls /dev/tty.*  shows /dev/tty.Bluetooth-Incoming-Port and the Arduino IDE can see it.  Unfortunately the word Incoming is right there in the middle of that port name.  Sending commands through the Arduino serial monitor doesn't seem to do anything.

The Bluefruit connect app appears to be able to send commands over something called UART but my board doesn't respond to the stuff that works over USB serial.

How do I talk to this board over Bluetooth?

The “UART” being referred to is the Nordic UART GATT Service. This is not a serial port or USB connection. It is a high level BLE protocol that simulates a serial port via the Bluetooth connection.

In order to connect to the device from your Mac you’ll need to write some C or Obj-C. I’ve done this for Windows, but not a Mac, so I’m afraid I can’t give you detailed instructions. However, the source code for the iOS Adafruit Bluefruit LE Connect app you’re using is open source and should be a good starting point.

Be warned of a few things though.

You’re going to have to learn a bit about the BLE protocols and standards. It’s not exactly for the faint of heart.
Apple throttles the speed/throughput of BLE for their iOS devices (as does Android) to protect battery life. I don’t know if they apply the same throttling to their laptops. You may not be able to achieve a satisfying data rate if you’re looking to create a high throughput “data pipe”.  With Win10 and the Bluefruit LE I was able to achieve 40 bytes every 30ms. You’ll likely be limited to 20 every ~30ms.

If you’re looking to just send some occasional text (maybe AT style) commands to the device via BLE though, you won’t come close to those limitations.


Error handling strings and chars I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?

void setup() {
   char* ss1 = "";
   char* ss2 = "";
   String txt = "";

   Serial.begin(115200);

   txt = "1234560001a";
   txt.toCharArray(ss1, txt.length());

   Serial.printf("\n\n");
   Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

   // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
   txt = "abcdef";
   txt.toCharArray(ss2, txt.length());

   Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
   Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
}

toCharArray is alias for getBytes. getBytes is documented as "Copies the String’s characters to the supplied buffer." You did not allocate the memory for the copied characters.

the right use of 'getBytes' and 'toCharArray' is

char buffer[BUFF_SIZE];
str.getBytes(buffer, sizeof[buffer]);

note: getBytes functions sets the terminating zero of the c-string in buffer


connecting 3.3V to +3V Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...

I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.

Thats all. Thanks already:)

The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The supply voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.


Troubleshooting an Arduino Computer Program I am trying to make a serial monitor print something based on when a button is pushed.

When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.

Thanks

int led = 2;
const int buzzer = 3;

int upButton = 5;
int downButton = 7;
int enterButton = 6;

int up = 1;
int down = 1;
int enter = 1;

bool homeActivated = true;
bool appsActivated = false;

int homeLocation = 1;
int appsLocation = 1;

bool homePrinted = false;
bool appsPrinted = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode (upButton, INPUT);
  pinMode (enterButton, INPUT);
  pinMode (downButton, INPUT);
  Serial.println("Initializing");
  delay(2000);
}

void loop() {
  up = digitalRead (upButton);
  enter = digitalRead (enterButton);
  down = digitalRead (downButton);

  //move up and down
  if (up = 0)
  {
    if (homeActivated = true)
    {
      homeLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      homePrinted = false;
    }
    else if (appsActivated = true)
    {
      appsLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      appsPrinted = false;
    }
  }

You need to learn basic C syntax.

= is assignment, not comparison.

For comparison you use ==

https://www.tutorialspoint.com/cprogramming/c_operators.htm


ESP32 seconds from epoch When using ESP8266 - getting seconds from epoch is done using

NTP.begin(NTPserver, 2, true);
delay(delay_tries);
time_t t = now();

while t stores amount of seconds from 1-1-1970.

When trying to do the same, using ESP32 - I cant get that numeric representation.

code below is from ESP32 example- updating time using NTP server ( process is done correct ). BUT when using now() yields 1970, as if NTP update has never occured.

How can I get time from Epoch ?

#include <WiFi.h>
#include "time.h"
#include <TimeLib.h>    <------- Added to original Code

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
  Serial.println(now());   <-------- Added to original code
}

to return 'epoch' seconds there is a function time in time.h

time_t now;
time(&now);

time_t is defined as long

this time is retrieved by the ESP32 SDK from NTP servers configured with  ESP32 Arduino function configTime

EDIT: it is the standard C time() function


Arduino leonardo. Encoder mouse movement I want to connect my sensonrs to an arduino leonardo.

The principal idea is use it like a scratch (like dj hero or beatmania??), if I move the scratsh up, the mouse will go up ( y Axis ), and if it go down, the y Axis down.

The middle is for gnd and the other four to 0 to 3 pin in the arduino.

So my problem is I am not sure about the conecction and also the code to run my program, beacuse all the thing that i try to do, had no work in my computer.

That's a quadrature encoder implemented using photo interrupters. Use a DMM to suss out which half of each is the diode and which is the phototransistor, connect both halves as you would were they independent, and decode the quadrature output.


Calculate burden resistor value of current transformer and measure ac current with arduino I Want to measure AC current with current transformer but i dont know exact value of burden resistor or calculation formula...i want to measure current of borewell pump. company specified pump as 1.5Hp power.

There is no "You need X resistor for Y transformer". The resistor you choose depends on what current range you are working with and what voltage range you want that to be expressed as.

That transformer is a 100:5 (or more properly a 20:1) ratio.  That means for every 20A going through it you get 1A out.

That output current is then passed through a burden resistor and you measure the voltage across that resistor.

If you are, for example, working with sensing up to 1A current then the maximum current you'd get out of it would be 1/20A, or 50mA.  If you want that to be expressed reliably within the range of a 5V ADC then you would:

Work from the mid-range of the ADC as 0V to give ±2.5V (assuming AC)
Calculate the resistor that gives 2.5V across it when 50mA is passed through it
Pick the next-lowest common resistor value.
Reverse the calculation to get the voltage range you now have.

In this example, R=V/I, so 2.5/0.05 = 50Ω.  50Ω resistors aren't common, but 47Ω ones are, so you'd pick that.

Then reversing it gives V=IR = 0.05 * 47 = ±2.35V

Give it a 2.5V offset to the ADC and you can now read points on a sinewave between 0.15V and 4.85V at 1A sensed current.


How can I connect the MP503 to an Arduino Uno (Smoke, Alcohol Sensor)? I don't know how I can connect an MP503 sensor to my Arduino.

Please help.

http://eleparts.co.kr/data/design/product_file/SENSOR/gas/MP503%20(Ver1.4)%20-%20Manual.pdf

Ok, first of all I doubt you will be able to get a lot of measurements with that. Because... I know that kind of sensors and you will quickly get tired of it.

Anyway, you have to connect

pin 1 to +5V
pin 2 to ground
pin 3 to +5V
pin 4 to a resistor towards ground. Value has to be determined.

To chose the value, you have to try. Change resistor values until, in fresh air, the voltage you can sense across the resistor is approx 1V. I think it is arount 10k, but you'll have to try

Chosen the resistor, you have to simply attach the node between pin 4 and the resistor to an analog input and then read the voltage.

Now you have to calibrate the sensor. Put it in a fixed-concentration gas and measure the voltage: nCalib = analogRead(sensorPin);.

Then, when you need to measure the concentration, you just have to read the voltage again with nMeas = analogRead(sensorPin);. The factor Rs/Ro can be calculated with the formula

Rs_over_Ro = nCalib / (1024 - nCalib) * (1024 - nMeas) / nMeas;

Once you have the factor, look at the graph in figure 3 to get the concentration:

As I told you, I think you will quickly get tired of it, but this is how to use it.


I can not upload hex files outside of the Arduino IDE to my Pro Micro I have a strange problem. I am trying to upload a .hex file to my lovely Arduino Pro Micro, but am unable to do so. If I use the Arduino IDE, it goes through perfectly fine and uploads the sketch. However, if I try to use avrdude from the terminal I get:

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

My commandline is:

avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -t

and the full output is:

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: exit bootloader

Thank you for any help, it is greatly appreciated.

--Dominic

Unlike the 328P and similar boards the 32U4 has no hardware method for triggering a reset to enter the bootloader.

On the boards with a UART -> USB interface the USB interface chip manually toggles the RESET pin to activate the bootloader. Without that chip a reset can't be done.

So a different method had to be invented. That method involves opening the serial port at 1200 baud and immediately closing it. That triggers a reboot into the bootloader.

The Arduino IDE manually performs that task when you press the upload button. It is not something that avrdude knows how to do.

So you will have to come up with some method of opening the serial port at 1200 baud immediately before running avrdude. Of course, it means the serial interface device disappears for a short while whilst the chip reboots and enters the bootloader, so you need to ensure you have a delay between the reset method and the call to avrdude - a delay that is long enough for your OS to redetect the chip, yet not so long that the bootloader times out.


GPS logging on the intel edison breakout board I'm working on my project car, and I have decided I would like to have a GPS and log some sensors too. I'm just at a bottle neck here, the sensors I have brought pull about 7v each where I can't pull that much from the breakout board that I have, and I can't seam to get the GPS to work.

I've tried using ths code but software serial isn't supported on the edison:

// GPS Setup
#define rxGPS 0
#define txGPS 1
SoftwareSerial serialGPS = SoftwareSerial(rxGPS, txGPS);
String stringGPS = "";

void setup() {
  pinMode(rxGPS, INPUT);
  pinMode(txGPS, OUTPUT);

  Serial.begin(9600);
  Serial.println("Started");

  // GPS Setup
  serialGPS.begin(4800);
  digitalWrite(txGPS,HIGH);

  // Cut first gibberish
  while(serialGPS.available())
    if (serialGPS.read() == '\r')
      break;
}

void loop()
{
  String s = checkGPS();
  if(s && s.substring(0, 6) == "$GPGGA")
  {
    Serial.println(s);
  }
}

// Check GPS and returns string if full line recorded, else false
String checkGPS()
{
  if (serialGPS.available())
  {
    char c = serialGPS.read();
    if (c != '\n' && c != '\r')
    {
      stringGPS  = c;
    }
    else
    {
      if (stringGPS != "")
      {
        String tmp = stringGPS;
        stringGPS = "";
        return tmp;
      }
    }
  }
  return false;
}

Any ideas or help would be much appreciated

Try this:

String GPSLine;

bool checkGPS()
{
  while(serialGPS.available())
  {
    char c = serialGPS.read();
    if(c == '\n') return true;
    if(c == '\r') continue;

    GPSLine += c;
  }
  return false;
}

void loop()
{
  if(checkGPS())
  {
    Serial.println(GPSLine);
    GPSLine = "";
  }
}


Arduino Uno: how to increase distance of serial communication to PC Does Arduino Uno's serial communication to  PC has the same distance as USB communication? (if I'm not mistaken 5m) If it is, what are the options for me to be able to communicate from Arduino Uno to PC with a longer distance? Thank you for any help!

There are many options of varying complexities, pros, cons and prices.

The simplest method is to use powered USB hubs to extend the range. It's 5m per run of cable between powered hubs, so if you have access to power at 5m intervals (or can provide power at 5m intervals) you can chain hubs together to increase your distance. That rapidly becomes unwieldy and expensive though.

Assuming you want to keep the ability to directly program your Arduino from the PC without having to mess with swapping cables around, etc, other options include:

USB over CAT5 adapters (up to 100m length)
Bypass the USB altogether and use RS-232 (MAX-232 chips, about 15m length)

There are also some bluetooth adaptors that allow programming of the Arduino, but that gets a bit tricky.

If you're not too worried about programming there are far more options:

Radio options, such as using XBees, nRF24L01 modules, etc.
Networking - connect to an Ethernet or WiFi network
GSM modem
RS-485 / RS-422 - similar to RS-232 but longer distance, and without the signals needed for rebooting the Arduino for programming

The "distance" of the fully networked options is, literally, global. Once on a network you have the option of arranging access from anywhere on the globe with an internet connection

It all depends, really, on what you want to be able to do over the connection.

(I am sure there are many more options I have forgotten - feel free to suggest them in comments, or even go ahead and edit this answer to add them if you like.)


How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter? In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc.
  How do I send and receive data using my pc-interface? What software do I write and how do I write it?

In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

The USB to SPI adapter you choose (NOT USB TO UART!)
The low-level control and interfacing of the nRF24L01+ chip
The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.

If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.

So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.


I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.

I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.

I tried calling Wire.setClock(400000);, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).

I also tried calling Wire.begin(); TWBR = 10;, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple

#include <Wire.h>
#include "Adafruit_FRAM_I2C.h"

/* Example code for the Adafruit I2C FRAM breakout */

/* Connect SCL    to analog 5
Connect SDA    to analog 4
Connect VDD    to 5.0V DC
Connect GROUND to common ground */

Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
uint16_t          framAddr = 0;

byte p = 55;   //any old value- just write the same thing into all locations

void setup(void) {
    Serial.begin(153600);
    //Wire.begin();
    //TWBR = 10;
    //Wire.setClock(400000);

    if (fram.begin()) {
        Serial.println("Found I2C FRAM");
    }
    else {
        Serial.println("I2C FRAM not identified ... check your connections?\r\n");
    }

}

void loop(void) {

    int i = 0;

    long a = micros();

    for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
        fram.write8(i, p);

    }

    for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
        fram.read8(i);

    }

    long b = micros();

    Serial.println(b - a);
    Serial.println("");
}

You are running at 400000 bits per second, or 200000 per half second you say it takes.
You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
200000/1000 = 200 bits per transaction.
Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.

That makes 50 bits per transaction.

So yes, half a second to write then read it all is perfectly possible.

The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.

A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.

So for a read and write it's 38+48 = 86 bits.

Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.

At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.

If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

So not a bad guestimate of 25% transmission in my original surmising.


Multiple sensors connected to Arduino MEGA 2560 Serial ports I am using Arduino MEGA 2560 to read values from two sensors. Sensor 1 is providing us two values separated by a comma and a space followed by a newline character. e.g.:

2.277, 7.942
2.269, 7.897
2.263, 8.040

Sensor 2 is providing us a single value followed by a newline character. e.g.

1.213
1.333
1.17

Sensor 1 gives twice as many readings as Sensor 2 in the same amount of time. Sensor 1 is connected via Serial1 and Sensor 2 is connected to Serial2 on MEGA board. I am using the following code to read the values:

void setup() {
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    {
      Serial.print(Serial1.readStringUntil('\n'));
      Serial1.flush();
    }
  }

  Serial.print("\t\t\t");
  if (Serial2.available()) {
    while(Serial2.available())
    {
      Serial.write(Serial2.read());
      Serial2.flush();
    }
  }
  Serial.println();
  delay(1000);
}

I am expecting an output similar to this:

2.409, 8.150            2.134
2.490, 7.851            2.133
2.603, 8.759            2.122
2.634, 8.305            3.12
2.727, 8.408            1.32
3.018, 7.982            2.543
3.030, 7.982            1.345
3.020, 8.587            2.435
2.844, 8.034            2.763
2.690, 8.690            5.433
2.721, 8.011            2.348
2.705, 8.242            7.654
2.670, 8.713            2.123
2.756, 8.563            2.098
2.899, 8.413            2.765
3.464, 8.196            2.654
3.705, 8.437            2.343
3.435, 8.558            1.245
3.446, 8.592            2.345
3.421, 8.075            1.234

Instead I am getting something like this:

2.770, 8.332.635, 8.281         2.345
2.690, 8.690            2.674
2.721, 8.011            2.356
2.705, 8.242            2.345
2.670, 8.713            3.002
2.756, 8.563            2.094
2.899, 8.413.102, 8.523         2.984
3.464, 8.196            2.398
3.705, 8.437            2.745
3.435, 8.558            2.789
3.446, 8.592            2.543
3.421, 8.075            2.984
3.504, 8.153.772, 8.770         2.183
3.705, 8.552            2.784
3.653, 8.443            2.567
3.908, 7.971            2.098
5.020, 8.581            2.20
3.913, 8.247            2.342
3.762, 8.023.575, 8.345         2.123

The sensor readings after every few lines are distorted. I understand this might has something to do with the serial buffers. How could I rectify this and obtain the desired output?

Your serial buffers and moving in and out of phase, which is distorting your display.

Try something like:

void setup() {
  String sensor1;
  String sensor2;
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    sensor1 = Serial1.readStringUntil('\n'));
  }

  if (Serial2.available()) {
    sensor2 = Serial2.readStringUntil('\n'));
  }

  Serial.print(sensor1);
  Serial.print(sensor2);
  Serial.println();
  delay(1000);
}

I would also recommend the method suggested by @Majenko in his comment below your question.


How to set a timer for a function and be able to reset it in the middle of the process? Hello me and my friend have to do an assignment for school but we need some help. We have to make a LED turn on and of with a button and a relay. But when I press the button the LED should be on for 10 minutes and then go off unless we press the button inside those 10 minutes then the LED should turn off. Then repeat this process when we press the button again.

const int relay = 6;
const int button = 5;
int stateold = 1;
int statenew = 0;
int LED = 0;

void setup()
{
  pinMode(relay,OUTPUT);
  pinMode(button,INPUT);
  time = millis();
}

void loop()
{
  statenew = digitalRead(knop);
  if(stateold==0 && statenew==1){
    if(LED==0){
      digitalWrite(relay,HIGH);
      LED = 1;
      }
    }
    else{
       digitalWrite(relay,LOW);
        LED = 0;
    }
  }
 stateold=statenew;

}

Below code is an example of what you described; pressing the button will turn on the LED and it will only turn off if 10 minutes passed or button is pressed again.

Read the comments in the code:

#define btn 5
#define rly 6

bool btnState;
bool ledState;
unsigned long timer = 0;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  pinMode(rly, OUTPUT);
}

void loop() {
  btnState = digitalRead(btn); // Read the button status (default is 1)

  if (!btnState) { // If button state == 0 (pressed)
    ledState = !ledState; // Toggle this boolean
    timer = millis(); // and reset the timer
  }

  if (ledState) { // If LED state == 1
    digitalWrite(rly, HIGH); // Turn on the Relay
  } else { // Otherwise turn it off
    digitalWrite(rly, LOW);
  }

  if (ledState && millis() - timer > 600000) { // If 10 minutes passed turn off the relay
    digitalWrite(rly, LOW);
    ledState = !ledState;
  }
}

You should also de-bounce the button and you may want to turn on/off the LED when button is pressed and released, not just when it's pressed.


Manipulating 3 IR led's on Arduino Uno I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.

However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.

e.g

IR LED 1 connected to pin 11 - send signal 0xABCDEFGH

IR LED 2 connected to pin 10 - send signal 0xSJKLMNOP

IR LED 3 connected to pin 09 - send signal 0xZXYRWVUG

I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.

//LED 1

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 11; i++) {
            irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED 2

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 10; i++) {
            irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED3

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 9; i++) {
            irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }

I think what you have done is a perfectly logical thing to do.  You had three programs that worked and so you pasted them all into the same file and compiled it.  The compiler spat its dummy out of the pram and you didn't understand what the h*ll went wrong.  Is that about right?

// You only need to include each header file once
#include <IRremote.h>

// You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
IRsend irsend_led1;
IRsend irsend_led2;
IRsend irsend_led3;

// This is where you do all the setup, it only gets executed once.
// You might need to assign the pin numbers to the irsend_ledX variables here.
void setup()
{
}

// This function is called repeatedly.  You can only have one of these.
void loop() {
    // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
    // I think the data is being sent multiple times, don't know why though
    for (int i = 0; i < 11; i++) {
        irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 10; i++) {
        irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 9; i++) {
        irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
        delay(1000);
    }
    delay(1000); //1 second delay
}

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.

Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.


Starting Off Low-Level Port Access    I'm trying to teach myself some low[er] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?

I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB_5)

Current code:

#define STATE B00001000
#define ZERO B00000000
void setup() {
    DDRB = STATE;
    }

void loop(){
    PORTB |= STATE;
    delay(500);
    PORTB &= ZERO;
    delay(500);
    }

It would probably help if you were using the right pin.  In the pins_arduino.h file for the Uno is this diagram:

//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+

That shows that pin D 13 is PB5 which would be a binary value of 0b00100000 not 0b00001000 as you have, which would be PB3, or pin D11.

The only way I can come up with 0b00001000 is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).


Working with long strings So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.

Thanks.

Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.

My advice:

Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.

For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).

Update after your comment below.

What you can try:

Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
Double check the wiring (although it seems easy).
Try different wires (maybe a jumper wire is malfunctioning).
Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).


Programming Servo How To Get -90 Degrees as the question title states, how will I go about turning the servo opposite of 90 degrees?

I have written my code as such;

  // Turn servo to the right
  if(x > 520 && y < 510 && y > 490){
  servo.write(0);
  delay(50);

  //Turn left
  }else if(x < 490 && y < 510 && y > 490){
    servo.write(180);
    delay(50);

 //Turn backwards
} else if(y < 490 && x < 520 && x > 490){
  servo.write(-90);
  delay(50);

Obviously -90 isn't an actual degree on the servo, and it will only turn between 0 and 180. I was therefore wondering if there was any other way to code it?

The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. Every other command works, and when I replace -90 with 90 degrees, it works as well. So it is wired correctly.

Of course I would have to add another joystick and another servo later on, but at this stage I am simply testing my own coding skills.

Normal servos only have a range of 180°. You can give yourself an "offset", so you have -90° to 90°, but you only ever get 180° range. You can't go -90° to 180°.

Using mechanics (outside the scope of this site) you can multiply your movement (think gears) so that your range is bigger.


Changing direction of DC motor i am working on a project which requires changing the direction of the DC motor using arduino. that is I want the DC motor to rotate clockwise when i press key 'A' and anti clockwise when i press key 'D' on my computer.

i have v+ and v- input wires from battery. i have connected one end of the DC motor to gnd of the battery. On the other end of DC motor i want to connect V+ and V- input from the battery to spin the DC motor in clockwise and anticlockwise respectively. I have used BC547 npn transistor.
i do not know how to change inputs (v+ to v- and vice-versa) using arduino when key is pressed.

is there any method other than H-bridge method to do so?

i use arduino uno.

Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit.

The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transistor to drive it.

The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+.

I found this schematic applicable, but only use the left side. The right side of the motor should be connected to ground (or the middle voltage of your battery). , and replace the opto's with normal transistors.

Come to think of it, I'm not entirely confident about replacing the bottom opto, since battery-negative is below GND in your case. I think it should work, but I'm still quite new to this stuff.

Also make sure you add something like 1k resistors to the base of the transistors (that replace the opto's)


NodeMCU burned, did I something fundamental wrong? I have a NodeMCU where I connected a LED strip (WS2812b, which operates at 5V).

NodeMCU is powered via USB 5V. The used power adapter can supply 2.5A max.

I don't have a separate power supply for the LED strip yet, so I connected it to VIN/GND of the NodeMCU.

That worked.

Yesterday, I took the NodeMCU (without led strip) to my PC and uploaded an updated sketch.
After that, back in the living room, I connected the NodeMCU with the led strip and the USB power supply.
I didn't need an ambilight at the moment so I left it off.
After 5 minutes, I smelled something burned. As you can see in the second image, the component below ground is burned.

I had this setup successful running for a week (with ambilight turned on for several hours) and had no issues at all.

Did I something fundamental wrong?
Any guess, why it works flawless and then suddenly burned after just 5minutes?

Any tip/suggestion is very appreciated!

The white component on the right is a DHT22 temperature sensor and has been added for completeness.

The resistor and LED on the right are not used, they were just plugged in from a previous setup.

Best regards

Casper

Yes, you did something fundamentally wrong.

The component that blew up is a diode.  It is designed to protect the USB from voltage being injected into the board.

That diode can handle an absolute maximum of 1A.

Any fault on your LED strip connection (a short to ground) will cause that diode to vacate the premises. As yours did.

The purpose of the VIN pin (as the label suggests) is as a voltage input. It's not really designed to provide power to other devices, especially as the ESP8266 itself can take more than half that 1A power budget when communicating.  You should not use VIN for powering anything more than maybe a couple of low power sensors. LED strips are a big no-no.


Problem with Software Serial: no response I am using an Arduino Uno board with IDE 1.6.7.

I have tried to implement a tweaked version of the basic example (SoftwareSerial example) from the Software Serial library. The code is attached.

It should blink the light and print the message on the serial monitor. But I am not getting anything.

In fact, I also tried the example as it is. It did not work either.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(8, 9); // RX, TX

void setup() {
    pinMode(13,OUTPUT);
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }
    Serial.println("Goodnight moon!");
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    delay(1000);
}

void loop() { // run over and over
    mySerial.println("hell");
    if (mySerial.available() > 0) {
        digitalWrite(13,HIGH);
        Serial.write("working..");
        delay(3000);
        digitalWrite(13,LOW);
        delay(2000);
    }
}

SoftwareSerial cannot transmit and receive at the same time.  So even if you connected pin 8 to 9 with a wire, your sketch will not receive what was transmitted.  That's a guess without your wiring diagram.

NeoSWSerial can simultaneously transmit and receive.  It is a drop-in replacement for SoftwareSerial.

However, AltSoftSerial is even better, and it only works on pins 8 & 9.  Use that instead!

This answer compares all 4 serial types, including HardwareSerial.


arduino not loading library I am receiving a compilation error from

#include <HX711.h>

The error is

fatal error: HX711.h: No such file or directory

However, C:\Users\user\Documents\Arduino\libraries\HX711 is there and has the correct files in it.
Sketch -> Include Library -> Manage libraries says that HX711 is installed. Strange thing is that I have another sketch that uses this library and it compiles. It uses quotes instead of angle brackets (which is strange because HX711.h is not in the same directory) and it works.
I have tried both quotes and angle brackets.

EDIT: I am really sorry about typing "define" instead of "include" into the question my only excuse was that it was late.
I copied the library directory to:

C:\Program Files (x86)\Arduino\libraries

and the problem remains.

I now have the HX711 directory in both the Arduino program files and the user directories and it still complains about it. The only way I can get it to compile is to place the hx711.h & hx711.cpp files directly into the sketch directory and change the line to #include "HX711.h"

EDIT:
Running Arduino 1.6.5 on Windows 8.1 64bit

You're using #define when it should be #include.


How can i stop a loop after 1 minute? This is my first Arduino project, and I would like to stop my servo's loop after 1 minute. Can someone help me?

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);
}

void loop()
{
  myservo.write(45);
  delay(1000);
  myservo.write(125);
  delay(1000);
}

Thanks!

As suggested by Jot in a comment, one way would be to simply do what you want (which takes roughly two seconds per iteration) in a loop, like this:

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);

  for (int i = 0; i < 30; i++)
    {
    myservo.write(45);
    delay(1000);
    myservo.write(125);
    delay(1000);
    }
}

void loop()
{
}

The problem with that is it relies upon knowing how long your delays are, and assumes that the myservo.write() functions take no time. A better method is:

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);

  unsigned long start = millis ();

  while (millis () - start <= 60000)  // for 60 seconds
    {
    myservo.write(45);
    delay(1000);
    myservo.write(125);
    delay(1000);
    }
}

void loop()
{
}

This uses the millis() function call to find out how much time has elapsed, and wait for 60000 milliseconds (60 seconds).

I've put the code into setup because that is where you put things you want done once.


Using a 4*4 keypad to enter an integer value I have a 4*4 keypad and I want to use it to enter a number.  I will then use this number as a delay to a LED or a motor to run for the specified time.
This is my sample code:

#include<Keypad.h>
#include<LiquidCrystal.h>
const byte numRows = 4; //number of rows on keypad
const byte numCols = 4; //number of columns on keypad

char keymap[numRows][numCols]=
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'X', '0', 'Y', 'D'}
};

char value[4]="";
int index = 0;

byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

Keypad key= Keypad(makeKeymap(keymap), rowPins, colPins, numRows,numCols);

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

void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
lcd.begin(20,4);

lcd.print("       WELCOME      ");
delay(100);
}

void loop() {
char keypress = key.getKey();
while (keypress != NO_KEY){
  if (keypress == 'X'){
      lcd.clear();
      for(int j=0;j<=4;j++){
        value[j]=0;
      }
      index=0;
      }
   else if (keypress == 'Y'){
      int amt = atoi(value);
      digitalWrite(13, HIGH);
      delay(amt);
      }
   else
      value[index]=keypress;
      index++;
    }
}

How do I read the value returned by the keypad as an integer?  (When I press 3 I want to read 3 not "3").

You can easily read by this line of code

value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3