arduino sketch on Win7 vs. MAC op system? I have a friend who is just getting started with Arduino UNO.  He downloaded a sketch and is using a UNO on Mac OS.  He loaded the sketch and verified.  it comes up with errors.  He sent me the same sketch and i opened it under Win7 arduino software.  verified, and it says it is fine.  i made an arduino file and emailed it back to him.  he is still getting the same errors.  can anyone help and let me know what is wrong?  i am not a MAC expert and wonder why  this works in win and not MAC????????  appreicate any help anyone can give me

I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


How to convert my Arduino setup to a PIC setup? I have an arduino setup with LCD, RTC, EEPROM, Reed Switch, AC/DC Buck Converter, 4X4 Keypad.
What PIC IC will let me connect with all these(40 Pins), and yet accept Arduino Code.
I don't want to rewrite the code. I learn Arduino only recently, So shifting to another coding language is near impossible, since am not a coder.

The PIC32 has full (or nearly full) support for the Arduino API through the chipKIT project.  If you want to use one of the smaller PIC chips (PIC16 / PIC18 etc) then you're out of luck. There just isn't a freely available C++ compiler for those chips, so the Arduino API can never really be ported to them.
I have, in the past, cobbled together an Arduino-style API layer for a handful of selected PIC18s which uses structs to emulate a couple of the Arduino C++ objects, but it only worked in a very basic way with no function overloading for things like Serial.print().
One of the problems from a low-end user's perspective is that the PIC32 only comes in harder to use TQFP and QFN etc packages in anything larger than 28 pins. That means you can't breadboard without a development board. Fortunately there are some breadboard friendly options in the chipKIT ecosystem, such as the Fubarino series of boards. For more pins though you'd be wanting one of the bigger boards, such as the MAX32 which is in a Mega footprint (but with even more pins).
It's important to note though that the PIC32 is a 3.3V device and, owing to physical differences in the way that some of the internals work, there are incompatibilities in some of the libraries and functionality (such as no "LOW" or "CHANGE" interrupt support, only "RISING" and "FALLING").

What PIC IC will let me connect with all these(40 Pins), and yet
accept Arduino Code.

The answer is none.
The PIC world is different than the Arduino world. In the end the same things can be accomplished. But they are not directly compatible. Just like PCs/Microsoft compared to Apple. They are both computer systems. They both can do the same kind of things. But how it is done is different.


How to control android app with arduino I'm trying to connect Arduino Leonardo to an Android tablet. I would like to make the Arduino send commands (using pushbuttons or a slider for example) to the tablet to switch between pages, to select a file on the desktop, to scroll up and down the screen, etc.

Thanks. I will really appreciate your help.

Perhaps this is not exactly what you are looking for, but from your examples it seems like using navigational commands from the keayboard/mouse would accomplish a lot of what you are requesting.

Android has USB HID support from honecomb, so you should be able to create a sketch to emulate a keyboard and mouse based on the IO data and it should work with your android device just by plugging the USB cable (if emulating a mouse, it will display the mouse cursor as soon as it is connected).

First, get a Lightblue Bean, http://punchthrough.com/bean/

It has everything you need:
- arduino
- bluetooth
- API
- code example
- android sdk
- ...

Develop your product using this platform.

If you want to scale and build your own platform, then you will have a foundation to validate your work.


Arduino-based mains frequency monitor follow-up Following my
previous question, I'm getting closer to thinking about putting together this mains frequency monitor. I would just like to do a sanity check on my electronics before I order the components and the board. Please keep in mind I am not qualified in this so I have had to research how all this will work.

A and B inputs will accept power from a 16VAC 1.25A unregulated power pack.

C1 is a 1µF 25V 85°C ceramic capacitor. I guess this is mostly unnecessary as the power pack should filter any DC bias, but it won't hurt.

D1 is an IN4001 1A standard recovery diode.

R1 is a 300ohm 500V 3W resistor. The RMS power is 16VAC, which is half-wave rectified, so that's sqrt(2) * 16 = ~24V peak @ 300ohm = 80mA peak, and about 25mA on average (right?)

IC1 is a 4N28 optocoupler. It's weird, in one data sheet I see 80mA max forward current on inputs but in another I see 60mA. Anyway, the average should be 25mA so I guess that's probably going to be okay?

The Arduino I will use is the Arduino Micro, as it's quite small and also has a 16Mhz crystal oscillator that will provide a more stable clock than a ceramic resonator. The Arduino will be powered by USB, which I believe is 5V. The digital I/O pins I believe will also operate at 5V and are rated at 40mA max.

C will come from one of the Arduino's digital output pins, and D will go to the Arduino's GND.

R2 is a 150ohm 500mW 250V resistor, that should ensure the C→D current does not exceed 40mA @ 5V.

Now, assuming the components look okay and the circuit looks okay (I assume the circuit is fine), I just had some questions:

Do I need to add anything to the output of the 4N28 coming from the input? I think with a regular transistor, some of the base current gets added to the collector current?
What can I expect the response on the output of the 4N28 to look like? I assumed that it would more-or-less be a square wave, where even a tiny current on the input would activate the transistor and allow the output current to flow freely on the other side, but someone has suggested that this might not be the case?
The way it is set up, the Digital I/O pin can be "trying" to output or not, and that's basically irrelevant to what the transistor is doing. When the transistor is on, the output current from the pin will successfully flow to GND. I assume there is a way to detect this in the Arduino? Something like setting the output pin to 1 and check in loop when there is or is no current flowing?

Thank you!

You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit.  All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.

You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

simulate this circuit – Schematic created using CircuitLab

You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.

Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.

I am not qualified in this

I think you will find it very beneficial to you to get qualified in this first before you try -> what you are trying to do has a real potential to kill you, especially if you aren't qualified in it.

  C1 is a 1µF 25V 85°C ceramic capacitor.

Again, that's a deadly choice of components here -> it pays to be qualified, preferably well qualified, in what you do first.

you may want to think of a transformer based solution first -> the principle is the same but it is much safer, especially for someone who isn't qualified here.

the software side of it is simple: use the zero-crossing signal to gate one of the avr timers and you can measure the mains frequencies to many many bits of resolutions.


How can i get rid of the error "cannot convert 'String' to 'const char*'" I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:

#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

there is no reason for command to be a String array. Instead make it a const char**:

const char** commands = {"/test", "/say", "/reset", "/sleep"};

Just change String commands[] to const char* commands[] or try using square brackets in the declaration instead of curly brackets


Executing machine code at runtime Uno I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?

Something like this:

uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

(or maybe with some avr like assembly code?)

The microcontroller is executing one command at a time from..where?

Flash memory directly. The AVR core can only execute instructions from Flash memory. It uses a two-bus system known as Harvard Architecture, where the Instruction Bus is connected to Flash and is used to execute instructions, and the Data Bus is connected to SRAM, EEPROM, all the peripherals, GPIO pins, etc.

It is possible to jump to any location in memory in a similar way as you have depicted, but in order to know where you first need to know the functions you want to call.  You can get the address of any function and assign it to a pointer, and then call that pointer as a function, but what would that achieve? You may as well just call the function directly and save time. Unless you want to store the addresses of those functions in an array or something to maybe associate them with a command to trigger the execution of that function. In which case you don't need anything "fancy", just pointers to the functions you want to use.

Something like this:

you are basically asking for function pointers. easily done like this, on a pic24 but applies to pretty much anything.

static void (* _isr_ptr)(void)=empty_handler;               //tmr1_ptr pointing to empty_handler by default

void _ISR _T1Interrupt(void) {
    _T1IF=0;                            //clear tmr1 interrupt flag
    _isr_ptr();             //execute user tmr1 isr
}

//activate the isr handler
void tmr1_act(void (*isr_ptr)(void)) {
    _isr_ptr=isr_ptr;           //activate the isr handler
    ...
}

the ISR executes _isr_ptr(), which is hooked to a user routine via tmr1_act().

the only difference is that this approach doesn't require knowing the fixed address. instead, it is provided for in tmr1_act() through isr_ptr, the function to be pointed to by _isr_ptr.

but the basic concept is the same.


ESP8266 WiFiClient connection always returns 0 I am trying to use a NodeMCU as a station to connect to a webserver, however, the WiFiClient connect function always returns 0 for no reason. I am able to connect the NodeMCU to my home WiFi, but it just cannot connect to any server (either with IP address or with URL).

If anyone is interested, the following is the testing code (I did not include the libraries intentionally for the clearness of the code).

int status = WL_IDLE_STATUS;
IPAddress server(74,125,115,105);  // Google

// Initialize the client library
WiFiClient client;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting to AP specified during programming");
  WiFi.begin("mySSID", "myPassword");
  while (WiFi.status() != WL_CONNECTED) {delay(500); Serial.print("."); }
  Serial.print("\r\nWiFi connected IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

void loop() {
  Serial.println(client.connect(server,80));
}

I had the same problem with my esp-01. Just download ESPWenServer library from here.

  https://github.com/esp8266/ESPWebServer

And from this try HelloServer.ino example code. If it still does not connects-
1.Either your WIFI is not working
2.You are typing wrong SSID and PASSWORD
3.Spacing between SSID name or PASSWORD is the issue.

For the 3rd one if possible change your Wifi password or name if it has spaces between it.


MKR1000 not showing up on OSX I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also
➜  ~  csrutil status
System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing

Double click the reset button on the board. Then it will show in the Port list :-)

See if this answers your question:
https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-strarted-08bb4a

If not, go to your Board Manager (this happened to me too) and search MKR1000. There should be another install to do. Install that one and you should be good.


How can I stop SoftwareSerial from receiving data and re-enable it at some other point? My project involves and RFID reader connected to an Arduino Pro Mini (5V, 16MHz) and an Adafruit CC3000 breakout WiFi chip. The device reads RFID tags and sends them to my web service. I am using Software Serial to read the RFID device data.

After I scan something, the Arduino tries to send the value that was read to the web service. This obviously causes a delay and the program only continues execution (i.e. next iteration of the loop() function) after the data has been sent.

My problem is simple. While the value is being sent, the serial buffer is can still accept scans from the RFID reader and on subsequent iterations, because there is data in the buffer the device attempts to send data again.

My question is how can I stop the software serial port from receiving data while I am trying to send data to the web service? Then when the data is sent successfully, how can I re-enable the software serial port from accepting data?

Call serial.end() to stop receiving.

Then call serial.begin(...) again when you want to start listening again.

I had the same problem with reading GPS-Data on Port 11 while sending APRS-Data out. This code worked for me:

GPS.end();

aprs_send();
while (afsk_busy());

GPS.begin(GPS_BAUDRATE);


Arduino micro program not uploading I am having trouble uploading a new program to my arduino micro. I first flashed the blink example program to the board and that worked. However now whenever I try to flash a new program it either cannot fine the port of it just gives me a general error. I have selected the right model and port in the tools menu as well as press the reset button right before the upload stage. This arduino micro has an external power supply. Here is the error code:

Sketch uses 4,244 bytes (14%) of program storage space. Maximum is 28,672 bytes.
Global variables use 154 bytes (6%) of dynamic memory, leaving 2,406 bytes for local variables. Maximum is 2,560 bytes.
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, COM9, } => {COM9, }
Found upload port: COM9
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM9 -b57600 -D -Uflash:w:C:\Users\Joel\AppData\Local\Temp\build4becb324f24d9ea6a5bead572d36ff0a.tmp/d4onOF.ino.hex:i
An error occurred while uploading the sketch.

Com 1 and 4 are default to this computer

Thanks in advance for your help.

This problem was fixed by restarting the arduino IDE by the exe instead of opining it from an .ino file.


How to use BlueTooth on mobile device to find AccessPt and enter PW for ESP8266 WiFi on an Arduino controller? How can I use BlueTooth on a mobile device to connect to my HC-05 equipped instrument to find the local WiFi AccessPt and enter the PW for my Arduino controlled instrument with ESP8266 WiFi?

I want to set up remote Arduino controllers with WiFi (ESP8288) connections in various locations where I have to log in to the Access Pt.  I want to use my phone to make the AP connection, connecting to my instrument's HC-05 via BlueTooth.  Does anyone have any code for this?  (RoboRemo?)  Or am I missing another simpler solution?

Consider the Amazon Echo:  You download the app to your phone.  You start the app and connect it to the Echo.  How?  Magic? No, BlueTooth.  Next step:  Use the app to enter your AP settings.  The Echo is now connected to your WiFi.  Delete the app.

I want to setup my Arduino devices the same way.

Don't overcomplicate things by adding bluetooth.

If you want to set the WiFi credentials at run time, use the WiFi Manager library. It's exactly what it was designed for.

Bluetooth and WiFi are different things. Absolutely different (except more or less same frequence used). Its the same as asking how to connect to WiFi from your car radio.


Bootup on lower power not functioning I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works beautifully when 5V power is applied first, then the battery is inserted, then 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied first. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, nothing. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

Update: I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.

Try re-bootloading your arduino by going to Tools > Burn Bootloader


Why do we use HX711 with load cell (Why do we need A to D conversion)? We generally amplify the signal from load cell but why there is need for A to D (analog to digital) conversion?

The HX711 is nothing more than a sensitive amplifier that takes the tiny signals from a load cell and amplifies them coupled with a high resolution ADC.
You can do without the HX711 but the signals are so tiny and the Arduino ADC so low resolution that the results are useless.
You can create your own amplifier with op-amps and use the internal ADC of the Arduino, and the results will be reasonable, though the resolution will suck.
You can use another high resolution ADC chip to increase your ADC resolution so you can measure more accurate weights.
Or... you can just do it all in the one chip with the HX711.

Why do we use HX711 with load cell (Why do we need A to D conversion)?

There are 2 parts to this question:
Part 1:

Why do we need A to D conversion?

In short: a microcontroller is a digital device, so it can only deal with digital, not analog, readings and data.
Details:
You need analog to digital conversion after amplification of the load cell signal because a microcontroller is a digital, not analog device. It has a digital processor, stores digital information in finite and discrete variables made up of digital bits (1s or 0s), and cannot otherwise work with, store, process, communicate or transfer, or do anything in memory with a number or value except that number or value first be converted to digital bits.
Part 2:

Why do we use HX711 with load cell?

In short: the voltage signals coming from a load cell are so tiny that a microcontroller's internal ADC (analog to digital converter) cannot read them without amplification first. The HX711 amplifies the tiny load cell signals, reads them with its own internal ADC, and sends them to a microcontroller, such as an Arduino, as digital data.
Details:
A normal ATmega328-based Arduino has only a 10-bit ADC, which returns values from 0 to 2^10 - 1, or 0 to 1023, for a total of 2^10 = 1024 values. Assuming your Voltage Reference is 5V, which is default, this means your voltage measuring resolution is only 5V/2^10 = 5V/1024 = 4.88mV. The voltage values returned by a load sensor (Wheatstone bridge, I believe), however, are much much smaller than this, so amplification and a better ADC are needed.
Here is the HX711 (see datasheet):

It includes an op-amp amplifier with a gain of 32, 64, or 128, as well as a 24-bit ADC, which has a resolution of 2^24 = 16777216 increments inside the HX711, instead of 2^10 = 1024 increments inside an ATmega328 microcontroller which is used by the Arduino Uno, Nano, or Mini. So, the HX711 has a resolution that is 16777216/1024 = 16384 times better than the Arduino's ADC. This means that even withOUT amplification, and still assuming a 5V voltage reference, this ADC already has a voltage resolution of 5V/16777216 = 0.298 uV, which is 16384 times smaller than 4.88mV.
Summary:
So, you use the HX711 to read the tiny tiny nanovolt or microvolt or so level voltages from the load sensor, since the Arduino can't read voltage values that small. You then communicate with the HX711 via what appears to be a bit-banged SPI protocol, shifting bits in and out of it, asking it for readings. It performs the analog amplification with its internal op-amp, and then it performs the analog to digital (A to D, or ADC) conversion to turn this true analog voltage into a binary (digital) number than can be sent to and processed by a microcontroller, such as an Arduino. No ADC is used on the Arduino itself for this reading.
References:

Sparkfun description and libraries: https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide
HX711 Datasheet, from Sparkfun: HX711 - "24-Bit Analog-to-Digital Converter (ADC) for Weigh Scales"


Why/when to use IoT publish/subscribe protocols rather then RESTful HTTP? I am sending data (GPS coordinates) from Arduino once a minute with HTTP POST request to REST API (in OpenShift PaaS). Data is then stored to MySQL db.

Would so called "IoT" publish/subscribe protocols (XMPP, MQTT) be better? Why?

When exactly do you use those two protocols rather than Restful HTTP? Would I really save a significant baterry energy using them?

AFAIK in those protocols machine would "publish" a data to broker and my app would subscribe to it. If I would like to gather data every minute in my app I guess that I would got to have some CRON job that would subscribe to data every minute? Or how would data gathering be achieved?

In my experience ReST is good for real-time data transfer and processing but has a lot of overhead for simple message passing. Plus, there's no queuing in it so store-forward configurations are troublesome.

MQTT is a message queue transport system where the message can be placed on the channel by the publisher and will stay there until the subscriber picks it up. So you can have some rudimentary store-forward capabilities with this. Also MQTT is more transparent and multicast so communicating to many nodes is no different than communicating to one.

With that, each have their place and use and ReST is great for sending large items (JSON blobs), sending data for calculation and getting it back, and for requesting a specific dataset. MQTT is more for "here's my sensor data every second, enjoy".

In my applications, the biggest power drain is turning on the radio to transmit data. I often keep the radio off, collect data points, and then turn on the radio to send multiple pieces of data together as one request using a RESTful HTTP call. For my case, RESTful HTTP is way more efficient since I do not need an always on connection.


A beginner lost at sea, Arduino looking at the sun I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!

const int analogInPin = A0;
const int analogOutPin = 9;

int sensorValue = 0;
int outputValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 500);
  analogWrite(analogOutPin, outputValue);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

I am using an NTE 2908 N-channel.

You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.

I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work

Otherwise, put the schematic on the question

How about pinMode (analogOutPin, OUTPUT); ?


HC-06 Bluetooth module and slow communication I'm communicating from an Android command line Bluetooth app interface to my Arduino. The Arduino is using a HC-06 Bluetooth module. The Arduino is supposed to receive this data and act accordingly.

However the Arduino seems to be missing bytes or just be plain slow most of the time. When testing from the computers serial connection it all works fine.

What's my issue?

There are a few things that may be causing your issues:

The HC-06 may be a cheap knock off and may not perform to the level that you expect.
There could be an intermittent wiring fault or loose connection.
The signal strength may be causing your issue - it just can't 'hear' your data.
The antenna on the HC-06 module might be compromised in some way resulting in the loss of signal.
The data rate (baud rate) may be too high.
Your code may have blocking functions or delays that is causing you to miss the data.
The Android app may have bugs in it.
The Arduino program may have bugs in it.


Arduino communicate with PC? I'm pretty sure that this is the right forum to ask this question, but if it's not just lmk.

I am trying to create an auto clicker that is as hidden as possible for a computer engineering HID unit project.

What I have created so far (it works) is an Arduino being sent serial data via a C++ application that when receives a  '@' character triggers the auto clicker code and a '#' to stop the clicking. I showed my teacher and he said this is too basic as it's just simply a serial data sending application, but he likes the autoclicking idea.

I had a few ideas but I don't know how I would make them work. All I am trying to do is while a keyboard or mouse button the arduino sends mouse clicks.

TLDR; Is there a way that I can communicate keyboard or mouse events from the mouse/keyboard directly to the Arduino whilst still working normally on the computer itself, or maybe even something less discrete like making a device driver?

I suck at coding btw so I will most likely need someone I know to help me code it.

I think want you to look at this function SetWindowsHookEx on Windows.  It lets you grab any mouse of keyboard input and don something,  The input still follows the normal route, you just get notified about it.

I used this function to hook the 4th and 5th buttons on my mouse to start and stop media player, so when people pestered me at work I could pause my tunes.

MSDN - SetWindowsHookEx function

StackOverflow - Example that might work

We can't help you with the getting of a mouse button or keyboard button state in Windows. That is about as far outside the scope of this site as you can get.

However the emulating of a mouse so that the Arduino sends mouse click events we can help with.

To do that you will need to get an Arduino that is based around a chip that can directly speak USB - that means an ATMega32U4 based board, such as the Arduino Leonardo.

These boards have the Mouse object by default, which you can use to send clicks:

void setup() {
    Mouse.begin();
}

void loop() {
    Mouse.click(MOUSE_LEFT);
    delay(100);
}

How you start and stop the clicking is up to you - maybe send a simple instruction through serial will be the simplest way. You will need an application on Windows that captures the required events from your keyboard or mouse and sends whatever signal you decide on to the Arduino.


Connect a button to bluetooth board and comunicate with Android I want to create a small device, just a button that sends its status to an Android application through Bluetooth.

I bought a Bluno Beetle, but the information it exposes to Bluetooth cannot be modified from Arduino code, so I have no way to send the button status to the Android App, rookie mistake I guess.

Could you please tell me which model of arduino+bluetooth should I purchase to do this ?

For your project you can buy cheap Arduino Nano, or even Mini(programmer needed). For BT module buy HM10. It's cheap and it supports Bluetooth Low Energy.


Arduino serial communication synchronisation i am trying to send data via Labview to my arduino board using serial communication.My problem is that the arduino reads only the first byte of sent data then when i change it ,it doesn't react.
For example when i start the communication i send '0' to arduino.I sees it.but while it is running i send '1' but it doesn't behave accordingly to it.
I noticed also that the board 'sees' sometime the new value after a random period of time.

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

char data = 'F';

void loop()
{
    data = Serial.read();
    delay(50);

    if (data == '0')
    {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
    if (data == '1')
    {
        digitalWrite(13, HIGH);
        delay(4000);
        digitalWrite(13, LOW);
        delay(4000);
    }

    data = '4';
}

I suspect you problem stems from the use of delay's in your code. for example,

if (data=='1')
 {
  digitalWrite(13,HIGH);
  delay(4000);
  digitalWrite(13,LOW);
  delay(4000);
 }

Those delays prevent any computations from happening for 4 seconds each. Your arduino will not read another character after it sees a '1' for 8 seconds. If you send too much data in that 8 seconds to fit in the serial buffer, the extra characters are lost.

The behavior you seem to want will require separating the code that reads serial from the code that runs the output, and making sure neither section ever stops execution with delays. Your blinks will need to be timed with something else, like frequent comparisons against the current time with millis()

JUST add the part ~
This flushes the serial buffer, which aids in error free data receiving. No need to implement the millis() protocol as you want the led to be active for that time so you do not want any data to enter the system, neither you are using interrupts service.

Serial.readString();


SIM808 module: GSM location command (AT+CIPGSMLOC=1,1) giving wrong value after execution of sending message command (AT+CMGS=+91xxxxxxxx) I wrote the code that if an interrupt is generated, get GSM location and send a  message.

The first time the interrupt is generated, I got the correct GSM location using AT+CIPGSMLOC=1,1 and successfully sent a message using the AT+CMGS=+91xxxxxxxxcommand.

But the next time an interrupt was generated, AT+CIPGSMLOC=1,1 gave a wrong location. When I commented out the code to send a message, on every interrupt generated I am getting the correct GSM location. So it seems like the problem is occurring after sending a message. But I have no clue what exactly is going wrong. Following is my code.

Note: on restarting the module, I'm again getting the correct location the first time, before sending a message.

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  while (!Serial) {
  }
  // initialize the pushbutton pin as an input:
  pinMode(sensorPin, INPUT);
  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

/////////***GSM RESPONSE***///////////
String DisplayGSMResponse() {
  if(mySerial.available()) {
    String gsm_input="";
    while(mySerial.available()) {
      gsm_input+= (char)mySerial.read();
    }
    gsm_input.trim();
    delay(1000);
    Serial.println(gsm_input);
    return gsm_input;
  }
}

void SendMessage(String mobNum,String Location) {
  Serial.println("Sending message..");
  mySerial.println("AT+CMGF=1");
  //Sets the GSM Module in Text Mode
  delay(2000);
  // Delay of 1000 milli seconds or 1 second
  DisplayGSMResponse();
  mySerial.println("AT+CMGS=\""+mobNum+"\"\r");
  // mobile Number
  delay(4000);
  DisplayGSMResponse();
  cleanBuffer();
  mySerial.print("test");
  // The SMS text you want to send
  delay(100);
  mySerial.println((char)26);
  // ASCII code of CTRL+Z
  delay(8000);
  DisplayGSMResponse();
}

void gprsInit() {
  if (isGPRSInit) {
    return;
  }
  Serial.println("GPRS INITIALIZING");
  mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=3,1,\"APN\",\"INTERNET\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=1,1");
  delay(8000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=2,1");
  delay(2000);
  DisplayGSMResponse();
  isGPRSInit = true;
}

void gprsterm() {
  mySerial.println("AT+SAPBR=0,1");
  delay(1000);
  DisplayGSMResponse();
  isGPRSInit = false;
}

String getGPS() {
  Serial.println("GETTING GPS LOCATION");
  String loc = "";
  String location = "";
  mySerial.println("AT+CIPGSMLOC=1,1");
  delay(3000);
  loc = DisplayGSMResponse();
  return location;
}

void loop() {
  if (buttonState == 1) {
    detachInterrupt(0);
    gprsInit();
    location = getGPS();
    SendMessage(mobileNumber, location);
    gprsterm();
    Serial.println("location = " + location);
    buttonState = 0;
    location = "";
    attachInterrupt(0, pin_ISR, FALLING );
  }
}

void pin_ISR() {
  buttonState = 1;
  Serial.println("interrupt");
}

EDIT: added gprsterm function.

Note: I removed the interrupt and called the code inside the loop function twice. The first time I got a correct result. The second time a wrong result. So it seems like the interrupt is not be causing the problem.

EDIT2:
One interesting thing I found is that at my home it is showing correct results every time, but in the office it is showing a wrong location on second location call i.e after the SMS was sent and we get the GSM location using AT+CIPGSMLOC=1,1.

It might be due to the command giving the nearest cell tower location. And for sending SMS it might be shifting to a different cell tower depending on your network. This could maybe be easily checked using a different cell provider or as you said its working at your home so I believe I am correct in assuming this is the answer

Serial.println("location = " + location);

I think in upper line you should remove + sign from the code.


SoftwareSerial with ESP8266 I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i programmatically send particular AT commands there is no response.
For eg:
I type AT in serial monitor I get OK
But if i send the following through SoftwareSerial pins

mySerial.println("AT");

there is no response.

Can anyone tell what will be the solution as to how to send AT commands explicitly.

The sketch is

#include<SoftWareSerial.h>

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

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
  delay(100);
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
}//setup

void loop()  {
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
  while (Serial.available()>0 ) {
    mySerial.write(Serial.read());
    delay(100);
  }
}//loop

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.

I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.

Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.

If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.

I found, for example, that the AT+CWJAP (join access point) command takes quite a while, like 10 seconds or so.

Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.

If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. OK, ERROR etc.).

The ESP8266 needs 115200 baud.

The example didn't run clean in my case until I increased the baud rate for the Arduino<->Computer (USB) communication to 115200 baud as well. With 115200 on mySerial and 9600 on USB, an AT request of mine did not return an OK in most cases.


IDE will not open in Windows 10 I have loaded the Arduino IDE on Windows 10 32-bit on a 64-bit machine. This is my kids' laptop so they don't have admin privileges but, I installed it with admin privileges.

I have restarted the laptop, but the IDE does not start when I try to open it.  I am not signed is as administrator.

Any assistance would be greatly appreciated.

OK.  I figured out it needs to run as administrator.

Thanks for your consideration though.


ESP8266 not working properly It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.

You can see the connections in the following picture:

The code I run is the following one:

#include <SoftwareSerial.h>
SoftwareSerial BT1(3, 2); // RX | TX

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

void loop()
{
    String B= ".";
    if (BT1.available())
    {
        char c = BT1.read();
        Serial.print(c);
    }
    if (Serial.available())
    {
        char c = Serial.read();
        BT1.print(c);
    }
}

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.

EDIT: I think power supply is 3.3V

SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

[Edited to be less accusational, which was not the original intent]

[Update]

Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).

Step 1: Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.

Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.

Click Here for Necessary At Commands


Pilot the the reset line by two input I have two input signal that when activated have to restart the ardiuno board so I have to connect them to the RESET pin. As you know the arduino board have only one RESET pin so I can't connect both to the same pin.
I think that a good idea is a circuit that takes the two inputs and activate the RESTART pin when one of the two is active.
Have you any idea to solve that problem?

Thank you.

Just use diode logic.

The resistor is probably not needed because the Arduino has an internal pullup resistor.

This assumes that the two reset inputs are active low

simulate this circuit – Schematic created using CircuitLab

What you want is an AND gate (e.g., 74HC08, which contains 4 AND gates).

An AND gate is a chip which sets its output HIGH when both inputs to it are HIGH.

Symbolically it looks like:

simulate this circuit – Schematic created using CircuitLab

This, of course, is assuming that both your reset signals are active low - that is, they are normally in the HIGH state, but when they want to reset the board they go LOW.

You can do the same thing with three transistors.  Two transistors in series make a NAND gate (like an AND gate but the output is inverted), and a third makes a NOT gate to invert the output:

simulate this circuit

Note that R4 is optional, since the RESET pin already has a 10KΩ pullup resistor in it.


MQTT broker and Arduino + Sensors NRF24L01 I am newbie, I have never used MQTT before, so I have some questions.
Here is my topology.

I have several sensors (Arduino Pro Mini + NRF24L01) and main server/handler(Arduino Mega + Ethernet Shield or ESP module) to receive/send messages to/from sensor nodes, so all network is build on NRF24L01 (NRF24 Mesh library). But I need to be able to communicate with all these sensors from outside over the internet. Previously I implemented simple socket communication.
I have recently discovered MQTT protocol and it is awesome. I want to implement communication between main server and outside world using it.

What part of my topology should implement broker in? I think it should be on the main server (Arduino Mega) but again communication between main server/master server is implemented via NRF24L01 modules and custom protocol.
Or in my case is better to use HTTP communication with master server?

Please explain this topic and suggest how to implement this correctly in my case.

The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.

A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.

Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.

Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.

Cheers!

You can use a Raspberry Pi as your MQTT server and you can also connect a nRF24L01+ module.


RedBearLab Wifi Mini I am trying to make a program using 'Energia'

  Energia is based on the latest and greatest Arduino IDE modified for TI Launchpad & RedBearLab development boards.

and RedBearLab Wifi Mini v1.0.

Every time I upload a program, even with the standard Arduino 'Blink' example, it resets my board and I need to manually click the RESET button on the board.

I have all the drivers and add-ons installed correctly. How do I fix that?
This is what it shows on the console when I upload a program.

Using HID to reset for RedBearLab board
Opening \\.\COM10
Getting storage list
Bootloader Version: 4
Silicon version ES1.32 or higher
Bootloader version is 2, 1, 4, 0
It's a CC3200 device: PG1.33 or higher
Switch UART pinmux to APPS
Switch to NWP bootloader complete
Load common boot command for PG1.33 or higher
Bootloader version is 2, 0, 4, 0
BlockSize is 4096, number of blocks is 16
erasing 13 blocks starting from  0
erasing file "/sys/mcuimg.bin"
deleting file "/sys/mcuimg.bin"
erase file completed
Downloading file "/sys/mcuimg.bin" with size 2936
.Download complete

I think it always will if the redbear is the type of board that has very little memory and only runs one program at given time.  It resets to run the new program in my humble opinion.  Your mileage may vary.


GET the first result in HTTP request I have a String content="" and if I put an HTTP request like this:

client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

the output I get is:

 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

The little parser I created is this:

while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the String content?

Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action_id":35"?
If both are true then your solution is simple.

First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.

But if the above is not what you needed then I am afraid you cannot get only the first response, because that has to do with the server itself.

Here is a solution, do try it.

I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.


How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable? How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?

Android devices usually don't have a USB host: they expect to be connected to some smarter device like your computer. Same goes with Arduino.
For this reason Arduino made the Mega ADK (that means Accessory Development Kit).

Mega ADK and Due act as USB hosts and can be connected directly to your Android phone. If you already have a board, another option is to get a USB host shield to add USB host capababilities.

Your sketch will tell the phone what kind of accessory application it is and your phone will download the appropriate application from the store.

There is a book about connecting Arduino to Android.

You can connect Android and Arduino with usb and use the easy tool App inventor 2 for android

Did you try this new application : https://play.google.com/store/apps/details?id=bp.usbbridge.appinvDemo and full version : https://play.google.com/store/apps/details?id=bp.usbbridge.appinv

Find Videos about Explications : USB OTG Bridge Serial UART for APP Inventor 2 and ARDUBLOCK on youtube


How to make 1 second delay more accurate? I have written two (1 second) delay programs.

The first program as follows:

void setup()
{
Serial.begin(9600);
TCCR1A = 0;
TCCR1B |= (1<<CS12);
TCCR1B &= ~(1<<CS11);
TCCR1B &= ~(1<<CS10);
TCNT1 = 3036;
TIMSK1 |= (1<<TOIE1);
}

ISR(TIMER1_OVF_vect)
{
  Serial.println(millis());
  TCNT1 = 3036;
}
void loop()
{
}

Whose output is as follows:

999  // 1 sec
1999 // 2 sec
3000
3999
5000
6000
7001
8000
9000
10001
.
.
.
58012
59013
60013
61012
62013 //60 sec

It has an error of around 13 ms at 1 minute and at 1 hour it will be 780 ms and in one day it will be around 19 seconds.

The second program is as follows:

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

void loop() {
  Serial.println(millis());
  delay(1000);
}

Whose output is near about as same as the first one's.

Is there any way to decrease the error and make it more precise? So that I can use it in my Arduino based stopwatch?

Majenko is perfectly right: you cannot expect much accuracy from an
Arduino clocked by a ceramic resonator. Typical drift is of the order of
1,000 ppm, and is affected by temperature and aging. You can,
however, get a delay which is pretty close to the CPU's idea of one
second. In other words, you can get something that is really close to a
perfect period of 16,000,000 CPU cycles. If that is what you want,
your best bet is to use a timer.

In your overflow ISR, you wrote:

  Serial.println(millis());

There are two issues here. The first is the use of Serial.println()
within an ISR. This should normally avoided: since Serial relies on
interrupts, using it with interrupts disabled can lock your program if
you ever fill the output buffer. In this particular instance, it happens
to be safe, because at this rate you are never going to fill the output
buffer anyway. However, while it can be OK to do that in a small test
program like yours, I would advise you against doing it in production
code.

The other issue is the use of millis(). This function does not provide
true millisecond resolution: it is a counter that is updated every
1024 µs. Every now a then it is updated by 2 ms at once in
order to compensate for the drift. Thus, you should think of millis()
as being good to within ±2 ms. If you need anything better, use
micros().

  TCNT1 = 3036;

This should be avoided. Dispatching an interrupt takes time, and this
time depends on whether there is already an interrupt handler (or other
critical section) running. If the timer happens to increment after the
interrupt fires but before you have time to execute the line above, then
you miss a timer tic. It has been suggested to you to move this line
before the Serial.println(). That would certainly reduce the risk, but
it will not completely prevent it.

The right thing to do is to never reset a timer if you want it to have
time continuity. Instead, set it to CTC mode (clear timer on compare
match) and let it reset itself when it reaches a value of your choosing.
In this case, you would have it repeatedly count from 0 to 62,499
instead of from 3,036 to 65,535.

Here is a modified version of your program illustrating the points
above:

void setup()
{
    Serial.begin(9600);
    TCCR1A = 0;            // undo the Arduino's timer configuration
    TCCR1B = 0;            // ditto
    TCNT1  = 0;            // reset timer
    OCR1A  = 62500 - 1;    // period = 62500 clock tics
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS12);    // clock at F_CPU/256
    TIMSK1 = _BV(OCIE1A);  // interrupt on output compare A
}

ISR(TIMER1_COMPA_vect)
{
    // OK in test code, don't do this in production code.
    Serial.println(micros());
}

void loop(){}

The output is as follows;

1000048
2000048
3000048
...
58000048
59000048
60000048  // 60 seconds

Use micros() vs millis() and blink without delay time tracking as Jot described. Results will have much less drift. And for better results go with a board that uses a crystal instead of a resonator as mentioned.


Atmega328P-PU: Programmer is not responding Few days ago, I built my own custom Arduino on the breadboard. It is built according to tutorial on http://www.crash-bang.com/resource/breadboard-arduino/. The Atmega328P-PU is already burned with the Arduino bootloader with simple blink sketch.

For the programmer, I decided to use the Arduino USB2Serial. Again, it is connected as shown on crash-bang site. Problem is I get this error when uploading a different sketch:

avrdude -Cavrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:build244630154737317489.tmp/sketch_may23a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "build244630154737317489.tmp/sketch_may23a.cpp.hex"
avrdude: writing flash (450 bytes):

Writing | avrdude: stk500_recv(): programmer is not responding

Most of the time I do not even get to this point and just end up with something like:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf5

What I have done so far:

I already tried to reset Arduino just before uploading the sketch.
According to the avrdude, bootloader is fine.
Reinstalled drivers, Arduino IDE
Changed the USB cable and connected it to another USB slot
Burned new bootloader using ArduinoISP

Thank you for help.

I've read the tutorial at the crash-bang website and found two issues with it. The first issue is minor and probably won't fix your upload issue.

Step 3 says to connect +ve rail –> AVCC (pin 20) and +ve rail –> AREF (pin 21). You can leave those pins not connected. A really awesome guy named Julian ILETT has a video on youtube showing a homemade Arduino using the bare minimum connections needed. https://www.youtube.com/watch?v=sNIMCdVOHOM.

The second issue with the tutorial is in Step 5, "Connect the DTR pin of the FTDI, via a 0.1uF capacitor to pin1 on the ATmega.". A lot of people claim this works, but it doesn't work for everyone. It doesn't work for me and I have 2 of the identical FTDI programmers used in the tutorial. If you watch Julian's video starting at 12:48, you will see that he had trouble uploading a sketch using the DTR / 0.1uf capacitor method. He is using a different USB to TTL device but I have one of the identical devices he was using and the 0.1uf cap method doesn't work for me.

The solution to the upload issue is to use a switch to reset the Atmega328P-PU. Like the tutorial says, use a 10k ohm resistor connected to +5V and pin 1 of the Atmega328P. Now connect a one terminal of a N.O. momentary switch to ground and the other to pin 1 of the Atmega328P. To upload your sketch, click the upload button on the Arduino IDE window. As soon as the Debug window says "Binary Sketch Size…", press the reset button and hold it down for 1/2 a second then release.

I've just joined arduino.stackexchange.com a week ago so my answer may be a bit late. Hopefully this helps people in the future.

"Step 3 says to connect +ve rail –> AVCC (pin 20) and +ve rail –> AREF (pin 21). You can leave those pins not connected. "

+ve rail should not be connected to Aref. The +ve rail will connect via the internal operation of the ADC mux.

AVCC and both Gnds should be connected per the datasheet:
5.2.7. AVCC
AVCC is the supply voltage pin for the A/D Converter, PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used.

28.2.
AVCC must not differ more than ±0.3V from VCC.... Optionally, AVCC or an internal 1.1V reference voltage may be connected to the AREF pin by writing
to the REFSn bits in the ADMUX Register. The internal voltage reference must be decoupled by an external capacitor at the AREF pin to improve noise immunity.

If you connect Aref to the +ve rail externally, and then select the internal reference, things can go bad.

FTDT thru 0.1uF cap to Reset, with 10K pullup, and reverse biased diode to VCC, works for me in plenty of designs.  Not sure why it does not work in all cases. The diode dissipates any spike on the Reset line to keep the chip from thinking high voltage programming mode is being started.


SIM808 module restarting repeatedly I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.

Use a 5A power supply and that should solve the problem.

I have never tried it but "super capacitors" might work, providing the extra power when its needed, it depends how long you need the 3A for.

I too faced the same problem and solved it.

Just use a 3.3V logic converter or a 3.3V interface, as the 5V causes the device to restart.


delay(time); vs if(millis()-previous>time); and drift Going through an old project, I had code on two Arduino Due that looked like this

void loop()
{
  foo();
  delay(time);
}

taking to heart the majority of literature on using delay(); I recoded this as

void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously

My question is twofold:

Why would if(millis()-PrevTime>time) cause more drift than
    delay(time)?
Is there a way to prevent this drift without going back to delay(time)?

There's one important thing that you need to remember when working with time on an Arudino of any form:

Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.

The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.

For instance, take the following:

if (millis() - last > interval) {
    doSomething();
    last = millis();
}

The variable last will be the time the routine triggered *plus the time doSomething took to run. So say interval is 100, and doSomething takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.

So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):

uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

Now the time that doSomething() takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for more that 100ms having passed - and that means 101ms or more.  Instead you should use >=:

uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: "as long as nothing else happens in your loop"...

What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.

if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.

Before you had drift. Now you have jitter.

your code is correct.

the issue you run into is with millis(): it will under-count slightly (the maximum under-count is just shy of 1ms, per invocation).

the solution is with finer ticks, like micros() - but that will also under-count slightly.


Arduino UNO not working? Recently I assembled my Shapeoko machine, we used Grbl shield with an Uno for the same.

For 1-2 weeks everything worked perfectly then once when I tried to work the machine, the serial communication was not working. I tried to replace the 16 MHz oscillator because I thought the problem might be with the oscillator since the LEDs were not blinking but they were lighting up.

Maybe the 5v regulator? Hard to say without the symptoms.


Read temperature (DS18B20) with the ATTiny85 I'm trying to read the temperature of a DS18B20 with my ATTiny85 - but I'm getting rubbish data :D

I should have gotten ~22 degrees, but I'm getting 129! I followed this tutorial i found here, but maybe there is something funky with the ATTiny85?

I would suggest it has to be the clock speed or memory. Whilst you can program the ATTiny85 with the Arduino IDE, it will take up quite a lot of its flash memory. There is a thread on the Arduino form here which might help pinpointing the issue.

One solution is to write it in AVR-C but I don't know if there is an easy way (or a library) for the 1-wire. I think you'll have to do it with the 1-Wire library alone as the DallasTemperature library is too much for the 8Kb of memory you have to play with.

Please feedback any breakthroughs you make as this is a nice project, the ATTiny is an awesome little chip...


How to determine what resistor value to use for LED strip I'm trying to use an ESP8266 powered by my computer through USB cable to control a WS2812B LED strip. I've read online that you're supposed to put a resistor before the data channel to help prevent noise but I'm struggling to figure out what the resistor value should be.
I've figured out so far that the LED strip will use a MAXIMUM of 25.8W and that the Vin pin that is powering the LED strip is outputting 5V. I also plan on putting a 470uF capacitor across power and ground.

It seems like people generally just use a resistor around 300 - 500 ohms so I'll just use a 500 ohm resistor. Answer found on another thread. And here as well.

Strips of LEDs like WS2812Bs need a high current 5V supply, with NO current limiting resistor.
You'll need a very high current regulated 5V supply, and would probably be better off using a separate 5V supply for the Arduino and the LED strip so you don't get large voltage fluctuations in the power to the Arduino as the LEDs turn on and off. If you do you a single power supply for both, you should use a power supply with extra capacity. I'd suggest at least a 30W supply. And yeah, you should probably have a filter capacitor on the 5V rail right at the Arduino.
Edit:
Were you asking about a resistor on the power line, or one on the data pin?


Arduino SIM5320e HTTP GET request to 000webhost.com Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com

I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.

MY DOMAIN: wastedb.000webhostapp.com

But if I try to send a request to dweet.io, it works as expected.

I am using a modified version of Adafruit_FONA library and will post the code snippet and response from serial monitor below.

Here are the parameters that I used for the WORKING GET request:

Host Address: www.dweet.io

Host: dweet.io

Response from Serial monitor for dweet.io (working):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

As we can see, the Arduino received a JSON response from the website.

Here are the parameters that I used for the NOT WORKING GET request:

Host Address: wastedb.000webhostapp.com

Host: wastedb.000webhostapp.com

Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.

EDIT: It is working now. The only solution that worked for me is to find another hosting site.

Try just using IP address for the Host line instead. I did the same thing for POST and it works fine for me.

Example:

Host: 13.xxx.xx.xx


Quick Programming Check/Review I've been racking my head trying to start programming in a library organized method. My code works, but the translation and split to a .h and .cpp file is riddled with errors.

It's gotta be stupidly simple all I'm asking for is a review:

Header File

# ifndef _INITIALIZE_H
#define _INITIALIZE_H

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

//-Extra Includes-
#include <config.h> //Provides baud...
#include <SSC32.h>

#define STANDARD 0
#define DEBUG    1
#define VIRTUAL  2

class Initialize {
    private:
        int _mode;
    public:
        Initialize();
        void begin();

};

#endif

associated .cpp file:

//Comments
#include <Initialize.h>
SSC32 SSC;

Initialize::Initialize()
{
    _mode = STANDARD;
}

void Initialize::begin()
{
    SSC.begin(baud);
    if(Serial.available() > 0){
        if(sscReturn == 1){
            Serial.println("ver");
        }
    }
}

The error from the compiler:

D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp: In member function 'void Initialize::begin()':
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:12: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected primary-expression before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected ';' before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected ')' before ';' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:17: error: expected primary-expression before '==' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:21: error: expected ';' before ')' token
Failed compiling libraries

Sorry, figured it out.

In the "config.h" file I was pulling, I had a
 #define = 18;

instead of a #define 18

I might be wrong, but the compiler stopped complaining


TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307 Been working on this project for some time now, like title states when I un-comment setSyncProvider(RTC.get) in the setup the program fails to get any of the Alarm.timerOnce to run.

I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.

#include <Wire.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

//#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
//byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
  prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
  ignPin = 7,     //  Igniter output pin D7
  solPin = 8,     //  Solenoid output pin D8
  genPin = 9,     //  Generator output pin D9
  tonePin = 11,   //  Tone output pin D11
  ligPin = 3,     //  Light sense pin A3
  intPin = 3,     //  Interupt pin D3 runs double bang

  runTime = 20,   //  minutes to run for

  state = 0;      //  state of operation

bool operate = false, // True if within operating time
   timeIsSet = false; // true if time till next opperation is set
double cur;

void setup() {
  Wire.begin();
  pinMode(13,OUTPUT);
  pinMode(ignPin, OUTPUT);
  pinMode(solPin, OUTPUT);
  pinMode(genPin, OUTPUT);
  Serial.begin(9600);
  //setSyncProvider(RTC.get);  //******************************************
  Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
  Alarm.alarmRepeat(20,0,0,OffAlarm);
  tone(tonePin, 31, 1000);
  randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

  OnAlarm();
}

void loop() {
  if ((analogRead(ligPin) > 30) && operate == true)
  {
    if (timeIsSet == false)
    {
      tone(tonePin, 58, 500);
      int randm = random(27,36);
      Alarm.timerOnce(randm,operation);
      Serial.println(randm);
      timeIsSet = true;
    }
  }
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

void operation(){
  tone(tonePin, 100, 1000);
  Alarm.timerOnce(12,after20m);
  digitalWrite(genPin, HIGH);
}

void after20m(){
  digitalWrite(genPin, LOW);
  Alarm.timerOnce(5,after5s);
  digitalWrite(solPin, HIGH);
  tone(tonePin, 494, 1000);
  timeIsSet = false;
}

void after5s(){
  tone(tonePin, 200, 1000);
  digitalWrite(solPin, LOW);
  Alarm.timerOnce(1,after1s);
}

void after1s()
{
  digitalWrite(ignPin, HIGH);
  Alarm.delay(500);
  digitalWrite(ignPin, LOW);
}

void OnAlarm() {
  operate = true;
}

void OffAlarm() {
  operate = false;
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  //Serial.print(operate);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Problem existed in the TimeAlarms library,

Q: How many alarms can be created?
A: Up to six alarms can be scheduled.
The number of alarms can be changed in the TimeAlarms header file (set by the constant
dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

so how I fixed it was to edit #define dtNBR_ALARMS 6  // max is 255 to #define dtNBR_ALARMS 14   // max is 255 in the TimeAlarms.h file.


Read Comma Separated String I have a string that looks like this "10.00,20.00,-50.00," in which these are angle values and they have 2 decimals and can be negative. I want to separate them into 3 separate floats. Here is my current code in which I use sscanf. All I get is 0.00 and have no idea why. Any help is truly appreciated.
String recvString = "10.00,20.00,-50.00,";
float r,p,y;

void setup() {
  Serial.begin(9600);
  Serial.println(r);
  int result = sscanf(recvString.c_str(), "%f,%f,%f,", &r, &p ,&y);
  Serial.println(r);
}

void loop() {}

The AVR implementation of sscanf() does not support parsing floating point numbers, thus you only get zeros out of it. You can't use the %f specifier with it. You need to convert these numbers by yourself with functions like atof() or similar.
Splitting a string into parts can be done many ways. You could use sscanf() to split up the string parts and then use something like atof() to actually convert to float. Or you use strtok() for splitting (see my answer to this question). Or you use one of the many other options, that you get, when googling for something like "Arduino split string" or "Arduino split c string".
Note: Using the String class in Arduino is easy for beginners, but not a good practice (dynamic allocation, heap fragmentation). Look at Majenkos blog for more information about that. Since you already used a function for C-strings, I would suggest moving completely to C-strings (which are basically only an array of char).

Use the indexOf function to find index then use the subString to get values like this:
String recvString = "10.00,20.00,50.00";
float r, p, y;

void setup() {
  Serial.begin(9600);
  //Serial.println(r);
  //recvString.toCharArray(s, recvString.length() + 1);
  //int result = sscanf(recvString.c_str(), "%f,%f,%f,", &r, &p ,&y);
  int i1 = recvString.indexOf(',');
  int i2 = recvString.indexOf(',', i1+1);
  Serial.println(i1);
  Serial.println(i2);

  String firstValue = recvString.substring(0, i1);
  String secondValue = recvString.substring(i1 + 1, i2);
  String thirdValue = recvString.substring(i2 + 1);

  Serial.println(firstValue);
  Serial.println(secondValue);
  Serial.println(thirdValue);

}

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

}


How do I convert a float into char*? Asked this question on Electrical Engineering Stack Exchange and was directed here:

Pretty self explanatory; how would I go about converting a float into a char*? I have code in which the float 'resistance' is constantly being updated. I would like to be able to update the variable 'result' to take the value of 'resistance'. Here is some of the code, in case it helps:

const char * result = "";
float resistance = 2.5;

result = resistance; //This bit (obviously) doesn't work

Thanks for your help!

There is a function in the standard Arduino library called dtostrf(). I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

char result[8]; // Buffer big enough for 7-character float
dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!

This will give result values like "  1.23" and " -1.23" and "123456789" (without the quotes). Note the last example - it won't truncate the number if it's too large, and that 10- character result (don't forget the final NUL) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).

Basically you are trying to convert a 4-byte variable (float) to a 4-byte string (char variables are 1-byte sized).
More info about Arduino data types here http://playground.arduino.cc/Code/DatatypePractices

You can try the answers to these questions  https://stackoverflow.com/questions/18270974/how-to-convert-a-float-to-a-4-byte-char-in-c

https://stackoverflow.com/questions/24420246/c-function-to-convert-float-to-byte-array

I admit that I am confused by the use of const char * result = ""; in your example.

The "const" keyword makes the variable as "read-only" and therefore you can't modify it.
https://www.arduino.cc/en/Reference/Const

Edit: Unfortunately I don't have an Arduino device right now to test myself the above solutions


Motor not switching with 2N3904 I have a small motor, it powers fine from the 3V3 and GND output of the arduino nano ble 33. However I need to be able to switch it on and off. My first attempt was to use an output pin, but that doesn't supply enough power. I'm trying to use a 2N3904 transistor (my first time attempting to use one, so sorry if I've done something stupid). I've tried wiring it as follows, but no luck:

Is this possible, or do I need something more substantial like a reed switch?

1st : you have to put an appropriate resistor between the output of your arduino and transistor Base pin

2nd : you have to connect you motor and biased transistor to >>>> a suitable power supply (which has enough current (Amps) on it's output)

you can use this circuit instead of yours :

3rd : don't forget to use the diode in the schematic; it protects transistors from you motor coil's spikes you can use 1n4147 ( it depends on the size of your motor but i think, it works for you ( i wasn't successful to take a look at your motor and it's specifications )

4th : ignore the number of transistor, you can use your transistor (2N3904) instead of it

5th :NOTICE : this circuit has a problem, you have to connect appropriate power supply and replace "arduino 5 volts" by the + of your power supply in this circuit schematic

good luck


Where do avrdude parameters get defined in the Arduino IDE? I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with avrdude.

I found this in boards.txt:

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

There is this in platform.txt:

# AVR Uploader/Programmers tools
# ------------------------------

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.cmd.path={path}/bin/avrdude
tools.avrdude.config.path={path}/etc/avrdude.conf

tools.avrdude.upload.params.verbose=-v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m

This line is particularly interesting:

tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

It seems like these variables are corresponding:

{cmd.path} --> tools.avrdude.cmd.path
{config.path} --> tools.avrdude.config.path
{upload.verbose} --> tools.avrdude.upload.params.verbose
{build.mcu} --> uno.build.mcu
{upload.protocol} --> uno.upload.protocol
{serial.port} --> ?
{upload.speed} --> uno.upload.speed
{build.path} --> ?
{build.project_name} --> ?

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.

Where are these variables explicitly defined in the Arduino library? (e.g. {runtime.tools.avrdude.path}, {path}, {cmd.path} ....) Or how do they get defined by IDE?

There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line

tools.avrdude.path={runtime.tools.avrdude.path}

as (in linux in windows replace ${xx} by %xx%)

set tools.avrdude.path ${runtime.tools.avrdude.path}

and the board.txt for the selected board like

uno.bootloader.tool=avrdude

as

set bootloader.tool avrdude

The arduino ide uses the following string to know the upload command environment variable

tools.${bootloader.tool}.upload.pattern

This way it knows the command to upload is

"{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.

So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.

A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.

IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.

Note I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.

The Arduino library is about what runs on the target, while the "IDE" (not sure if it can still be called IDE, as now they try to do also command line) is about everything else.

But my impression is that if you are ready to ask these sort of question, you could consider dropping the IDE and moving to a more standard Makefile approach. Or Maybe Eclipse, where you still have the IDE, but you can define everything in a more standard way.

The Arduino approach is good to get people with little experienced started, but after a while one started to feel its limitations.


Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.” I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

My Code:

//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }

Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).

You can confirm your connections and baud rate with:
EspSerial.println("AT");
You should receive `OK' in reply.

As shown in the Fritzing diagram, you have connected the ESP8266 to the Mega's Serial1 pins (18 and 19), but in the program, you try to interact with Serial2 (pins 16 an 17). For this to work, your wiring and your program must match.


Only return button state once in X amount of time? I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
  }
}

Would spit out something like this with a single quick press of the button:

PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

But what I want is for a single button press to just return PASSED! once for that single button press.

To avoid this problem you can use a boolean variable as a flag that permit to enter inside the if only once.

bool flag = true;

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW && flag) {
    Serial.println("PASSED!");
    flag = false;
  }
}

You can add a delay.

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
    delay(1000);
  }
}