text:
Arduino Square Wave Phase Shift by 270 degrees
I am using this code to generate a square wave with Arduino and shift it by 90 and 180 degrees. However, this code is not able to shift it to 270 degrees. Could you please suggest how may I modify the code so that it supports a 270 degrees square wave phase shift operation.
void setup() {
  pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
  pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B
  // Both outputs in toggle mode
  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
  // CTC Waveform Generation Mode
  // TOP=ICR1
  // Note clock is left off for now
  TCCR1B = _BV( WGM13) | _BV( WGM12);
  OCR1A = 0;    // First output is the base, it always toggles at 0
}
// prescaler of 1 will get us 8MHz - 488Hz
// User a higher prescaler for lower freqncies

#define PRESCALER 1
#define PRESCALER_BITS 0x01
#define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

// Output phase shifted wave forms on Arduino Pins 9 & 10
// freq = freqnecy in Hertz (  122 < freq <8000000 )
// shift = phase shift in degrees ( 0 <= shift < 180 )
// Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC
/// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.
int setWaveforms( unsigned long freq , int shift ) {
  // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.
  unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave
  ICR1 = clocks_per_toggle;
  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision
  OCR1B= offset_clocks;
  // Turn on timer now if is was not already on
  // Clock source = clkio/1 (no prescaling)
  // Note: you could use a prescaller here for lower freqnencies
  TCCR1B |= _BV( CS10 );
}
// Demo by cycling through some phase shifts at 50Khz
void loop() {
  setWaveforms( 40000 , 0 );
  delay(1000);
  setWaveforms( 40000 , 90 );
  delay(1000);
  setWaveforms( 40000 , 180 );
  delay(1000);
}

The answer is in the code you posted, in a comment: “To do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC”.

I tried to understand that statement and it doesn't make much sense to me. Could you please help me modify the code or understand the statement? @EdgarBonet

Not your own code?

No, I took it from here: https://electronics.stackexchange.com/questions/174656/avr-arduino-output-2-pwm-waveforms-with-90-degree-phase-shift?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

It sounds like it means "Invert the waveform, and do a 90 degree shift".

setting the FOC bit forces an output compare once regardless of OCR value, effectively causing a 'premature' toggle. This inverts the waveform in the long run. FOC are the last 2 bits (6, 7) in the TCCRB register, FOCxA/B by macro

@mystery could you please advice on how can I modify the code to be able to do the operation. Sorry I am really new in this space

The Arduino can only shift across a range of 180 degrees in CTC-mode using a 16 bit Timer. If you shift one channel to 90 degrees (other OCR set to 1, not zero) and then add a logic-inverter, you'll get the equivalent of 270 degrees as mentioned by Edgar Bonet.
As for using FOC (forced output compare), Edgar B. is again correct. It's possible to preset a channel as inverted, then perform the shift with an OCR set for 90 degrees -- you won't need an extra logic inverter. But this method is not for someone new. You'll want an O-Scope handy to make it work (and some time to study FOC and CTC mode-12).
I think it easier to use a single section from a 7404 hex-inverter to flip your 90 degree shifted waveform to 270.
Search for "Phase Shift Square Waves" and you'll find a VIDEO (as of 2022) for an example project that uses FOC tactics to create runtime-adjustable phase shifts on an Arduino. Perhaps you'll see a way to make an easy code change for the flipped-phase you want...
FWIW stockvu


text:
Problem with interpretting and using the IMU data
I am using MPU6050 IMU for getting accelerometer and gyro data. I could read the data using the code from the I2Cdev library here, but the problem I have is that I can't use this data in a meaningful manner. As an example I want to define the motion of an object in x,y,z axis using accelerometer data. Although I get a set of values, I can't understand how to use it.
If I could convert these values to ms-2 units, I hope I would be able to achieve this
Could you provide me some advice, code or reference to work on this?
I also tried the code here to get the raw values.

Assuming it is moderately linear, you should be able to get a rough idea of the scale by aligning the device at rest until two axis read near zero and one reads a large non-zero value, which should correspond to 9.8 m/s/s gravitational acceleration.  Flipping it over would let you determine any offset error on that axis.

You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.
http://www.varesano.net/projects/hardware/FreeIMU
see demo video in which the on screen data mirror physical motion of the sensor
http://www.youtube.com/watch?feature=player_embedded&v=rFvX3vZJHTQ
hope this helps

John, thank you very much for the information. I went through some of the projects they have provided. I can get the yaw pitch roll readings too. But the issue I am having is really in the accelerometer readings. I want to map a path using the accelerometer data. Can you suggest me a way for that?

By using your said software (in original post) or getting it from inside ofthe freeimu (find out where in the code does this task), you can read the raw accelerometer data in x, y, z. You need to read the device data sheet to learn a) the range setting (says plus and minus 2g) b) the data representation. Says, for a particular device (you need specific for your chip from data sheet), reading is plus and minus 1023 for 2g. That is, for 2g, it is +1023. for minus 2g, it is -1024. That, use the scale factor to get g reading in ms-2.

see video https://www.youtube.com/watch?v=C7JQ7Rpwn2k for excellent teaching, 200k viewing, by the factory engineer. 3. What do you want to do with "map a path". In theory, ms-2 gives speed and distance by integration. In practice, it is highly error (thousands % over short time) as explained in the later part of the video. 4. Practical solution use odometer (physical wheel touching ground or camera as optical odometer) to get speed and distance and freeIMU to get roll pitch and yaw (heading and direction of movement). Hope it helps

Best data accuracy is by 9 DOF (degree of freedom) using accelerometer , gyro and magnetic compass and a software to do data fusion, like freeimu. Add GPS, for best long term error.  commercial air liners uses even more multiple sensors and data fusion.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Interrupts for analog inputs
I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?
I actually want to analogRead() a potentiometer inside the ISR.
This is my code so far, http://pastebin.com/ykpp78GB
And my circuit is just two potentiometers connected to pin A0 and A1.

You can use a pin change interrupt on an analog input, and you can read an analog input inside an ISR. But using the same pin both as an interrupt trigger and an analog input makes little sense, unless you are using the analog comparator (not pin change) interrupt. You should start by telling us what you actually want to achieve.

It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.
It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.
In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.

What I want to do is to analogRead() a pot inside the ISR. I have an Arduino UNO.

Well, I'm thinking that maybe I should read those analog values inside a timer interrupt. Considering I'm using some delays inside the loop() function.

authors: Димо Гърдевски

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Why doesn't pin 9 blink?
I use simple LED blinking code on an Arduino MEGA 2560. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?
My code:
// Set up the DATA direction
void setup()
{
  for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);
}

// The main program
void loop()
{
  for(int j=2; j<=10; j++)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }

  for(int j=9; j>=2; j--)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }
}

And the circuit is:

It looks like your main problem is the loop in setup():
for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);

This will call pinMode() with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to i<=9.
However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely must have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.

yes... hears the problem.. got it... :)

I'd just like to point out that the standard is i < 10, not i<=9.

@TheGuywithTheHat I wouldn't say it's 'standard' in any real sense. It's simply more common to use < because it clearly shows the number of iterations over a 0-based range. In this case though, the loop counter isn't 0-based so the conditional makes no difference.


text:
Why can't the Atmel ATtiny family delay over a minute?
I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:
int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

When I assign onPeriod and offPeriod to be 1 * 1000 (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.
For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).
I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.
Am I doing something wrong here?
It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:
int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}

The type for the delay value is an "unsigned long" according to this. But I don't think that's your problem.  Could the Delay code not be compatible with your processor?  Also, it is likely you can call delay(1000) in a loop driven by the number of seconds (for instance 6) you wish to delay.

The delay() library works with times below a minute (I haven't tested exactly what but I've done <10 seconds, and then went to test 60 seconds, the latter of which does not work). I would think that if the library isn't compatible, any calls to it won't work, but maybe it's a small bug with it and my MCU?
I just tried unsigned long and it doesn't work. Let me try throwing a delay(1000) in a function.

Looks like throwing it into a delay function works. I'm thinking maybe it's an overflow issue now.

Overflow issue seems weird, because unsigned long is 32-bit which is way more than the 15 * 60 * 1000 = 900000 I require.

This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.
See my page about Integer arithmetic and overflow.
To excerpt from that:

On the Arduino (Uno) platform, what do you think will be printed here?
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Did you guess:
60000
86400
500

Nope!
It prints:
-5536
20864
0

This is because of integer arithmetic. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.
And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.
For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.
Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).
Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

Solution
First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Now we get:
60000
86400
500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.
The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an int and a long will result in the int being promoted to a long (regardless of whether it appears first in the expression or not). However if an int is being added to another int, it will not promote them to a long, even though the result may not fit into an int.

Thanks for all the information. I was suspecting overflow but have forgotten all the C++ I've learned in university since it's been so long. I had remembered arithmetic is done on largest type, but oversight made me blind to the fact that all the individual numbers are INT. You mentioned at the beginning of your answer "on the Arduino (Uno) platform", but from the diction used in your answer, this seems to be general C++ behaviour. Any reason to keep thinking it's for Arduino only?

The distinction is because on this platform an int is 16 bits. If you try the same code on your PC an int will probably be 32 bits or even 64 bits. If you have come from programming PCs the problem is still there, but masked by the larger integer size. 16-bit ints would be used on other platforms with small processors (8-bit processors) - probably such as PIC etc.

My copy of Kernighan and Ritchie (The C Programming Language) mentions on page 9: The range of both int and float depends on the machine you are using; 16-bit ints, which lie between -32768 and +32767, are common, as are 32-bit ints.

These are the problem lines:
long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

Even though long should hold the result, integer operations in C++ are still done in int by default. And on AVR int is 16 bits. The fix is to tell the compiler what size the intermediate result should be:
long offPeriod = 1 * 60L * 1000;
long onPeriod = 1 * 60L * 1000;

According to AVR libC the implementation of the delay function has a limited value range that varies with the F_CPU macro definition. So your delaySeconds(int) function is the only solution.

He is using delay, not _delay_ms


text:
Get USB host controller serial number or ID using Teensy or other HID devices
I have a Teensy board and would like to know if there's a way to get a serial number (or any other kind of ID that is preferably unique) of the host controller that I plug my Teensy into. E.g. can I get any unique identification numbers of my Macbook's USB controller when I plug my Teensy into it? C/C++ code examples for Teensy would be highly appreciated.

There's no such information necessarily provided.  You can have custom software on the host collect and offer information, and you may be able to unreliably fingerprint the type/version host operating system by small details of its behavior.

What could I potentially receive about the host controller at all?

Without custom code on the host, almost nothing, except seeing how it habitually configures and uses your device.

Nothing in the USB spec requires the host to provide any sort of identification to connecting devices. The standard way of implementing what you want consists in writing a custom driver which communicates the necessary information to the device. If installing a custom driver is not an option, all you can do is try to detect the OS by observing what it does during the enumeration process. Such identification will not be reliable (enumeration process can change after an OS update) and by no means unique.
Note that if your goal is to make sure the host is trusted, a simple ID will not be enough as it can be easily spoofed. You'll have to implement some sort of authentication scheme, e.g. challenge-respose.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Multiple Stepper Motors in One Shield?

I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?

Please clarify: what shield model are you using, what stepper motors do you intend to use?

Is the picture related to question? I can see one 4-wire stepper motor only.

The board shown looks like it can handle two steppers, as a stepper requires two H bridges (if bipolar, or at least their low side switches if unipolar), so could replace the two PMDC motors requiring one each.

Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).
But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)


text:
Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment
Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?

That won't be easy. You'll have to break one open, and see what's inside. Maybe a thermistor, which you could connect to an arduino analog pin, but you'd have to manually calibrate it.

I actually found one here: https://blog.safaribooksonline.com/2013/07/25/an-arduino-powered-bbq-thermometer/ do you think I can do these? I am not really in to electronics just need this for my biorector for thesis.

If that unit also contains a thermistor, you can indeed follow that guide. But you'd have to open it first to find out.

Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.
Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.


text:
Help with socketIO Example
I'd like to get a TCP based connection from an arduino to a node.JS server. I found an example, I've tried to run it but its throwing the errors below, would appreciate any help.
Error Messages
    Arduino: 1.6.6 Hourly Build 2015/09/24 05:43 (Windows 7), Board: "Arduino/Genuino Uno"
WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
socketio.ino: In function 'void hello(Client&, const char*)':

socketio:19: error: expected unqualified-id before '.' token

socketio.ino: In function 'void setup()':

socketio:38: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

socketio:39: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

exit status 1
expected unqualified-id before '.' token

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Arduino Code
    #include
    #include
#include <ArduinoJson.h>
#include <SocketIOClient.h>

EthernetClient ethClient;
SocketIOClient client(ethClient);

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "192.168.100.40";
int port = 3000;

// Socket.io "hello" EVENT handler
void hello(Client& client, char const * data) {
    Serial.print("[hello] event happening: ");
    Serial.println(data);
    Client.emit("goodbye", "Arduino here, goodbye!");
}

// Socket.io "goodbye" EVENT handler
void goodbye(Client& client, char const * data) {
    Serial.print("[goodbye] event happening: ");
    Serial.println(data);
    Serial.println("That is all.");
}

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

    if(!client.connect(hostname, port)) {
        Serial.println(F("Not connected."));
    }

    //Event hanlders
    client.setEventHandler("hello", hello);
    client.setEventHandler("goodbye", goodbye);

    //Say hello to the server
    client.emit("hello", "Arduino here, hello!");
}

void loop() {
    client.monitor();
}

SocketIO.h
/*
    socket.io-arduino-client: a Socket.IO client for the Arduino

    Based on Bill Roy's Arduino Socket.IO Client (which is based on
    Kevin Rohling's Arduino WebSocket Client) with event handling by
    @dantaex

    Copyright 2014 Quentin Pigné

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SocketIOClient_H
#define SocketIOClient_H

#include <Arduino.h>
#include <Client.h>
#include <SPI.h>

#include <ArduinoJson.h>

#include "HashMap.h"

//Length of static data buffers
#define DATA_BUFFER_LEN 200
#define SID_LEN 24

//Max size of the HashTable
#define HASH_SIZE 20

class SocketIOClient {
    public:
        SocketIOClient(Client& client);
        //Public connection methods
        bool connect(const char* hostname, int port = 80, const char* resource = "socket.io", const char* nsp = "/");
        //Public event handling methods
        void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));
        //Public data emitting methods
        void emit(const char* event, const char* data);
        //Monitoring for incoming data
        void monitor();

    private:
        //Connection attributes
        Client& client;
        char* hostname;
        int port;
        char* resource;
        char* nsp;
        char sid[SID_LEN];
        //Incoming data reading attributes
        char databuffer[DATA_BUFFER_LEN];
        char* dataptr;
        //Event handling attributes
        int nbEvent;
        static HashType<const char*, void(*)(Client& client, JsonArray& data)> hashRawArray[HASH_SIZE];
        static HashMap<const char*, void(*)(Client& client, JsonArray& data)> eventHandlers;

        //Private incoming data reading methods
        bool waitForInput();
        void eatHeader();
        void readInput();
};

#endif

Where is your code?

Hi @NickGammon, ive added the code.

bump    anyone?

Make your char * parameters const char *.

Did his suggestion fix it? If so, please mark the answer as the correct solution.

Hi @NickGammon, no I'm still having issues, updated the errors in my original post.


text:
Help with a function that accepts different parameter types
I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.
char PingTime[6] = "3ms";
char PingText[60] = "ping reply blah blah";
float humidity = "40.56";
int DigialPin = 0;

PrintXMLTag(cl,"pingtime",PingTime);
PrintXMLTag(cl,"PingText",PingText);
PrintXMLTag(cl,"humidity",humidity);
PrintXMLTag(cl,"DigialPin",DigialPin);

void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val)
{
  char tmp [100];
  StrClear(tmp,100);

  // If val type is float ----------------------
  int d1 = val; // Get the integer part
  float f2 = val - d1; // Get fractional part
  int d2 = trunc(f2 * 10000);// Turn into integer
  sprintf(tmp,"<%s>%d.%02d</%s>\n",tag,d1,d2,tag);
  // end float

  // If val type is string ----------------------

  // If val type is int ----------------------

  // If val type is char ----------------------

  cl.print(tmp);
}

Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.
void PrintXMLTag(EthernetClient cl, char* tag,  char* val)
{
  char tmp [100];
  sprintf(tmp,"<%s>%s</%s>\n",tag,val,tag);
  cl.print(tmp);
  StrClear(tmp,100);
}

The simplest way is certainly to overload the PrintXMLTag() function by declaring it as many times as possible types for val variable; function overloading is perfectly supported in C++ 5not in pure C though).

Thanks all for the replies. Ive opted with simply converting the variables into type char before sending to the xml function. Seems to have done the trick, not sure why I didn't think of this prior to posting the question?

try using this example instead of iostream you can use iostream.h too..
#include <iostream>
using namespace std;

int sum (int a, int b)
{
  return a+b;
}

double sum (double a, double b)
{
  return a+b;
}

int main ()
{
  cout << sum (10,20) << '\n';
  cout << sum (1.0,1.5) << '\n';
  return 0;
}

If your goal is really to print the value from XML, you don't need to worry about types, as long as you believe the XML to be correctly formed. The value in the XML file is already character string just print it. The converting from string to variable (sprintf()) and back to string (Serial.print() or printf()) is unnecessary.

take a look at: http://www.cplusplus.com/doc/tutorial/functions2/
template <typename SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}

This appears to be what you want.

Not quite, because most types will need to be special-cased.


text:
Output to LCD is sometimes shifted to the side
I have an Arduino Uno connected to a LCD. When I try to write to it using the LCD library and the following sketch, it will keep shifting the output around, sometimes drastically.
The sketch:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 10, 11, 9, 8, 7, 6, 5, 4, 3, 2);

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

void loop ()
{
  lcd.clear ();
  lcd.home ();

  for (int i = 0; i < 2; i++)
  {
    for (int j = 0; j < 16; j++)
    {
      lcd.setCursor (j, i);
      lcd.print ("s");
    }
  }

  delay (1000);
}

You would expect it to print

SSSSSSSSSSSSSSSS
SSSSSSSSSSSSSSSS

But it will often print

SSSSSSSSSSSSSSS
SSSSSSSSSSSSSSS

As in, it skips the first line. And, occasionally, it will even print like this:

SSSSSSSSSSS
SSSSSSSSSSS

Is it the LCD's fault, or might there be something wrong with the way it is connected?
EDIT:
It is a common Hitachi HD44780-compatible LCD.
EDIT 2:
 Hopefully it is correctly wired up.

I don't understand that wiring.  What is that regulator doing over to the right, and what is it supposed to be wired to? Where is the power for the LCD coming from?  Where is the contrast trimmer?

@Majenko The regulator was meant to represent the power. I used that mistakenly (first time using Fritzing. Or doing schematics for that matter). I am not sure how to show the power coming in the breadboard view... What do you mean by contrast trimmer? AFAIK those are all the wire coming out of the LCD.

@Majenko Hopefully the new image makes more sense

Is that actually what you're powering the LCD from? Or are you really using a regulated 5V supply?

It is a regulated 5V supply. I just don't know how to show that in Fritzing

Ok, one last question before I conclude that I don't have a clue what's happening with your system:  What wire are you using to wire it all up? Type / length / connections, etc.

Er, dunno, standard wires? Like these: https://i.sstatic.net/y7eu5.jpg

Ok, I have exhausted all the ideas I have at the moment as to why it may not communicate 100%.  It may be down to the LCD possibly - try introducing small delays into your loop - maybe a ms or so after the setCursor - or try doing the setCursor twice in a row.

I had already tried that. It is most likely the LCD's fault, I just wanted to check for any oversight on my parts. Thanks for the help though.

Try running some example programs. If they work as expected, your LCD is not at fault. Try to use the example wiring (12, 11, 5, 4, 3, 2) and don't forget the contrast POT. Why aren't you supplying power (+5V) from the Arduino itself?

Why do all those lcd.setCursor? You cleared the screen, the library should write each letter next to the previous one.

@MKII Printing the same character over and over ("S", in your case) may be hiding some quirk of the LCD. Change the output line to lcd.print ((char) 65 + (32 * i) + j); . This will print capital letters (from 'A') on the top line and the lowercase equivalents on the bottom - that way you'll know immediately if it's shifting left or cuttting off the right.


text:
Calculating time between Serial events
I am trying to calculate time between two serial events. Using Arduino UNO R3 with 16MHz default clock source.
I am using timer 1 with pre-scale of 64 to get time per one count = 4000ns. This i am choosing at random without any specific reason.
Sending character 'o' to start the timer and character 'k' to stop it and hence calculate the time in between. The ISR routine calculates how much times the timer overflows.
The code is:
    unsigned int t;
unsigned int c;
char r;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;

  TIMSK1 = (1<<TOIE1);//enable timer overflow interrupt
  sei();
  //SREG = (1<<8);//enable global inteerupt
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()>0)
  {
    r=Serial.read();
  if(r=='o')
  {
    TCNT1=0;
    TCCR1B |= (1<<CS11)|(1<<CS10);//64 pre-scale & start
    Serial.println(TCNT1);
  }
  else if(r=='k')
  {
    Serial.println(TCNT1);
    TCCR1B = 0;//stop timer
    t=TCNT1+(c*65536);
    t=t*(4*10^(-9));
    Serial.print("overflows = ");
    Serial.println(c);
    Serial.print("time = ");
    Serial.println(t);
    c=0;
    t=0;
  }
  }
}//loop

ISR(TIMER1_OVF_vect)
{
  c++;
}//isr

But, on serial monitor only the block of if(Serial.read()=='o').... is executing. The flow does not enter the second else if block.
What is wrong with this code? How long does the Serial buffer hold its vale ?
EDIT: I got the code working for checking for 'k'. But the timer value it calculates is very less than compared to what it should be. Is anything wrong with the timer settings. Setting CS10=CS11=1 gets the pre-scaler value to 64.
Hence, the time for 1 count should be = 1/(16MHz/64) .
Is anything wrong with this?

You can get more accurate timing by connecting a GPIO to the RX line. Then use a pin change interrupt to capture the start bit of both serial characters. I don't have any code example, sorry

I'd read the result of Serial.read() to a variable and check this variable, because otherwise the first Serial.read() will have already read the 'k'. I reckon you can remove the Serial.available() check.
void loop() {
    int chr = Serial.read();
    if(chr=='o')
    {
        TCNT1=0;
        TCCR1B |= (1<<CS11)|(1<<CS10);//64 pre-scale & start
    }
    else if(chr=='k')
    {
        t=TCNT1;
        TCCR1B = 0;//stop timer
        t=t+(c*65536);
        c=0;
        Serial.println(t);
        t=0;
    }
}//loop

Yes. thank you. Just found that Serial.read() clears the Serial receive buffer. Thats why it will never enter the else if block. I will try with a separate variable as you said.


text:
Optimizing code for ATtiny10
I'm trying to squeeze code onto an ATtiny10, but I'm just not getting there. I'm using 1060 bytes and only have space for 1024 bytes.
The code is simple enough; I need to read a button pin. If high it needs to pick a random value and that causes one of two random LEDs on the PCB to turn on for two seconds. Is there a way to optimize this code to work on this IC?
int buttonState = 0;

void setup() {
    pinMode(3, INPUT);
}

void loop() {
    buttonState = digitalRead(3);
    if (buttonState == HIGH) {
        bool ranNum=random(0,1);
        if(ranNum == 0) {
            digitalWrite(0, HIGH);
        }
        else {
            digitalWrite(1, HIGH);
        }
        delay(2000);
        digitalWrite(1, LOW);
        digitalWrite(2, LOW);
    }
}

I'm not sure what the compiler would optimize out in this situation, but have you tried using direct port manipulation instead of using digitalWrite(), digitalRead() and pinMode(). When not using this the compiler might optimize these functions out.

Not sure if it helps byte wise but you can change if(ranNum == 0) {             digitalWrite(0, HIGH);         }         else {             digitalWrite(1, HIGH);         } into digitalWrite(ranNum == 0 ? 0 : 1, HIGH);

I'm unsure about how direct port forwarding works i'll look up some tutorials thanks for the suggestion. The ternary operator doesnt seem to save any bytes good suggestion tho

digitalWrite(ranNum & 1, HIGH) -- also use a uint8_t instead of an int.

also also random() is a wrapper around rand() which probably wastes bytes. Use rand() & 1 to get a random 1 or 0.

On such a small device, I would get rid of the Arduino core and program at the avr-libc level.

@EdgarBonet On such a small device I'd get rid of avr-libc and program it in assembly...

Please take a look at an article I wrote some time ago regarding AVR code optimizations.

Are your pins and pinMode()s correct?  pinMode(3,INPUT) seems like the default, and the random HIGHs on 0&1 seem inconsistent with the LOWS on  1&2

How big is the code if you replace random by a constant?

Related: Optimizing code to use less flash memory and SRAM and What can I do if I run out of flash memory or SRAM?

Aren't the LEDs quite weak? Isn't the default I/O input? The code as presented here would seem to switch the internal pull-up resistors on and off (as none of the I/O pins are set up as output). Switching the internal pull-up resistors on and off will produce some light on the LEDs, but not very much. The current through them will only be on the order of 0.1 mA (100 µA). Or is there some kind of driver circuit that makes up for it?

As I stated in a comment, this device would be too small for me to
consider programming it using an Arduino core. I would rather stick with
the avr-libc and direct port manipulation:
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB = _BV(PB0)   // PB0 as output
         | _BV(PB1);  // PB1 as output
    for (;;) {
        loop_until_bit_is_set(PINB, PB3);  // wait for PB3 high
        if (rand() & 1)
            PORTB |= _BV(PB1);  // PB1 high
        else
            PORTB |= _BV(PB0);  // PB0 high
        _delay_ms(2000);
        PORTB &= ~_BV(PB0);     // PB0 low
        PORTB &= ~_BV(PB1);     // PB1 low
    }
}

This is plain C, but I expect it to be accepted by the Arduino IDE as a
valid .ino file. I tried compiling it like this:
avr-gcc -mmcu=attiny10 -Os -Wall -Wextra -DF_CPU=8000000 prog.c -o prog.elf

And it resulted in a program that uses 660 bytes of flash. Most of that
is in the implementation of rand() and its dependencies
(multiplication and division routines).

If rand() is really taking up that much space, you could probably save a lot of it by using a more compact RNG. Here's one of my favorites, which should run fine on an ATTiny and probably generate better randomness too.

You could even use the LSB noise of the ADC to generate a random number. Works pretty well from my experience.

If the button is pressed by a human and your clock is high enough (MHz range), you can use a trick and get rid of the RNG.
You can replace it with a free running counter like this:
unsigned char count = 0;

void loop() {

    count += 1;

    buttonState = digitalRead(3);

    if (buttonState == HIGH) {
        if( (count & 1) == 0) {
            digitalWrite(0, HIGH);
        }
        else {
            digitalWrite(1, HIGH);
        }
        delay(2000);
        digitalWrite(1, LOW);
        digitalWrite(2, LOW);
    }
}

You have count incremented every ⪝10 us (depending on your clock speed, attiny executes one instruction per cycle), so when the user pushes the button, the counter will be sampled.
Note: I assumed loop() is all what the microcontroller has to do, and it's constantly called.

That's better randomness than an RNG.  Since delay and its clock is running, you could use its TCNT0 or TCNT0L instead of count and get faster counting at zero cost.

Neither loop() nor digitalWrite() may not even be called. The underlying GCC compiler is pretty good at inlining, optimising them down to single assembly instructions.

What does it matter, if the function was inlined or not in this context? At the end the function code gets executed, regardless if the compiler inlined it or not.

@next-hack: Function calls are instructions which use up valuable flash space (and need time to execute).

@Michael, I think I quite know that... Still, what's the connection between Redy000's answer and the fact that loop() or DigitalWrite() might be inlined, or implemented as an actual branch ?

Are you sure the pins are correct?
Maybe use a smaller random number generator per https://arduino.stackexchange.com/a/18092/6628 ?
static uint8_t lfsr = 0x01;
const byte LFSR_MASK = 0x8e;

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(3, INPUT);
}
void loop() {
  //      int buttonState = digitalRead(3);
  if (digitalRead(3)) {
    if (generateNoise()) {
      digitalWrite(0, HIGH);
    }
    else {
      digitalWrite(1, HIGH);
    }
    //delay(2000)
    //for (int i = 31; i; i--)_delay_us(64516);
    _delay_ms(2000);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
  }
}

uint8_t generateNoise() {
  // Return 1 bit of noise using a Galois Linear Feedback Shift Register
  // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs

  if (lfsr & 1) {
    lfsr =  (lfsr >> 1) ^ LFSR_MASK ;
    return (1);
  }
  else         {
    lfsr >>= 1;
    return (0);
  }
}

The RNG didn't help as much as changing the much-disparaged delay.

Your linear feedback register seems indeed quite efficient space-wise. Plugging it into my implementation of the program reduced its size from 660 to 142 bytes!

Great. You could probably afford go to a 16 or 32 bit random state variable for richer randomness.

An 8-bit chip requires multiple instructions for processing 16 bit. Changing ints to either uint8_t or int8_t will save code.
Depending on compiler optimization, replacing
if ( (count & 1) == 0) {
    digitalWrite(0, HIGH);
}
else {
    digitalWrite(1, HIGH);
}

with
digitalWrite((count & 1), HIGH);

could save bytes.

I tried the optimization you suggest on an Uno. It saved two bytes.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using timer0 on Arduino Uno
I am trying to find a simple timer0 interrupt example, but none of those work. Neither this code which I tried to run:
boolean toggle0 =0;

void setup() {
pinMode(8, OUTPUT);
  cli();

  // Set timer1 interrupt at 1 Hz
  TCCR1A = 0; // Set entire TCCR1A register to 0
  TCCR1B = 0; // Same for TCCR1B
  TCNT1  = 0; // Initialize counter value to 0

  // Set compare match register for 1 Hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)

  // Turn on CTC mode
  TCCR1B |= (1 << WGM12);

  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);

  // Enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER0_COMPA_vect){  // Change the 0 to 1 for timer1 and 2 for timer2
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

void loop() {

}

What am I doing wrong?

You know you don't need to use interrupts for this. You can instruct the timer to change the output pin when the counter overflow or reaches OCR1A. You do this with the COM1A1 COM1A0 bit in the TCCR1A register. Though you'd have to use pin 9 (or 10) instead of pin 8.

The main problem is you are using the wrong interrupt handler. You are setting up Timer1, but the interrupt handler is for Timer0:
boolean toggle0 = 0;

void setup() {
pinMode(8, OUTPUT);
  cli();
//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER1_COMPA_vect){  //change the 0 to 1 for timer1 and 2 for timer2
  toggle0 = !toggle0;
  digitalWrite(8, toggle0);
}

void loop() {

}

Thank you kindly, can you please update it to work on a timer0 intrerupt?

@adrya407 I wouldn't recommend it, as the Timer0 is used for millis(), delays and so on. If you change ticks from 1.024ms (overflow interrupt), to CTC with exactly 1s (compare match interrupt), then overflow will not work anymore at all.

Arduino timers are reserved for buid-in functions:
Timer0 is reserved fire a millisecond interrupt for the millisecond counter
Timer1 is reserved for measuring time passed since the last reboot
Timer2 is reserved for pwm timing
So, using these timers is not a good suggestion if you plan to use above options. For me, Timer0 seems a good choice, as microsecond timing is a bit of an overkill.
Here you may find your solution:
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers

On the UNO all three of these timers are involved in PWM timing. Where the claim about Timer1 come from?


text:
Programming Arduino via ICSP
I'm trying to programming Arduino Nano with another Arduino Nano via ICSP. I have a 6-pin cable directly connected to the ICSP's pin of the second board:
ICSP NANO ISP 1
pin1 pin2 pin3
pin4 pin5 pin6

ICSP NANO 2 (to be programmed)
pin1 pin2 pin3
pin4 pin5 pin6

I have correspondingly wired pin 1 (ICSP) of nano1 to pin 1 (ICSP) Nano 2, pin 2 (ICSP) of nano 1 to pin 2 (ICSP) Nano 2, etc.
I make this step before flashing: getting the Arduino ISP with example sketch ArduinoISP, plug off the Arduino ISP and attach the 6-pin cable to the ICSP port of the second board, plug Arduino ISP to the USB port, in the Tools menu select Arduino as ISP, load with external programmer, and fail...
This is the log:
avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM12
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         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 : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Errore durante il caricamento dello sketch
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Get yourself a cheap $2 USBASP off eBay. Save yourself the hassle.

You shouldn't connect the two reset pins of both nanos. Connect the reset of the target to pin 10 of the programmer. Also, you need to prevent the programming nano from being reset when the serial connection is opened.

I suggest you to try and read the Arduino page about ArduinoISP.
Particularly, you will notice that pins 11, 12, 13 and Vcc and GND are all common, BUT the reset pin is not common to both boards. So I suggest you to detach the pin 5 of ICSP from the ArduinoISP board and connect it to its pin 10. Or, if you prefer, connect
ISP - Target
+5V - +5V
GND - GND
11  - 11
12  - 12
13  - 13
10  - RST

Then try again

thanks, now im getting that `avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
Hardware Version: 4728160
Firmware Version: 0.4598883
Topcard         : STK502
Vtarget         : 1.8 V
Varef           : 0.0 V
Oscillator      : Off
SCK period      : 0.1 us
avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01`

Did you try to flash the ArduinoISP again, then connect the "slave" nano (remember, the pin RST on the slave should be connected to pin 10 on the master) without connecting the slave to the USB and then try to flash with external? If so, try to flash the bootloader (there should be a command in the menus like "flash bootloader", but I don't remember where

i miss the PIN 10 to connect to the RST pin , thanks again

@FrancescoValla Glad this fixed the issue


text:
Rename cu.usbserial-1410 on macOS
Is it possible to rename, e.g., cu.usbserial-1410 to something else?
I have to connect multiple Arduino's and right now the order is rather important.
Being able to set a fixed name would help a lot.

Someone on https://apple.stackexchange.com/ might have more chance of answering this. It's an OS X problem not an Arduino problem.

Depending on your application, can't you ask the Arduinos for their "name" to recognize them? Relying on the PC's names of the interfaces will only work to some degree.

@thebusybee yeah, I think I probably will do that so it also works on windows

Proposal:
Instead of trying to convince the PC's OS (be it macOS, Windows, or Linux) to use a fixed name for interfaces that connect specific Arduinos, add a identifying feature to your Arduino application. Then from the PC application ask each connected Arduino for its name to identify it.


text:
Esp8266 firmware update with uno "chip sync error"
I have an ESP8266-01. I followed the instructions on this
http://yaab-arduino.blogspot.com/2015/12/flashing-esp8266-firmware-arduino.html?m=1
exactly. When I start the firmware update the TX and RX pins blink rapidly along with the blue light on the ESP.
Then the terminal spits out "chip sync error" and disconnects.
I would like this to work because buying a ftdi cable isn't an option right now.

This error occurs due to a mismatch in Baud rates. So I suggest you try different baud rates, specifically 9600 and 115200 as these seem to be the most common....Gd Luck!!

Problem is......
In the ESP8266 Flash_Download_Tool_v3.6.1 The lowest setting available is 115200 baud

It's actually likely that the ESP isn't in flashing mode.- you did follow the points under Flash it! to the letter, right

I run the same problem too and took me countless hours to figure this error out. The problem seems the Baud rate starts at 115200 while the COM port is set to 9600. What I did is I checked the Device Manager and find the COM port, right clicked to properties and to the Port Settings Tab, I changed the Baud Rate to 115200 and flash the firmware again. And it works!

just after compilaion starts in the arduino ide , press and hold the flash button and then press the reset button , now release the reset button and finally release the flash button, this is how the esp goes into flash mode.this will work


text:
Errors seen whilst compiling with AdaFruit Motor Shield ("invalid library")
Whenever I compile a sketch, change the Tools > Board selection, or open/close Boards Manager/Library Manager I get the following message in the console:
> WARNING: Spurious .github folder in 'Adafruit Motor Shield library' library
> WARNING: Spurious .github folder in 'Adafruit Motor Shield V2 Library' library
>
>
> Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm

Arduino IDE 1.6.6 and higher are picky about what you have in your libraries folders. There are two general valid library formats, the old "pre-1.5" format and the newer 1.5 format, the specification of which is at https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification.
Any folder in any of the Arduino libraries folder that doesn't follow a valid library format will cause the "Invalid library" message. Common causes of this issue are:

Putting a sketch folder in the libraries folder. Libraries may
contain example sketches but a sketch by itself is not allowed.
Libraries that are in a subfolder, rather than the library folder
being in the root of the libraries folder as required.

Now lets look at your specific messages:
Invalid library found in C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master: C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master

By looking at the Adafruit-Motor-Shield-for-Arduino repository we see that it's not a library but the PCB design files for the shield and thus has no business being in the libraries folder. Please move it to a different location.
Invalid library found in C:\arduino-1.6.8\libraries\robotarm: C:\arduino-1.6.8\libraries\robotarm

Without being able to see what's in this folder I can't say exactly the problem. If you will provide a directory listing I could update this answer with specific directions. As it is now, that folder is doing you no good in the libraries folder.


text:
Arduino Uno R3 not working with Cytron shield GPS 53
My project is to find latitude and longitude of certain places. I am using an Arduino Uno R3 with a Cytron GPS 53 shield to get the position of places but, my device cannot run because COM4 already in use. How to fix this error?

Please read How do I ask a good question?. Please give a lot more details, like how you are connecting things. I don't see how COM4 in use is anything to do with a shield.

Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port.  The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).
The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.
If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).
Hopefully that should give you a start.


text:
Running quartz clock off an arduino
I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/
For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)
Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:
    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    void setup()
    {
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 9 to be an output output
    }

    void loop()
    {
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
    }

For this reason I have tried to merge it with the 1 wire clock project and got
const int a1  =  8;     //use digital I/O pin 8
const int a2  =  9;
const int tick1 = 1000;
const int tick2 = 50;

int cyclesPerSecond = 974;

//pins
int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
int pwmOut = 6; //pin 6

//timekeeping
int seconds = 0;
int masterClock = 0;//number of square waves

void setup()
{
attachInterrupt(clockInterrupt, clockCounter, RISING);
pinMode(a1,OUTPUT);   //set pin 8 to be an output output
pinMode(a2,OUTPUT);   //set pin 8 to be an output output

Serial.println(pwmOut);
analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
}

void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
masterClock ++; // with each clock rise add 1 to masterclock count
if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
{
seconds ++; // after one cycle add 1 second
masterClock = 0; //reset clock counter
}
}

void loop()
{
  if (seconds == 1){
   digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
   else if(seconds == 2)
   seconds = 0;
   digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
  }
}

However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

Tear out the resonator, put a 32kHz clock crystal in place, and tune the async timer to sidereal time.

The idea of using the Arduino's own PWM as a clock is completely misguided. The author of that instructable does not have a clue what he is talking about. Forget about that and just calibrate your millis() or, for better accuracy, use a proper watch crystal.

tick1 has a way to large value (1000), if it has to wait one second, and the do some other stuff, but it has to do this every second, it will fail. I also miss a way to prevent the first if from being called multiple times.

@EdgarBonet - actually it is you who are mistaken.  The idea is not really to use PWM, but to use the hardware timer behind the PWM, which is a very good idea indeed.

@ChrisStratton: Are we talking about the same instructable? This guy is using a PWM signal from pin 6, which is driven by the same hardware timer as the millis() interrupt. There is no way this can be more accurate than millis() itself, thus the whole technique serves no purpose at all. Ultimately, the accuracy of both millis() and the PWM is limited by the ceramic resonator clocking the Arduino, which is quite poor.

Before something like an Arduino Stack Exchange "Flame War" may
start between Chris Stratton and other I would say there's only "one hardware clock" on an Arduino Uno.

As I said in my comment, the idea of using the Arduino's own PWM as a
clock source is completely misguided. It will be no more accurate than
using millis() or micros(): both these functions and the PWM rely on
the same primary clock source, namely the ceramic resonator clocking the
chip.
Also, you should avoid using delay() for timekeeping. The time it
takes to run around the loop() is the sum of all your delays plus the
time needed to execute the actual instructions, which you do not know
accurately. It is far better to use either millis() or micros().
Here is a tentative sidereal clock code, not tested:
// Pins driving the clock.
const int a1 = 8;
const int a2 = 9;

// Length of one sidereal second in microseconds.
const unsigned long SIDEREAL_SECOND = 997270;

void setup()
{
    pinMode(a1, OUTPUT);
    pinMode(a2, OUTPUT);
}

void tick()
{
    static int activePin = a1;

    // Pulse the pin.
    digitalWrite(activePin, HIGH);
    delay(50);
    digitalWrite(activePin, LOW);

    // Next time use the other pin.
    if (activePin == a1) activePin = a2;
    else activePin = a1;
}

void loop()
{
    static unsigned long last_tick;
    if (micros() - last_tick >= SIDEREAL_SECOND) {
        tick();
        last_tick += SIDEREAL_SECOND;
    }
}

You can tune the speed of the clock by changing the constant
SIDEREAL_SECOND. I set the constant to the actual length of a sidereal
second, in microseconds, but you may find that the clock does not run
exactly at the correct speed. This is because the ceramic resonator
inside the Arduino is not very accurate. You can remove most of the
inaccuracy by calibration: measure how fast or slow it runs and change
the value of SIDEREAL_SECOND to compensate. You will still face some
residual inaccuracy owing to the fact that the resonator's frequency is
not very stable, and is highly temperature-dependent.
If you want to build a clock that has decent accuracy, your best bet is
to use a 32768 Hz quartz crystal, as suggested by Ignacio
Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a
“barebones Arduino”) to make a
24-hour analog wall
clock. You should be
able to easily adapt the code I published in that page to fit your
project.

Thank you for sharing your project. I made a Vetinari Clock using AS2, but mine is running a bit too fast. So I'll give your calibration method a try.

Bad idea, this will fail or at least momentarily misoperate in a little over an hour.  Unless you are going to use very large integers, you cannot use a mechanism which figures time from zero, but must do so incrementally.

@ChrisStratton: You are mistaken. Since micros() rolls over cleanly modulo 2^32, the rollover is not an issue.

I'm not 100% certain of what you are trying to do but I noticed a few bits in the code which don't look right to me.  For instance this function:
void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
  masterClock ++; // with each clock rise add 1 to masterclock count
  if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
  {
    seconds ++; // after one cycle add 1 second
    masterClock = 0; //reset clock counter
  }
}

This is causing a part of your inaccuracy.  You are incrementing the integer masterClock variable and then seeing if it is >= to a floating point value, the equals is not necessary and will almost never be true.  If the condition occurs then you increment seconds before setting masterClock to zero, losing any part of a second you had left over.
Looking at what others have said I would be inclined to take a different approach to this project rather than try and fix this code.

Writing another answer because I just had a completely different idea.
A standard option for keeping reasonably accurate time with an Arduino
is to use an RTC module. If possible, choose one based on the DS3231
rather than the DS1307, as the former has builtin temperature
compensation, which makes it significantly more accurate.
The RTC is typically used to provide the time over I2C in a broken-down
form: year, month, day, hour, minute and second. This is not really
convenient for a sidereal clock, as it would require complex conversions
to derive the sidereal time. However, most RTC modules have the option
to output a 32,768 Hz square wave. If you can feed this signal to
the digital pin 5 of your Arduino Uno, then you can use the
Timer/Counter 1 to count the cycles and raise an interrupt every
sidereal second, i.e. every 32,678.53 cycles of the RTC signal.
There is small issue with the above number not being an integer. One
could just round it to the nearest integer, which would make the clock
slow by about 14 ppm, or 1.2 s/day. This may not seem like a
large error, but the DS3231 is capable of much greater accuracy:
±2 ppm from 0°C to +40°C.
An elegant solution is to count the cycles internally using a 32-bit
fixed-point number, with 16 bits for the integer part and 16 bits for
the fractional part. On each timer interrupt, we compute what value the
timer should have on the next interrupt (variable next_count below),
simply by adding 32,678.53 to the previous value. Then we use the
integer part of the result (16 most significant bits) to program the
next interrupt. This way the interrupts will be spaced by either 32,678
or 32,679 signal periods, with the average being exactly the value we
need. This provides very high granularity, as our time unit is now
effectively 2−31 s ≈ 0.466 ns.
In the code below, the first three functions are left empty, as “an
exercise for the reader”. Or rather because they are dependent on the
specifics of the hardware setup. I am only showing the logic of using
the Timer 1 for getting an interrupt every sidereal second.
/*
 * RTC-based sidereal clock.
 *
 * Configure the RTC to output a 32,768 Hz square wave.
 * Feed this square wave to pin T1 = PD5 = digital 5.
 */

#include <avr/sleep.h>

static void setup_rtc()
{
    // Configure the RTC to output a 32,768 Hz square wave.
}

static void setup_clock_pins()
{
    // Configure the pins for driving the clock.
}

static void tick()
{
    // Advance the clock by one second.
}

/*
 * For better granularity, time is counted in units of 2^-16 cycles of
 * the 32768 Hz square wave (~ 0.47 ns), as a 32-bit unsigned integer.
 * Timer 1 holds the 16 most significant bits.
 */
const uint32_t SI_SECOND       = 32768UL << 16;
const uint32_t SIDEREAL_SECOND = 0.99726958 * SI_SECOND;

// Interrupt fired every sidereal second.
ISR(TIMER1_COMPA_vect)
{
    static uint32_t next_count;
    next_count += SIDEREAL_SECOND;
    OCR1A = next_count >> 16;  // use the 16 most significant bits
    tick();
}

void setup()
{
    // Configure Timer 1.
    TCCR1A = 0;            // normal counting mode
    TCCR1B = _BV(CS10)     // count rising edges of T1
           | _BV(CS11)     // ditto
           | _BV(CS12);    // ditto
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

    // Enable pullup on T1 = PD5.
    PORTD |= _BV(PD5);

    setup_rtc();
    setup_clock_pins();
}

void loop()
{
    sleep_mode();
}


text:
Prevent Switch case from not being complete
I got this program. It controls a refrigeration room using a ds1280 temperature probe.
The thing is, sometimes the probe reach 7.00°C then the refrigerattion cycle start (refrigeration cycle is on a switch case statment) and then the probe read 6.75. So the refrigeration don't complete its start and leaves part of the system in wrong mode.
How can I add some guard to ... once the switch case statment don't being interrupted by anything unless complete the on in this case or the off in other case.
Here are the most resembling parts of the code.
void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

Sorry for the horrible indentation... this thing paste like thath

Nope, you can use block controls to paste code correctly. I've cleaned up a bit the formatting, you can finish it up and add proper indentation.

I suggest you write (indented!) a simple representation of what you would like to do (the algorithm) in plain English.

Try to avoid complex test cases inside "if" tests, especially if they can have side effects and if you do use complex conditions, check that the operator precedence meets your expectations. But I would advise to avoid complex tests altogether.

Sorry the first time un here... Yes... Is a sistem drive by temperature.... The one secon to add switch statement... For say..  Tunr one fan then wait a second. . turn another fan... Wait a second. Turn compressor on.

The idea us simple... Yet challenguing to me ... If the temperature is 7 or higuer start refrigeración... If its 3 or lower .. Stop refrigerattion...if.. The temperature is un between. Start ventilation Machine..

Problems arises when... The  state Machine dont complete its tasks... So the variables arent initiated and for say.... Refrigerattion wont start again... - sad sad very sad case

Please edit your main post and put there the description. Btw why do you place all those dots? It makes reading harder.

The posted code is driven only by the refrigerationBegin, refrigerattion comOnTime  comOnDelay, variables, and the millis().  There is nothing temperature sensitive in this code.   If you don't want a prematurely terminated start or stop cycle, you might need to insert a "compOn  ==0" or "compOn ==6" test into the hidden code to prevent that from happening.

Sorry... The programa has a thermostar función thath stop and star refrigerattion according the temp. I dont post it because the whole code is too big.

Are you trying to control by temperature or by time?
(I'm finding the code hard to follow. There seem to be 2 copies of it, and the comments in turnOnCompressor() seem to contradict the function name. I also don't see any code that mentions temperature.)
If this is temperature controlled, you need a dead-band - a temperature range bounded by a high- and a low setpoint. If you have a single setpoint, the system will jitter as air-circulation and electrical noise make the temperature appear to alternate above and below setpoint. The turn-on setpoint needs to be higher than the turn-off setpoint. You'll need to experiment to find out how far apart they need to be for the system to be stable.


text:
Arduino Bluetooth Shield
A friend of mine bought two of these Bluetooth shields here. I have been trying to get the two Arduinos connected to each other through Bluetooth. I could not get it working myself but I found some code online here that I tried. The shields connect to each other (the lights on both turn red) but the I can't send data between them. Does anyone have any code that may works with these shields?


text:
Help choosing a servo motor
I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo".
The Links are:
Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773
Servo2: http://www.ebay.in/itm/251928442829?aff_source=Sok-Goog
My Problem is that I am confused with the name "Digital Servo". Its cheaper but I a afraid that will it work as normal.
Please help me.
Are both the same product, but with a different name?

Servos are digital by definition.  All you have there is two sellers that are selling the same product, but they are describing them slightly differently.  They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).
However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them.  That's about ¢5 or 3p.

On ebay I've seen stepper motors erroneously labelled as servos and real servos labelled as digital servos, to differentiate from the misnamed stepper ones. Usually the price is a good indicator of which is which, but comparing with similar products is the safest bet.


text:
Why is this returning the wrong answer?
Why does this print output -3? xpos can be any value.
void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);

}

What types are your variables declared as? (int, float, etc)

xPos and yPos are ints and pwm is currently float i tried int aswell, and its outputting 0 not -3 sorry, (xPos*255)/1023 outputs -3.

@user10936 Could you edit your question to include the setup() loop and the declarations of xPos, yPos, and pwm. There could be something there that you're overlooking.

Just swap the priority of the operations. So use pwm = xPos*255/1023; instead.

The problem is that (255/1023) is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:
pwm = xPos*(255.0f/1023.0f);

Is the f designator necessary? Without it does the compiler treat the calculation as doubles and then re-cast it to float or something? Also, is it not sufficient to add the decimal point to just the numerator or denominator? I know it works in 'regular C++ on a computer', but in an embedded environment would it bloat the program memory?

@chaaarlie2 Without the f designator, a C++ compiler would treat it as double during the calculation, which normally requires slightly more resources. Most Arduinos treat float and double the same though so it wouldn't necessarily make a practical difference. It's not usually a good idea to rely on platform quirks like that though.

@chaaarlie2 I would always put the f designator on both values, simply for consistency. The chances are that the compiler would be smart enough to convert the integer to floating-point at compile-time (rather than run-time), so it probably doesn't matter from a technical point-of-view.

I prefer the format pwm = xPos *  val1 / (float) val2; which works equally for hardcoded values, constants and variables.

The previous answer correctly suggested writing
pwm = xPos*(255.0f/1023.0f);

in place of the original form pwm = xPos*(255/1023);.  But because 255/1023 - 1/4 = -1/1364 which is fairly small (ie it differs by 1 part in 1364), just saying
pwm = xPos/4;

will usually give the correct result or nearly so.
Note, the following python program shows that this result is exact 514 times as xPos ranges from 0 to 1023, and is one too large 510 times, which for many processes being controlled by PWM signals is close enough.
#!/usr/bin/env python
c = [0]*8
for i in range(1024):
    vf = int(i*255.0/1023.0)
    vi = i/4
    d = vi-vf
    c[d+3] += 1
    #print '{:5} {:5} {:5} {:5}'.format(i, d, vi, vf)
print c


text:
Turn on a light when there is an input
I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.
LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.
Here is the code:
void setup()
{
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(8, INPUT);
}

void loop()
{
   bool on = digitalRead(8);
   if(on)
   {
     digitalWrite(4, HIGH);
   }
   else
   {
     digitalWrite(4, LOW);
   }
}

What am I doing wrong?

Use input with pullup on pin 8 and a button to ground (GND). See below:
const int ledPin = 4;
const int buttonPin = 8;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
   digitalWrite(ledPin, digitalRead(buttonPin));
}

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.

Thank you for your reply. It worked. But I still don't understand why my solution didn't work. Will you be able to explain?

See updated answer.


text:
I2C between Arduinos without Master
I am working on a library for some Arduinos that should talk between each other.
The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches.
So far everything works pretty nice but once a while everything gets stuck.
I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:
To make all Arduinos interchangeable I have no Master (Wire.begin()) in my I2C Bus.
I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.
Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

Slaves are just waiting for a Master to ask them something. If there is no Master no slave will ever do something. Note that I2C can have multiple masters on the same bus. So either do something with that, or have the Arduinos wait a certain time (e.g. based on the id), to see if there is a master, and if not assume the role of master themselves.

You have to have a master for an I2C bus to work.  Can't you allocate one of the dip switches to define the master?
Edit to be able to remove the downvote
Nick his answer seems to imply that you do not need masters but that is wrong.
What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right.
As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.

I was still investigating and found some, who had the same demands that I had: actively send data from many Arduinos to the central Arduino and not wait for the Master that pulls the information from the Slaves. Look here or there according to what they say, it is possible to setup I2C Arduinos without Master.
But my setup caused me headache. I changed the Concept and pull the data from the Slave. It only takes 2ms to pull from 10 Slaves that is fast enough

As shown in the answer below it is possible.

@jantje - I don't think the answer below says you can have a working I2C bus without a master, because you need a master to transmit.  I suppose as long as no one on the bus needs to transmit you don't need a master, but if there are no transmissions there isn't much need for the bus.

@matt - you are right. I can't remove the downvote yet (it states it is only 17 hours ago I voted :-( ) If I forget -> remind me.

Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

There is no master except during transmissions. Thus it is possible to rotate the job of master if you want. You would need some way of deciding when it was a particular board's turn to be master.
I have code here on my RS485 page about how you can set up a rolling master using Serial communications. The same basic idea could be used to make a rolling I2C master.

Hi Nick, thank you for your reply, I was hoping that you find this question once.

Hi Nick, thank you for your reply, I was hoping that you find this question once. I have read a lot about I2C on your invaluable website. Yes, a rolling master would have been a solution, but due to its complexity I stayed with one dedicated master that polls data from the the slaves. It is so fast, there was no drawback in responsiveness. What I like in your rolling master approach is that the system does not depend on the ONE Mater! I should have found it earlier.

I am planning setup, where would be more Arduinos and more pasive devices (sensors - pure slaves) on the I2C bus. Each Arduino would "sit down" as slave and respond request, until it have something to say/demand. Then it stop being slave, "stands up" and start transmiting as a Master. After sending what had to be send and eventually getting all answers it igain "sits down" and became slave. So most of the time there are only slaves on the bus, sometimes there arise a Master for a moment. Arising 2 or more Masters solves the I2C protocol itself (first sending 0 get the bus)


text:
How to use console.log message from nodejs server, to control led pin 13?
I want to use Arduino Yun as a client, that connects to my nodejs server, receives a message from nodejs and then change led pin 13 on/off according to the message send.
I have this example of a nodejs server:
  var express = require('express');
var http = require('http');
var url = require('url');

var app = express();

//app.set('port', 8080);

var server = http.createServer(function(request, response){
    console.log('Connection');                                                          var path = url.parse(request.url).pathname;

    switch(path){
        case'/':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Hello World');
            response.end();
            break;
        case '/arduino/digital/13/0':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Led 13 is off');
            console.log('Led 13 is off');
            response.end();
            break;
        case '/arduino/digital/13/1':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Led 13 is on');
            console.log('Led 13 is on');
            response.end();
            break;
        default:
            response.writeHead(404);
            response.write("Oops, this doesn't exist - 404");
            response.end();
            break;
    }

});

//server.listen(8080);

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

server.listen(server_port, server_ip_address, function () {
  console.log( "Listening on " + server_ip_address + ", server_port " + server_port )
});

The server is running on an openshift nodejs server - It's not Localhost!
Here is the Arduino sketch I use:
/*
 Possible commands created in this shetch:
 * "http://yunobomber-cuebo.rhcloud.com"                         -> Serial Monitor "Hello World"
 * "http://yunobomber-cuebo.rhcloud.com/arduino/digital/13/1"    -> Serial Monitor "Led 13 is on"  &  digitalWrite(13, HIGH)
 * "http://yunobomber-cuebo.rhcloud.com//arduino/digital/13/0"   -> Serial Monitor "Led 13 is off" &  digitalWrite(13, LOW)
 */

#include <Bridge.h>
#include <HttpClient.h>

HttpClient client;

void setup() {
  Bridge.begin();                                                          // Bridge startup

  Serial.begin(9600);
  while (!Serial);                                                         // wait for a serial connection
}

void loop() {
  // Initialize the client library
  HttpClient client;

  // Make a HTTP request:
  client.get("http://yunobomber-cuebo.rhcloud.com");       // Insert alternative url for other commands - See explanation at top

  while (client.available()) {                             // Read message from server
    char c = client.read();
    Serial.print(c);
  }
  Serial.flush();
  delay(5000);
}

void process(HttpClient client) {
  String command = client.readStringUntil('/');

  if (command == "digital") {
    digitalCommand(client);
  }
}

void digitalCommand(HttpClient client) {
  int pin, value;

  // Read pin number
  pin = client.parseInt();

  // If the next character is a '/' it means we have an URL
  // with a value like: "/digital/13/1"
  if (client.read() == '/') {
    value = client.parseInt();
    digitalWrite(pin, value);
  }
  else {
    Serial.println('Error: Could not read url!');
  }
}

The serve works as it should, which can be seen here:
http://yunobomber-cuebo.rhcloud.com
I'm also get the message send from the server, when I read serial monitor, so the connection to the server from the Yun is also working. I can also console.log on the server side and see that a connection is established from the Yun.
The problem seems to be with the readStringUntil(); method, what I want to do is actually readStringAfter(arduino/), but such a method doesn't exist or at least I'm not sure how to make one?
Also I wonder if my approach is wrong, since I use REST calls to control the Yun, maybe I should solve it diffenrently, since I've already established a connection to and receiving input from the nodejs server?
Hope that someone can help my understand and solve this issue?


text:
LCD Display 128x64 weird pin, C86 (input)
I got some LCD display from my friend. Base on the model number (TopWay LM6023) printed on product, I found the data sheet from google. According to the datasheet, it is a 128*64 LCD display, but I am confusing the pin out does not same/similar to the famous one. I read the datasheet, there are C86 pin. I have no idea what’s that, and how to make it work. I created a github repo, I am wonder if someone could help to write an example code and wiring to Arduino UNO.
Moreover, I also would like to know what is 6800 & 8080 interface, is it Arduino UNO can simulate ? If yes, any reference?

the difference is how the Intel  8080 and the Motorola 6800 handle hardware I/O ..... the 6800 uses memory mapped I/O .... it uses an enable signal (pin10) and read/write select signal (pin9) ..... the 8080 uses ports for I/O .... you enable the write signal (pin9) if you are outputting data from the microcontroller and enable the read signal (pin10) if you are inputting data to the microcontroller

with the arduino, you probably want to use the serial interface, since it uses only two pins for the data  (pin17 and pin18 (need to verify pin numbers))

Unfortunately driving a graphic LCD is not as easy as driving one of the most popular type HD44780 LCD's.
Back to the subject:
If the state on this pin is HIGH then you shall use  Motorola's 6800 interface, when state on C86 is LOW, use Intel's 8080 interface.
Depending on your selection you would have to keep the communication standard. For 8080 interface refer to point 3.3.1 of you datasheet, for 6800 see point 3.3.2.
Note: If you are struggling, try to search for the libraries using controller's name: LM6023A or one of the S1D15300 or S1D16700
Also, consider number of pins available on your Arduino. It may be that you can drive this LCD with Arduino Uno using serial interface only. (See this link)

Thank you for your reply, your information are helpful after I read the link. Seems it is not a simple task could be complete within a day or week.

This is why sometimes is easier to search for readily available libraries. Unfortunately this one is none of the most popular. You can also check the big collection of the libraries under the name of u8glib - see the list of the supported lcd's: https://github.com/olikraus/u8glib/wiki/device


text:
Standalone ATmega328P stops responding when RX is connected
I have followed this demo and have set up a standalone ATmega328P being programmed from a Raspberry Pi via the SPI lines. I have also added a 16 MHz crystal with 22 pF capacitors, as well as I have enabled and set up I²C between the ATmega and Raspberry Pi.
I have compiled and uploaded a bunch of programs and I can confirm everything works as expected.
As you can imagine, it is quite hard debugging things without a serial connection, so I connected pin 2 of the ATmega to GPIO14 of the Raspberry Pi and pin 3 to GPIO15. At this point, when I try uploading a program, I get this:
$ avrdude -P /dev/spidev0.0 -c linuxspi -p m328p -U flash:w:build-uno/program.hex

avrdude: error: AVR device not responding
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

If I break the pin2 to GPIO14 connection, then my program gets uploaded. And if I restore the connection between the pins and open Minicom on the Raspberry Pi I see the output of my simple program:
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);

  Serial.println("Echo Test");
}

$ minicom -b 9600 -o -D /dev/ttyS0

Welcome to minicom 2.7.1

OPTIONS: I18n
Compiled on Aug 13 2017, 15:25:34.
Port /dev/ttyS0, 16:50:17

Press CTRL-A Z for help on special keys

Echo Test
Echo Test
Echo Test
Echo Test

But whenever I press a button on the keyboard (inside Minicom), I notice that the ATmega gets reset. If I hold the button down the transmission of "Echo Test" seizes as it is getting reset rapidly.
How can I get serial to function properly?
Addendum:
I'm using a Raspberry Pi 4, and in raspi-config I have disabled serial login and left the serial hardware enabled.

There are two things wrong with the circuit in that demo.

There is no decoupling capacitor on the power pins. This is required to keep the power stable during opertaion.
More critically: this is being powered from 3.3V, but is being run at 16MHz. That is outside specifications. You should use an 8MHz crystal to operate at 3.3V.

Thanks for pointing out, I see now indeed it's unrelated. Upvoted yours, deleted mine.

Here is another video from the same creator which shows it working at 3.3V. He is using /dev/ttyAMA0 which doesn't work in my case so something is different but I can't tell what. I'll try adding a 0.1uF capacitor on the input, see if that makes any difference.

It will work at 3.3V, but it won't be stable. The serial port name change is because of a different version of Pi being used.

Well in my case it is not only unstable it plain doesn't work, guess I'll just call it unlucky then and stick to debugging through i2c until I can establish a better setup. Thank you!


text:
USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader
Is it possible to use RXC Interrupt vector with the factory programmed bootloader still existing in the arduino pro mini?
I've written a simple echo program using RXC interrupt vector, the program prints "READY" on startup but as soon the chip receives the first character it goes into a repetitive reset loop i.e. I keep receiving READY READY READY.. so on.
I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?
Thanks in advance.

Could you post the code?

Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does not affect the way the sketch runs.

I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.

Hi Nick, I can't locate the code, its ancient now, sorry. I encountered this error while I was doing some quickie code. I had to use some arduino based libraries and I also required to use the Rx interrupt. As Far I remember, I wrote the usual winavr style ISR after importing avr/interrupt.h    That time, I think, my code was causing restarts and I kept getting READY READY READY. As you say, I did use the Serial port( Serial.print )and inside main() I printed READY. I think I should not have used the interrupt vector as it was already used by the arduino Serial port.