How do I use RFID-RC522 with an Arduino? I am working on a project for my local Makerspace, we have limited budget so I was hoping to use the RFID-RC522 el'cheap'o RFID/NFC readers on eBay, I received a couple of SPI based boards, they work, however the code examples for them are limited.

I have found several different libraries and settled on this one: https://github.com/ljos/MFRC522

The trouble is that all the code available online seem to spawn from some Chinese guys Python code that people have translated, and hacked into an Arduino library.

The code works, but Mifare cards are meant to have 4, 7 or 10 byte UIDs and the example/library is returning a 5 byte serial number.

There is no documentation and the NXP datasheet is incomprehensible... Additionally it seems to work with most cards, but it doesn't work with Mastercard PayWave cards which conform to the ISO 14443 standard. The more expensive RDM880 reader which is based on the MFRC500 works fine and has a nice library but the cost makes the implementation impossible.

So, can someone help me to get this NXP MFRC522 based unit reading the UID from all ISO 14443 cards.

#include <SPI.h>
#include <MFRC522.h>

#define RFID_SS  10
#define RFID_RST 5

MFRC522 rfid( RFID_SS, RFID_RST );

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

void loop() {
  byte data[MAX_LEN];
  byte uid[5];

  if ( rfid.requestTag( MF1_REQIDL, data ) == MI_OK ) {
    if ( rfid.antiCollision( data ) == MI_OK ) {
      memcpy( uid, data, 5 );
      for ( int i = 0; i < 5; i++ ) {
        Serial.print( uid[i], HEX );
        Serial.print( ' ' );
      }
      Serial.println();
    }
  }
}

Sorry, but I must disagree with your 'NXP datasheet is incomprehensible'. From the FIRST PAGE of the MFRC522 datasheet:

'Remark: The MFRC522 supports all variants of the MIFARE Mini, MIFARE 1K,
MIFARE 4K, MIFARE Ultralight, MIFARE DESFire EV1 and MIFARE Plus RF
identification protocols'

Here it says the MFRC522 covers just a part of ISO/IEC 14443. The following are missing fron the NXP RC522:

*MIFARE DESFire EV1 (includes AES encryption)

MIFARE DESFire EV2 (includes MIsmartApp, Transaction MAC, Unlimited Applications
MIFARE Plus drop-in replacement for MIFARE Classic with certified security level (AES 128 based))

MIFARE SAM AV2 (secure access module that provides the secure storage of cryptographic keys and cryptographic functions)*

These are probably the ones used in bank cards. Again, from the FIRST PAGE of the MFRC500 datasheet:

'All protocol layers of the ISO/IEC 14443 A are supported.'

You'll have to plow through all the different MIFARE / ISO/IEC 14443 specs to find out how many ID bytes there are for the different types (I suspect diferent types return a different quantity of bytes).

So, basically, you're screwed. Spring for the expensive MFRC500-based reader. I assume that with the higher cost you also get a high-class API, documentation and examples or even (gasp!) tech support.

Cheers


Why so different not connected analog inputs? I took just Arduino Uno board, connected Ethernet Shield to it and compiled Web Server example. And it works.

But it outputs:

analog input 0 is 1023
analog input 1 is 1023
analog input 2 is 789
analog input 3 is 663
analog input 4 is 525
analog input 5 is 449

Why so different values? Shouldn't it be zeros? Is this static electricity or what?

Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...


Reading I2C sensors with a timer interrupt I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.

Step I: testing the timer

I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!

200
201
200
201

CODE

// Timer variable
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Step II: Reading values from the sensor in the ISR

Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.

CODE

// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  calcBias():
  Serial.print("Readings take: (us)");
  Serial.println(samplingTime);

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  Serial.println("Enabling interrupts..");
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  Serial.println(z);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  // Update x, y, and z with new values 2.5ms
  getGyroValues();
  cont++;
}

void getGyroValues()
{

  //starting samplingTimer
  samplingTime = micros();

  // Gets the angular velocity from the sensor
  byte zMSB = readRegister(L3G4200D_Address, 0x2D);
  byte zLSB = readRegister(L3G4200D_Address, 0x2C);
  z = ((zMSB << 8) | zLSB);

  samplingTime = micros()- samplingTime;
}

void calcBias()
{
  Serial.println("Bias");

  // Reads sensors and display three values
  getGyroValues();

  [...]

  Serial.println(bx);
  Serial.println(by);
  Serial.println(bz);
}

void writeRegister(int deviceAddress, byte address, byte val)
{
    Wire.beginTransmission(deviceAddress); // start transmission to device
    Wire.write(address);       // send register address
    Wire.write(val);         // send value to write
    Wire.endTransmission();     // end transmission
}

int readRegister(int deviceAddress, byte address)
{
    int v;
    Wire.beginTransmission(deviceAddress);
    Wire.write(address); // register to read
    Wire.endTransmission();

    Wire.requestFrom(deviceAddress, 1); // read a byte

    while(!Wire.available())
    {
        // waiting
       // Serial.println("No Data");
    }

    v = Wire.read();
    return v;
}

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.

Here is the output:

starting up L3G4200D
Bias
4.00
0.00
-3.00
Read

Try putting sei(); at the start of the ISR. I think I2C needs interrupts enabled to work.


Safe to control multiple power sources through a switch through the ground? I've attached the breadboard layout and schematic of a circuit I'm constructing, which is a simple Arduino radio control car, with a 9V powering the Arduino Uno, and the 6 volt battery pack feeding power to the motors via the L293D. My question is regarding the switch where I've connected the ground from both battery power supplies to one side, and connected the ground of the circuit to the other side. Is this OK and safe to do? Is there anything I should be concerned about with this setup? Is there a safer or better way to do this? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity?

In case you are wondering why I have two switches, the reason is because I wanted to debug the radio receiver using the serial monitor when I wired this to USB, but I also wanted to prevent it from powering up the motors so my project doesn't try and roll away while it's still connected to the USB cable. The switch I'm asking about in my question is sort of a mains power switch, so when it's off USB I can just flip on both switches and set the robot car free...

You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.

That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.

I suspect it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.


What is causing this warning in Arduino IDE? I'm using DS3231 module with rinkydink library and it is working just fine, however every time i want to compile the code Arduino IDE shows this warning:

  C:\Program Files (x86)\Arduino\libraries\DS3231\DS3231.cpp:291:106:
  warning: ISO C++ forbids converting a string constant to 'char*'
  [-Wwrite-strings]

What is this warning and how to solve it?

The warning was caused by this line:

char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

In C++, the content of a character string such as "Jan" cannot be
modified. Thus, if you assign the string to a pointer, the pointer
should be declared as const char *:

const char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

The same applies to the other arrays of strings: daysLong, daysShort
and monthLong. As a consequence, the prototypes of the methods
getDOWStr() and getMonthStr() should be changed in order to return a
const char *.

BTW, are you sure this library is still maintained? This should have
been fixed a long time ago, and it seems the source was last modified in
2015. You may be better off using a more modern alternative. For
instance, in the Arduino library manager, you can find DS3231 and
Adafruit's RTClib.


Recommended way to fork a library I want to extend a library, available on github to add some features I need.
Of course I will made available the new source code as well.
Because it's the first time I do this, I'm not sure how to do.

My idea:

fork the original repository
create a new branch
make the changes
commit them locally
push the new branch on another (mine) repository (of course, to avoid messing up the original one)

Is it correct?
How to test the library while developing it? I mean, in which folder I have to clone the repo?

Almost.

Fork the library to your account
Check out your fork
Edit as needed
Commit locally
Push back to your fork

Your fork is yours to do with as you wish. Github makes it easy, should you wish, to then pass those changes back up to the original repository (make a "pull request"). But you don't have to do that (and probably don't want to).

You can make a new branch if you like, but that's pointless - your fork is, in effect, a branch itself (well, it's an entire new tree really).


Arduino Mega Pins for SoftwareSerial (vs. AltSoftSerial) I am currently looking at using an Arduino Mega to build a MIDI Receive box that will then pump the data over USB, but am having design issues/uncertainties with the Arduino's receiving end.

I am looking to having (hopefully) 16 MIDI (as 5-pin DINs) inputs on this build, with no outputs other than the USB. The Mega has the 4 Rx pins, which still leaves me with 12 to create in software. From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs, while AlftSofSerial does. However, it also appears (at least from what I've gathered) that AltSoftSerial is not supported on as many pins as I would need to make this work.

With my setup up, not all 16 MIDI devices would be sending data into the Arduino at once, but only 2 - 4; these would be operating at the same time though (i.e. a Keyboard note along with a volume fader), so I don't believe SoftwareSerial would work well for what I need.

Is it possible to work out what I need with SoftwareSerial/AltSoftSerial and the physical UARTs? If there's any necessary info that seems to be missing or I seem to be misunderstanding something, please let me know. Thanks!

From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs

Correct. You can only listen() on one instance at a time.

AltSoftSerial can only support 1 instance, but allows simultaneous transmit and receive, and doesn't block the whole system while either transmitting or receiving.

So the best you can hope for is 4 hardware UART and one AltSoftSerial for 5 ports.

I would suggest looking into the possibility of using multiple Arduino Mega boards with 4 ports on each (4 boards would give 16 ports in total) and have them communicate with each other through some other protocol (SPI or I2C for instance).


Connecting six stepper motors to Arduino Uno I need to control six stepper motors using an Arduino Uno but most of the CNC shields I saw can control only four at a time. Is there a way to interface two CNC shields with a single Arduino Uno?

To answer your question, probably not.  But don't let that stop you.

Connecting two identical shields to a single Uno isn't going to work unless they explicitly support it, because the pins will clash.

So can you find yourself a CNC shield that is 'stand alone', if it had either an I2C or SPI bus interface then that would be even better?

Or can you find 6 stepper motor controllers that can be controlled from a smaller number of pin (or bus)?

Or can you find yourself an alternative processor with more grunt or more pins, such as a Mega or ESP8266 or ESP32?

Do a bit of research, get a few possible solutions and then ask on here for advice on why not to choose them.  Of course the more details and links you can provide the better informed peoples advice will be.


Passing a time_t array as a function parameter I'm trying to log reconnections and disconnections of a network. For that I've created 2 time_t arrays to store such occurances:
const int logSize = 10;
time_t conLog[logSize];
time_t disconLog[logSize];

Now, down the road, I have some manipulation and time calculation to do, and for that I wish to pass those log as a variable.
For example - zeroing its values:
void initLog(time_t log[], time_t init_val = 0)
{
        int sizeLog = sizeof(log) / sizeof(log[0]);
        Serial.print("size: ");
        Serial.println(sizeLog);
        for (int i = 0; i < sizeLog; i++)
        {
                log[i] = init_val;
        }
}

in order using it in a simple way : initLog(conLog);
But unfortunately this is wrong.
I've tried to replace time_t log[] with time_t &log - but still no luck.
What do I do wrong ?

When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (time_t) and where it starts in memory - it knows nothing about the size of the array.
The sizeof() call just gives you the size of that pointer, not the size of the memory it points to.
sizeof() is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.
Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array.  It is typical to create a macro to do this for you at the time you make the array:
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))

Then pass that to your function:
initLog(conLog, CONLOG_SIZE);

Alternatively, since you already have the size in a constant in this case, you could just use that:
initLog(conLog, logSize);


Which reflectance sensor array for a line following robot? I'm working on a line-following robot with my son. We've found a sensor array on Robot Shop that will help us but .. there's two and I'm not sure which will be the best for us.

The difference between them, as described in this PDF is "The QTR-8A uses a voltage divider for each sensor’s output while the QTR-8RC uses an RC circuit."

What I want to do is detect which sensor the followed line is triggering. All I need is a yes/no. But I'm too new to this to decide which of these two sensors would be best for me.

The main difference between the two models, as stated in the PDF you provided, is the output they provide to the MCU.

The QTR-8A will provide an Analog output, requiring a corresponding analog pin on the microcontroller. The QTR-8RC will provide a Digital output, but will allow the same accuracy of the QTA-8A by measuring the discharge time of the capacitor (HIGH to LOW time), with the advantage of higher accuracy due to the use of RC circuit instead of a voltage divider.

Both seems pretty straight forward, but for your needs, the QTR-8RC might seem more compatible, considering the Arduino Uno has 6 analog I/O pins (you didn't mention which Arduino is going to be used, the Arduino Nano has 8 and the Arduino Mega has 16), and that the QTR sensor provides 8 outputs. The way you could accomplish that with QTR-8RC and 8 digital I/O pins is described in the PDF:

  Turn on IR LEDs (optional)
  Set the I/O line to an output and drive it high
  Allow at least 10 us for the 10 nF capacitor to charge
  Make the I/O line an input (high impedance)
  Measure the time for the capacitor to discharge by waiting for the I/O line to go low
  Turn off IR LEDs (optional)


How can I calculate remaining battery life time with arduino I want to display a 3.7V battery's remaining life time on LCD screen using arduino. Like a laptop does. 1h 23m remaining or others. Do I need any kind of module to measure the thing? Can anyone tell the method please?

you may use ADC(analogRead) to measure Li-Ion Cell voltage. unlike Ni-Cd or Ni-Mh batteries, a Li-Ion Cell Voltage is a good measure for battery status. the discharge cycle of an usual Li-Ion cell Starts at 4.2v(full charged, better avoid that!) which quickly comes down to 3.7v. it remains about 3.7 volts most of the cycle and at the end, comes down again to about 2v which battery protector circuit cuts battery off circuit.

but if the Arduino itself is powered from li-ion battery, it can't measure the battery voltage as the ADC Reference is the current varying cell voltage itself. in this case you need to set VREF of Arduino to a lower internal constant reference(1.1v):

https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

and implement a voltage divider

simulate this circuit – Schematic created using CircuitLab

now you can measure cell voltage compared to a fixed reference. a full battery of 4.2 will be read in ADC as about 1000 (4.2* (1/1+3.3) * 1024). 3.7 should be read about 880 and 2.2v (if the Arduino is still ON!) will be read 500 in ADC unit.


Arduino NANO (CH340) error while flashing bootloader Ok. So I'm close to tearing me hair out on this one.

I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)

Anyway, I feel like I've tried everything to make them work.
I am consistently getting

  Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

Installed CH340 drivers, no difference
Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!

Any ideas on how I should move forward here?

Hit reset randomly in the first few seconds of uploading/burning.


Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store I'm trying to build an air pollution sensor for a college project, with an Arduino Due and a series of Spec Sensors digital gas detectors. However, I'm having a little trouble getting the first one of them (Carbon Monoxide, https://www.spec-sensors.com/product/digital-co-sensor/) to behave, before I can run multiple. As they're all the same sensor setup but for different gasses, once I get the first one working, the rest should follow easily.

The code's very simple, as it uses Spec's own command system - sending the letter "c" to the sensor forces it to take one reading per second for as long as the sensor is powered, and then the serial monitor displays whatever comes back:

    void setup() {
      // sensor running via Serial1
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.print("c");
    }

    void loop() {
      if(Serial1.available()!=0)
      {
        Serial.write(Serial1.read());
      }
    }

My problem comes with the data that's being returned. The gas reading is present, but so is a lot of superfluous information that I don't need. According to the sensor's tech document, the information returned is: serial number, reading (ppb), temperature, humidity, raw voltages, and amount of time the sensor has been running for. In the serial monitor, it looks like this:

Right now, all I want is the reading in ppb (the second value), either as the only data coming through or being stored, so that it can then be used in calculations like averages per hour. The trouble I have is that this information appears to be coming through as a stream of individual bytes, and in this format I'm having difficulty working out an effective way to specify which information I want to store, and which I want to ignore.  I've been trying, for example, to come up with a way to specify that the first 14 bytes (serial number, comma, space - as this will always be the same length) should be ignored, and then the next series (up until the next comma - as this reading could be 4-6 digits) be stored as an int, or something, but I just can't seem to get anywhere no matter what I try. Does anyone have any suggestions?

Since the length of each data varies, you should extract data using spererator like comma in the stream.

First, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

  102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function.
https://www.arduino.cc/en/Serial/ReadStringUntil

Second, parsing process. This process is extracting data you want from strtok() function. strtok() is from C language. It divides string by seperator characters.
https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Lastly, utilize the data and repeat whenever sensor sends the data.

I'm not expert at coding. I haven't tested the code below. But this code would be helpful.

int data[12];
int isDataReceived = false;

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write('c');
}

void loop(){
  while(Serial1.available()>0) {
    String inString = Serial1.readStringUntil('\n');
    char * pch = strtok(inString, ","); //Serial number would be ignored
    for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
      pch = strtok(NULL, ",");
      data[i] = atoi(pch);
    }
    isDataReceived=true;
  }
  if(isDataReceived) {
    Serial.print("Data:");
    Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
    isDataReceived=false;
  }

}


getHostByName always failing to find a valid ip I'm using an arduino Uno and a CC3000 wifi shield. I installed Adafruit library in arduino to get access to Wifi network. I'm currently trying to run some samples that comes with the library. It successfully connects to Wifi network and returns

IP Addr: 192.168.137.101
Netmask: 255.255.255.0
Gateway: 192.168.137.10
DHCPsrv: 0.0.0.0
DNSserv: 8.8.8.8
localhost -> 172.217.22.46

Pinging 172.217.22.46...0 replies

But when it tries to connects to a remote service like "www.adafruit.com" or "www.google.com" it assigns ip to 0 which means the host ip unknown. My wifi-hotspot is capable of providing internet connection. Can anyone please tell me what can I do to access remote web site through Wifi from this configuration. Setup method of one of the sample codes that I tried is mentioned below.

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  displayDriverMode();
  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  }

  displayMACAddress();

  /* Optional: Get the SSID list (not available in 'tiny' mode) */
#ifndef CC3000_TINY_DRIVER
  listSSIDResults();
#endif

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  while (! displayConnectionDetails()) {
    delay(1000);
  }

#ifndef CC3000_TINY_DRIVER
  /* Try looking up www.adafruit.com */
  uint32_t ip = 0;
  Serial.print(F("www.adafruit.com -> "));
  while  (ip  ==  0)  {
    if  (!  cc3000.getHostByName("www.adafruit.com", &ip))  {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  uint8_t replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  if (replies)
    Serial.println(F("Ping successful!"));
#endif
  Serial.println(F("\n\nClosing the connection"));
  cc3000.disconnect();
}

My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.


reading micro SD card directly from PC Is it possible to read a microSD card (on a breakout) through the USB port on the arduino? or perhaps another USB port I could attach to the breakout?  Basically, I would like to read data off the card with my laptop without having to go and remove it each time!

It would be very useful, but afaik this is not possible, since the Arduino sketch you write communicates to the PC via the serial interface only.

The IDE/Arduino driver can use the USB to write your sketch and use the USB for communicating, but for sketches the USB (as direct medium) is not possible.

The SD card will not show up as a specific drive/map/folder on your PC.

Since you want to read the SD card, write in your sketch code to transmit the file(s) you want to send to the PC, to transfer them by UART, and on the PC write a program that reads the serial port and processes it.


Need help to send serial data from arduino to XBee and to another XBee wirelessly? I try to send serial data RPM to XBee series1 and then from XBee to another XBee wirelessly in API with Escapes Mode. I think I have to send the data Frame.But not very sure.
Any help?

Following is the code to read RPM and send to XBee?

#include <XBee.h>
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

XBee xbee = XBee();

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;

uint8_t start_data[] = { 0x7E, 0x00, 0x50, 0x01, 0x01, 0xff, 0xff,0x00, 0x05, 0x00,0x01,0x03, 0x84, 0x00 };

void setup()
{
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("I am ready to send some RPM!");
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()
{

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

  Serial.write(0x03);

  delay(2000);
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;

  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}
}

You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. Xbee-Arduino library.


How to interface USB to custom Arduino Uno Schematic and programming atmega? I'm fairly new to designing schematics and working with the atmega on its own and I'm designing an arduino schematic on eagle. Ive gotten to the stage where I need to incorporate a TTL USB interface in order to program the chip. I've just became aware that the arduino uses another avr chip to do so but it appears similar to the microcontroller and just need some clarification.

Since I want it all on one board like the arduino uno, my question is how is the USB-B connected to the microcontroller and how would I Incorporate it into my schematic?

Another question (out of curiosity) if I was to mass produce said PCB with one program on the atmega chip and leave out a USB module so people wouldnt be able to reprogram it (without taking the board apart obviously) How would that be done?

Heres a photo of my current schematic:

Since I want it all on one board like the arduino uno my question is how is the USB-B connected to the microcontroller and how would i Incorporate in my schematic?

The USB interface forms a bridge between the USB connector and the UART of the "master" MCU.  You don't have to use a microcontroller, but almost any UART to USB bridge chip will do the job.  Common ones are the CH340G (cheap and unstable), CP2102, FT232, etc.  The DTR signal from the USB chip is used to reset the main MCU.

You should look at the existing Uno schematics to see how the two chips are wired together.

  Another question (out of curiosity) if I was to mass produce said PCB with one program on the atmega chip and leave out a USB module so people wouldnt be able to reprogram it (without taking the board apart obviously) How would that be done?

You would program the board through the ICSP pins - in the same way that you put the bootloader on.  Normally you'd invest in a proper programmer to connect up to the chip, but you can do it with an Arduino acting as the programmer.


WebSocket message with Arduino MKR 1010 using WiFiNINA and ArduinoHttpClient libraries I am trying to send a WebSocket message to a server. The example for the ArduinoHttpClient library uses WiFi101 but that will not work for the MKR 1010. So I am trying to use WifiNINA instead. The WiFi part works fine but is seems the WebSocket cannot "begin".

#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoHttpClient.h> /*Need to implement*/
//https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/SimpleWebSocket/SimpleWebSocket.ino
//https://www.arduino.cc/en/Tutorial/WiFiNINAConnectWithWPA

char ssid[] = "SSID_NAME";        // your network SSID (name)
char pass[] = "WPA2_Password";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status
char serverAddress[] = "192.168.0.195";  // server address
int port = 3652;

WiFiClient wifi;

WebSocketClient client = WebSocketClient(wifi, serverAddress, port);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();

}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  //printCurrentNet();

    Serial.println("starting WebSocket client");
    client.begin();
    Serial.print("Is client connected? -> ");
    Serial.println(client.connected());

      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();

    while (client.connected()) {
      Serial.print("Sending fire alarm ");
      // send fire alarm
      client.beginMessage(TYPE_TEXT);
      client.print("Fire alarm from arduino mkr1010 - sensor1 ");
      client.endMessage();
    }
    /*
      // check if a message is available to be received
      int messageSize = client.parseMessage();

      if (messageSize > 0) {
        Serial.println("Received a message:");
        Serial.println(client.readString());
      }*/

}

void printWifiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  Serial.println(ip);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

Could it be that there are compatibility issues between the ArduinoHttpClient library and the Arduino MKR1010? I am thinking of getting an ESP32 instead since there seem to be more WebSocket libraries built around it.

I needed to use port 80.

I got a hint from wikipedia:

  The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections), which is of benefit for those environments which block non-web Internet connections using a firewall.

https://en.wikipedia.org/wiki/WebSocket

Switched to port 80 and it works!


Calibrating ESC and then using it i have 30Amp ESC which i can move motor by providing values ,

but i am unable to know what is the minimum and maximum throttle speed of the motor....

how to achieve that level of info through arduino,

although when i calibrate through Open pilot software ,it is able to calibrate and the minimum value is 1500ms ..

Also after calibrating it once , do i need to arm everytime before using ESC in the arduino program through serial input ?

Used this code -

/*
Coded by Marjan Olesch
Sketch from Insctructables.com
Open source - do what you want with this code!
*/
#include <Servo.h>

int value = 0; // set values you need to zero

Servo firstESC, secondESC; //Create as much as Servoobject you want. You can controll 2 or more Servos at the same time

void setup() {

  firstESC.attach(9);    // attached to pin 9 I just do this with 1 Servo
  Serial.begin(9600);    // start serial at 9600 baud

}

void loop() {

//First connect your ESC WITHOUT Arming. Then Open Serial and follo Instructions

  firstESC.writeMicroseconds(value);

  if(Serial.available())
    value = Serial.parseInt();    // Parse an Integer from Serial

}

the problem was when i was connecting the battery , it was not making any sounds...it was already calibrated by open pilot GCS so it was not calibrating again... i needed to reset the ESC and then run this program from arduino


Powering servos with external source I understand why servos and motors require an external power source when run from the Uno, but I've seen a lot of tutorials (for example, this one), where the servo is connected directly to the Arduino's 5V port. I did this, and I think it fried my servo. This is also the method shown on the official Arduino tutorials for Knob and Sweep. In fact, the knob tutorial was the first and last tutorial I tried with my servo -- after trying it, the servo didn't work.

It went like this:
1) Try sweep code without using external supply. Works fine.
2) Try knob code without using external supply. Servo hums without moving and heats up (a lot).

Why do tutorials say to do this if it's not advisable?

Most likely you fried the voltage regulator or the diode on your Arduino board (depending in which power source you used), because the servo has drawn too much current.

Many Arduino Kits or Starter Packs come with really small servos. These do not need much power (especially when no mechanical load is attached to them), so you can power them directly from the 5V pin. Greater/stronger Servos draw much more current and cannot be safely run in the 5V pin.

Many tutorials show this, because it is an easy start for a beginner. And with the right servo it works. More sophisticated cases are not covered there.

EDIT:

Since your Arduino works fine, the voltage regulator and/or the diode should be fine. I tested the Knob example on my Arduino Nano, while powering the servo on the Arduinos 5V pin (and the Arduino is powered over USB). When the Servo is moving, you can see that there is a significant power draw (The power LED gets a bit dimmer), but not so much, that it would be a problem for the Arduino or USB port. Also the example code works as it should, without the servo heating up. I also used a SG90 Micro Servo (9g, by Tower Pro; same as in the tutorial you linked). I also tried the same with an external power source (5V from a powerful USB charger). It still works as intended, but with more power, since the servo now can draw much more current to produce a higher thrust.

So the only thing, I can think of for your problem is, that you either have corrupt hardware, or you have connected it wrong (for example wrong polarity). My Servo has the same color coding for the wires as in the tutorial you linked. Brown is ground, Red is 5V Vcc and Yellow is for the pulse signal.


Arduino IDE crash when I connect Blend Micro I recently bought Blend Micro and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.

I am using Windows 10 with Arduino IDE 1.6.12

I would really appreciate any help with my problem, thank you in advance.

you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.

Well, then you should navigate in out arudiono folder: digit cd "XXX" where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.

then write arduino_debug.exe and you should see on the terminal the error appear; with that we may find the issue.


I have to make an LED with an ultrasonic distance sensor, the idea is to make the LED blink faster when getting closer to at an specific distance i alread have this code, but i do not know how to make the led blink.

CODE:

const int ledPin = 6; // The pin of your LED, D06
const int trigPin = 5; // The pin to which the TRIG is connected, D05
const int echoPin = 4; // The pin to which the ECHO is connected, D04
const int ledOnTime = 1000;
// The time that the LED stays on, after detecting the motion (in milliseconds, 1000ms = 1s)
const int trigDistance = 40;
// The distance (and lower than it) at which the sensor is triggered (in centimeters)
//
int duration;
int distance;

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    digitalWrite(trigPin, LOW);
    digitalWrite(trigPin, HIGH);
    delay(1);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034/2;
    if (distance <= trigDistance) {
        digitalWrite(ledPin, HIGH);
        delay(ledOnTime);
        digitalWrite(ledPin, LOW);
    }
    delay(100);
}

I would say the way to go is using non-blocking code with millis(). Look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It doesn't use delay(), which is considered bad coding practice, since it is just busy waiting. Nothing else can happen during a delay, except for interrupts. Instead of waiting it is better to regularily check the clock, if it is time to do something (much like you would do in real life for example for baking a pizza).

The clock is provided by millis(), which returns the number of milliseconds since startup. Below you see the BlinkWithoutDelayexample. The variable interval controls the blink frequency. If you remove the const keyword before it and change it according to the measurements from the ultrasonic sensor, you will get a changing blinking frequency with changing distance.

Try to combine the codes into one. Remove all delay() calls, except for the delay(1) (it is needed to trigger the ultrasonic sensor and it is small enough to not matter greatly).

const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

The rest is up to you. If you need more information about the BlinkWithoutDelay example, you should google it. There are tons of tutorials. This is a great coding excerise, so have fun :)


while compare, something is wrong I have 5 LDR and Arduino Mega. I connect them and get light level.

void loop() {
// print the analog output in milli volts
int w=analogRead(west);
Serial.print("west = ");

Serial.print(w);
Serial.println(" mv");

int e=analogRead(east);
Serial.print("east = ");

Serial.print(e);
Serial.println(" mv");

int n=analogRead(north);
Serial.print("north = ");

Serial.print(n);
Serial.println(" mv");

int s=analogRead(south);
Serial.print("south = ");

Serial.print(s);
Serial.println(" mv");

int c=analogRead(control);
Serial.print("control = ");

Serial.print(c);
Serial.println(" mv");

delay(1000);

if(e > w)
Serial.println("west");

else if(e < w)
Serial.println("east");

else if(s > n)
Serial.println("south");

else(s < n);
Serial.println("north");

Serial.println("\n");
}

This is my loop and I always see east-north. When west is bigger than east I also see east. What

Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct else(s < n) is doing.  When the if condition that this else gives an alternative to is false, the statement   (s < n) gets executed.  That statement is an expression statement, and its value is the evaluation of s<n, either true or false.

If the semicolon after (s < n) weren't there, you'd get a compile error because (s < n) serial.println("north") is not a valid statement.  You may have meant to say else if(s < n) instead of else(s < n).

Note, in the sequence

if (e > w)
   Serial.println("west");
else if (e < w)
   Serial.println("east");
else if (s > n)
   ...

that last else typically is reached only rarely, because the only condition to get to it is e and w being equal.  Due to sensor noise and signal processing noise, the chance of e and w being equal is probably at most a few percent.

If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second if and second else .  That is, instead say:

if (e > w)
   Serial.println("west");
else
   Serial.println("east");
if (s > n)
   ...


Control relay with both Arduino and DAQ at the same time I want to control a relay with both Arduino and DAQ. Arduino is used as an embedded  device for the control, while the DAQ is hooked up with a computer and performs the control with a user interface. Here is below a schematic of the circuit wiring for the control:

The two signal pins of the relay are connected with the digital pins of Arduino and DAQ. For some reasons, when Arduino comes into play, the control via DAQ cannot be achieved. If only Arduino or DAQ is connected to the relay, there is no problems with the control.

My plan here is, mstly, to let Arduino to instruct some tasks. In some special cases, I want to have the control with DAQ. Anyone can debug my circuit above? Thanks!

I guess, that you drive the digital pin of the Arduino directly with digitalWrite() for HIGH and LOW and that the DAQ does the same (I didn't researched this).

In that case your circuit is dangerous for the devices. As long, as they both output the same, everything is ok. But take the case, that the Arduino is driving it's pin HIGH, while the DAQ driving it LOW. That would be a short through the pin driving circuit's of both devices and most likely the flowing current will exceed the maximum current rating of the pin. This can fry the involved pins hardware or even the complete devices. You get some kind of race condition here: The device, that can handle drain/source more current will be the winner.

In general you have to implement rules, how the devices should work together. Do you need the actions from the DAQ to be executed no matter what the Arduino does? Or should the Arduino be the master here? Or something inbetween? It is not clear, what do you need here.

I will give you 2 suggestions about possible ways:

You could control the relay only with the Arduino. The DAQ can be connected to a digital input of the Arduino (so that it can sense the DAQ's output state) and in the Arduino code you can implement all the logic you need to drive the relay to your liking.
You could define an idle state of your relay input and set it with a pullup or pulldown resistor. It will ensure, that the relay input is at the defined idle state, as long as no device is driving the line to the opposite state. For this you need the devices outputs to be high impedance (on the Arduino this means the pin is configured as input; for the DAQ you need to know yourself or research it).

Let's say the idle state would be HIGH. We would connect the relay pin with 5V through a high resistor (this is the pullup resistor) (maybe 10k, the value is not critical). Both devices can be connected directly. If one device needs to change the state to LOW, it can drive it's output pin actively low, forcing the relay pin to also go to LOW. If it doesn't need the state to be LOW anymore, it should put it's pin into high impedance mode. The pullup resistor will pull the state to HIGH again. You can also add relatively low resistors between the devices to protect against damages from accidentally driving active HIGH while the other is LOW (These can be calculated from the maximum current rating for the pins; 20mA for the Arduino). This kind of logic is often called open drain logic.

simulate this circuit – Schematic created using CircuitLab

If the DAQ cannot put it's pins to high impedance, you can setup that circuit yourself with a single MOSFET:

simulate this circuit

If you use this circuit on both devices, you don't need the small resistors anymore.

The second possibility already implements a specific logic. You need to decide if this logic is good for you. You can invert it's logic (idle state LOW). Personally I would go with the first option, because it is easier and more flexible.


Upload already compiled code on Linux CLI without arduino-cli I have a sketch for an Arduino Nano. I'm compiling it on my build server and get these 3 files:

project.bin.elf
project.bin.hex
project.bin.with_bootloader.hex

Now I need to be able to upload/flash them onto the board (connected via a serial interface) without arduino-cli. Mainly because I can't install it via apt-get which means I'd have to start jumping through loops to be able to use it (stuff like keeping it up to date, installing, etc. on hundreds of devices).
So I was wondering if there are any tools in the debian repositories I can use to upload the compiled sketch and if so how.

I've been looking for a solution and came across several answers and topic but strangely enough all either use arduino-cli, other specialized tools or link to dead pages or pages that no longer contain the answer.

Examples:

How to compile, upload and monitor via the Linux command line?
Compiling sketch vi command line

Use avrdude.

The command format is simple, assuming you have installed it from the Linux repositories:

avrdude -carduino -patmega328p -P/dev/ttyUSB0 -b115200 -Uflash:w:/path/to/project.bin.hex:i

Depending on what bootloader is installed in your nano you may need to change the  baud rate (-b115200) to 57600. Also, of course, the USB device should be set to what your board actually identifies as.

The breakdown of the command is:

-c<programmer type>
-p<part name>
-P<port>
-b<baud rate>
-U<instruction>

The programmer type, part name and baud rate can all be gleaned from the boards.txt file in the AVR core files.  For example, for the Nano:

nano.upload.protocol=arduino
nano.menu.cpu.atmega328.upload.speed=115200
nano.menu.cpu.atmega328.build.mcu=atmega328p

relate to -c -b and -p respectively.  The instruction will always be the same, and means "Write to flash the following file in IHEX8 format".  "flash" is the destination memory, "w" is the write command, and ":i" at the end defines the expected file format.

On a Linux computer with avrdude installed you can find much more information with man avrdude.


How to loop over objects or pass object to function? I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.

I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.

However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.

I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.

I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:

SomeClass classA();
SomeClass classB();

// error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
SomeClass things[2] = {classA, classB};

int init(class SomeClass thing) {
    std::cout << "Setting up thing ";
    thing.setFoo(100);
}

int main() {

    for (int i=0; i < 2; i++) {
        things[i].setFoo(100);
    }

    // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
    init(classA);

    return 0;
}

And just for completeness my class files which are simplified versions of the AccelStepper class:

SomeClass.h:

#include <stdlib.h>

class SomeClass
{
public:
    SomeClass();

    void    setFoo(float foo);
};

SomeClass.cpp:

#include <stdlib.h>
#include <string>
#include <iostream>
#include "SomeClass.h"

SomeClass::SomeClass()
{
}

void SomeClass::setFoo(float foo)
{
    std::cout << "foo ";
}

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

There's a couple of fundamental errors in your sketch.  Mainly your construction of your class instances:

SomeClass classA();
SomeClass classB();

Those are taken as functions that return a SomeClass object, not SomeClass constructors.  Instead they should just read:

SomeClass classA;
SomeClass classB;

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier.  For instance, your array would look like this:

SomeClass *things[2] = {&classA, &classB};

That is an array of pointers to the objects.  It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.

Your loop would then run like this:

for (int i=0; i < 2; i++) {
    things[i]->setFoo(100);
}

Note the use of -> instead of . because you are using a pointer to the object.

Similarly your init() function would be like this:

int init(SomeClass *thing) {
    Serial.println("Setting up thing");
    thing->setFoo(100);
}

init(&classA);

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:

int init(SomeClass &thing) {
    Serial.println("Setting up thing");
    thing.setFoo(100);
}

init(classA);

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using .


Not getting proper readings on Arduino from MAP Sensor In recent project, I have to take reading from MAP sensor. So basically, we used analog pin for this. But in my case, I don't get proper result which actually I want.

When I'm taking readings through multi-meter then I got proper readings. Means when I start the vehicle then it's show 0.99 V. When I provide full throttle then voltage also increase and it's reach to 1.66 V. And finally when suddenly come back to normal throttle then also voltage decrease around like 0.48 V and then within a second again show normal 0.99 V.

Here, when I'm taking readings from MAP sensor through multi-meter then I'm providing ground to multi-meter. And when I taking readings from MAP sensor through Arduino then I'm not providing any ground to Arduino. Because I think it may be damage my Arduino.

So, I think this is also one possibility and may be possible that's why I'm not getting that type of voltage output through Arduino.

Here, the ground which I provide to multi-meter is from 12V DC battery which is used in CNG Auto rickshaw. So, that's why I'm not providing ground to Arduino. So, give me some suggestions about this. What should I do for this. Providing ground to Arduino or not.

Here, it's my code.

int kMAP1 = 0;
float kMAP2 = 0;

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

void loop()
{
  kMAP1 = analogRead(A0);
  kMAP2 =  kMAP1 * (5.0 / 1023.0);

  Serial.print("MAP1: ");
  Serial.print(kMAP1);

  Serial.print("\t");

  Serial.print("      MAP2: ");
  Serial.println(kMAP2);

  delay(1000);
}

And it's my serial monitor output.

MAP1: 490         MAP2: 2.39
MAP1: 433         MAP2: 2.12
MAP1: 270         MAP2: 1.32
MAP1: 0           MAP2: 0.00
MAP1: 447         MAP2: 2.18
MAP1: 401         MAP2: 1.96
MAP1: 518         MAP2: 2.53
MAP1: 487         MAP2: 2.38
MAP1: 344         MAP2: 1.68
MAP1: 374         MAP2: 1.83
MAP1: 611         MAP2: 2.99
MAP1: 429         MAP2: 2.10
MAP1: 647         MAP2: 3.16
MAP1: 668         MAP2: 3.26
MAP1: 460         MAP2: 2.25
MAP1: 489         MAP2: 2.39
MAP1: 278         MAP2: 1.36
MAP1: 277         MAP2: 1.35
MAP1: 318         MAP2: 1.55
MAP1: 383         MAP2: 1.87
MAP1: 238         MAP2: 1.16
MAP1: 237         MAP2: 1.16
MAP1: 134         MAP2: 0.65
MAP1: 191         MAP2: 0.93
MAP1: 230         MAP2: 1.12
MAP1: 308         MAP2: 1.51
MAP1: 479         MAP2: 2.34
MAP1: 388         MAP2: 1.90
MAP1: 544         MAP2: 2.66
MAP1: 518         MAP2: 2.53
MAP1: 419         MAP2: 2.05
MAP1: 544         MAP2: 2.66
MAP1: 586         MAP2: 2.86
MAP1: 544         MAP2: 2.66
MAP1: 575         MAP2: 2.81
MAP1: 184         MAP2: 0.90
MAP1: 202         MAP2: 0.99
MAP1: 883         MAP2: 4.32
MAP1: 671         MAP2: 3.28
MAP1: 884         MAP2: 4.32
MAP1: 487         MAP2: 2.38
MAP1: 403         MAP2: 1.97
MAP1: 184         MAP2: 0.90
MAP1: 426         MAP2: 2.08
MAP1: 412         MAP2: 2.01
MAP1: 428         MAP2: 2.09
MAP1: 434         MAP2: 2.12
MAP1: 420         MAP2: 2.05
MAP1: 312         MAP2: 1.52
MAP1: 414         MAP2: 2.02
MAP1: 435         MAP2: 2.13
MAP1: 405         MAP2: 1.98
MAP1: 418         MAP2: 2.04
MAP1: 515         MAP2: 2.52
MAP1: 462         MAP2: 2.26
MAP1: 578         MAP2: 2.83
MAP1: 332         MAP2: 1.62
MAP1: 330         MAP2: 1.61
MAP1: 164         MAP2: 0.80
MAP1: 425         MAP2: 2.08
MAP1: 345         MAP2: 1.69
MAP1: 226         MAP2: 1.10
MAP1: 0           MAP2: 0.00
MAP1: 97          MAP2: 0.47
MAP1: 872         MAP2: 4.26
MAP1: 55          MAP2: 0.27
MAP1: 492         MAP2: 2.40
MAP1: 531         MAP2: 2.60
MAP1: 1023        MAP2: 5.00
MAP1: 43          MAP2: 0.21
MAP1: 6           MAP2: 0.03


Arduino on breadboard Tension is 4.4V instead of 5 V,looking for some guidance I build a circuit that work on breadboard now i try to prototype it,so i start solder it on a prototype board and the arduino is out of sync.So i check the tension and for some reason it's 4.4~4.6 on the Vin pin of Atmega328 so i try to find how to debug.I don't have a lot of theorical knowledge on electronic,but my thougt was as long as everything is plug in parrallel the tension should remain the same ( and i don't have any thing in serie) so for the tension to drop i may have something acting as Resistor, and i try to find how and what.
I use 22AWG 0.7mm wire o create a 5V line and my GND line on each side of the Atmega ( roughly 7 cm on each side),i start to wondering if it was not a bad idea. I have picture of my prototype bellow,but it's messy so not sure it help. My question is how to you proceed to troubleshoot this thing ? What are the step you do to find out where is the problem

The yellow-boxed 5V and Gnd buses on the freetronics.com.au ProtoShield Basic for Arduino [like you used] already have copper strips connecting the holes.  The strips run on both sides of the board and the holes are plated-through, so there's no need (for this kind of circuit) to have additional bus wire running along above the boxes.  Having that extra wire there gets in the way of making changes, whether for debugging the circuit or for adding or replacing components.

From the frontside picture, it appears you may have a voltage regulator on board.  (However, I don't see the connections to 5V and Gnd, so might be misinterpreting things.)

If your board input is 5 VDC from an external supply, feeding that 5 V into a regulator will lose half a volt or so, which may account for what you are seeing.

However, let's instead suppose you are putting 7 to 12 VDC into an on-board 5V regulator and then measuring 4.4-4.6 V out.  One possibility is the regulator isn't working.  This can happen if the regulator's input or output capacitors are the wrong sizes or wrong kinds, and cause oscillation.  Diagnosing that kind of problem is straightforward if you look at the 5V line with an oscilloscope.  Another possibility is something drawing a lot of current (eg a couple of amps) and taking the 5V line out of regulation.  That's usually easy to diagnose because of all the resulting smoke and heat.

Drawing a good schematic is an excellent step to take to allow better problem debugging.

Other steps to take:

Measure the amount of current the whole board is drawing, or that the NRF24L01 is drawing.  (For the latter measurement, you might need to lift your ground lead off the NRF24L01 board and put the ammeter into the ground circuit.  In general you want all the grounds to be at the same voltage, so the voltage drop across the ammeter is a problem, but not much of one.)
Pull the '328P chip and see if that makes any difference.  In general, it's a good idea to work out a prototype board's power supply problems – such as shorts, reversed electrolytics, incorrect resistors – in advance of installing a microcontroller chip onto the board.
Remove the NRF24L01, if feasible, while debugging the power supply.  If you can't easily remove it, check your schematic and see if all of its pins except 5V and Gnd are open when the '328P chip is pulled.  If so, you can detach the NRF24L01  ground lead to take it out of the circuit.  If, during testing, you unsolder and remove the NRF24L01 board, consider making a socket for it from two 5-pin female header strips.


What's with the debug error messages, like VMDPE_1|1_VMDPE? I'm using visual micro for visual studio, and I understand this kind of thing is caused by conflicting serial data when I try to read and print to the main serial at the same time, right?

Well, I need to read serial data from the main serial on my Mega 2560, and then I need to see it on my LCD screen, which is controlled by the board via SPI. I know I can use those two at the same time because I'm doing it with my transmitting arduino and I can see that it's transmitting correctly.

When I try to view my serial data in the serial port, I get nothing but a stream of these error codes, or whatever they are. They generally look like this: VMDPE_1|1_VMDPE. Usually there are some numbers in there too, like: MDPE_1|2571143_VMDPE. I sort of expected that, since you can't read and write at the same time on one serial. But that would be fine, because my project is not going to be plugged into a PC anyway.

So of course I try to pipe my data directly to the LCD screen so I can plug my recieving arduino into external power and not have to see the error messages, which I thought were coming from the debugger of my compiler. Here's my code:

//on the receiver side

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

char incoming[3];

void setup() {
    Serial.begin(9600);
    //TFT_BL_ON;      // turn on the background light
    //Tft.TFTinit();  // init TFT library
    //Tft.setDisplayDirect(DOWN2UP);
    //TFT_BL_ON;      // turn on the background light
    //Tft.drawString("INCOMING:", 20, 301, 3, RED);
    Serial.println(incoming);

}

void loop() {

    if (Serial.available()) {

        Serial.readBytesUntil(',', incoming, 3 ) ;

        //Tft.fillRectangle(64, 236, 45, 165, BLACK);

        //Tft.drawString(incoming, 65, 235, 4, WHITE);
        Serial.println(incoming);

    }
}

But nope! I get the same error codes on my LCD screen! Even worse, now they seem to have screwed up my zigbee module! I took it off the board, plugged it into my computer, and now the XCTU utility is reading all sorts of messed up values that are total nonsense. Somehow, this seems to have overwritten the zigbee's actual SERIAL NUMBERS!!! What are they now? Take a guess!

Serial number high: E_1|2571092_VMDPE

Serial number low:  MDPE_1|2571143_VMDPE

Your incoming buffer is not big enough to handle the data that you're giving it. Cutting away the comments from your code:

char incoming[3];

This declares a buffer for two characters, allowing for the (required) 0 on the end. println() needs to know when to stop printing characters: it does this when it sees a NUL (0) character.

Serial.readBytesUntil(',', incoming, 3 ) ;

You're passing in that you want to read 3 characters - but that completely fills incoming, leaving no room for the trailing NUL (0).

Serial.println(incoming);

This then prints the first character, the second character, the third character... then the 4th, 5th, 6th, 7th etc. in memory until it finally reaches a NUL and then quits.

What you call "debug messages" are actually printed gibberish in memory... To fix it, you need to make incoming larger.

Also, it's a good idea when using buffers like this to use the sizeof() function, as follows:

Serial.readBytesUntil(',', incoming, sizeof(incoming)-1 ) ; // Note the -1!


Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on I'm connecting a button to ESP8266.
Connection goes like this:
3v to one side of button, other side connected with GND and pin number 2 (no resistor).

Every time I connect the ESP both built in LED's stay on until I press the button, they turn off until I let go (even though code states otherwise).
Plus, When I monitor the serial, gibberish runs while ignoring my print commands, until I press the button then the serial stops outputting altogether.

When I run the serial without the button, everything works fine.
Am I connecting it wrong, or is the button damaged, or any other problem source?
Thanks in advance.

EDIT: I added the pinMode(BTN_PIN, INPUT_PULLUP) to take the resistor role; to the code, still not helping.

When pin 2 is connected to ground as you have done it puts the chip into an invalid boot mode. It will be spewing out messages at 74880 baud complaining about the boot mode being invalid.

You must not connect pin 2 to ground. It must, at boot time, be connected to 3.3V through a resistor (which is should be provided by the board for you if you use a development board not a bare module).

By connecting the button between 3.3V and GND you are causing a short circuit that removes the power from the module and risks damaging the power supply on your board.

The proper way of wiring a button is to use:

pinMode(2, INPUT_PULLUP);

and then connect the GPIO pin to ground through the button.

The INPUT_PULLUP acts like the required pullup resistor keeping the input HIGH while "idle", and the button connects the input to GND when you want to "activate" it, making it LOW.

Those are the only connections you should make.  If you want to use an external resistor instead of the internal one with INPUT_PULLUP, then that goes between the input pin and 3.3V.

Never ever cause 3.3V to be directly connected to GND.


How do I convert a program made on Notepad to my Arduino on Proteus I had the Arduino IDE but I accidentally deleted it. I have no internet connection, so I could not download it again. I do not currently possess the Arduino hardware itself but I do have Proteus and the Arduino library in it.

So I want to program my Arduino. Previously I would simply write the sketch and compile it and go to where I compiled it and simply add it on my Proteus Arduino and run it. Since I don't have the Arduino IDE, I tried using Notepad and tried to save it as a .hex file and run it on Proteus and there was an error created saying Error reading hex file.

So how can I program my Arduino on Proteus with the given materials (Notepad, Proteus)? Can it be done? Or is there any other way?

Besides displaying source code and letting you edit it, the IDE uses avr-gcc (and half a dozen other avr- utilities, like avr-objcopy, avr-ar, avr-nm) to compile and link the code and convert it to an elf or hex form, then uses avrdude to download it.  Using proteus, you can get by without  avrdude, but not without a suitable compiler and linker.

If you have a micro-SD slot on your phone, perhaps you can download the IDE to a card and then move the card to your computer to install the IDE.


Timer Countdown to control relay (multiple functions in void loop) I'm trying to build this project with a simple code.
Object is to hit up button to increment minutes or down to decrement minutes then hit start to start countdown,
while its counting relay will turn On light till counting is done will turn light off and if I hit end button while counting it will end counting and turn off relay.

Here is my try I would appreciate if you could support me.
i can not move to countDown() function in the loop if i press start
I need help to figure out a good technique of declaring functions in void loop in arduino

#include <LiquidCrystal.h>

LiquidCrystal lcd(1,2,4,5,6,7);

#define numberOfSeconds(num) ((num/1000) % 60 )
#define numberOfMinutes(num) (((num/1000) / 60) % 60)

//unsigned long timeLimit = 3600000; // 1000 ms in 1sec, 60secs in 1min, 60mins in 1hr. so , 1000x60x60 = 3600000ms = 1hr

const int upBtn = 8;
const int downBtn = 9;
const int startBtn = 10;
const int endBtn = 11;

int btnPushCounter = 0;
int minutes;
int seconds;
unsigned long minutesGiven;
unsigned long timeLimit;
unsigned long timeRemaining;

int upBtnState = 0;
int lastUpBtnState = 0;

int downBtnState = 0;
int lastDownBtnState = 0;

int startBtnState = 0;
int lastStartBtnState = 0;

int endBtnState = 0;
int lastEndBtnState = 0;

bool bPress = false;

void setup() {

 lcd.begin(16,2);
 pinMode(upBtn, INPUT_PULLUP);
 pinMode(downBtn, INPUT_PULLUP);
 pinMode(startBtn, INPUT_PULLUP);
 pinMode(endBtn, INPUT_PULLUP);

 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Minutes : ");
 lcd.print(btnPushCounter);
}
void loop() {

    checkUp();
    checkDown();
//    countDown();
    if(bPress){
      bPress = false;
      displayNumber();
    }
}

void displayNumber(){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Minutes : ");
    lcd.print(btnPushCounter);
}

void checkUp(){
  upBtnState = digitalRead(upBtn);
  // compare the buttonState to its previous state
  if (upBtnState != lastUpBtnState) {
    // if the state has changed, increment the counter
    if (upBtnState == HIGH) {
        bPress = true;
      btnPushCounter++;
    }
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastUpBtnState = upBtnState;
}

void checkDown(){
  downBtnState = digitalRead(downBtn);

  // compare the buttonState to its previous state
  if (downBtnState != lastDownBtnState && btnPushCounter != 0 ) {
    // if the state has changed, increment the counter
    if (downBtnState == HIGH) {
        bPress = true;
      btnPushCounter--;
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastDownBtnState = downBtnState;
}

void checkStart(){
  startBtnState = digitalRead(startBtn);
  if(startBtnState != lastStartBtnState){
    if(startBtnState == HIGH){
      bPress = true;
//      lcd.
    }
  }
}

void countDown() {
//  unsigned long timeLimit = 3600000;
  minutesGiven = btnPushCounter;
  timeLimit = minutesGiven * 1000 * 60;
  timeRemaining = timeLimit - millis();
  while(timeRemaining > 0){
    seconds = numberOfSeconds(timeRemaining);
    minutes = numberOfMinutes(timeRemaining);
    lcd.setCursor(2,7);
    lcd.print(minutes);
    lcd.print(" ");
    lcd.print(seconds);
    delay(50);
    timeRemaining = timeLimit - millis();
  }
}

I think what you're looking for is to declare your functions near the top of your file, usually before the first function you write, setup(), in this case. So add this just above your setup() function:

// Forward function declarations
void displayNumber(void);
void checkUp(void);
void checkDown(void);
void checkStart(void);
void countDown(void);

C compilers (and thus, C++ because it was derived from C) read the source code only once through, so any function must become known to the compiler ahead of where it is first called. This would require you to place all low-level functions first, then all functions that call those, then the functions that call those, ..., etc. And there are some cases that even this arrangement won't solve, e.g., functions that call each other (oww, my brain hurts!!). So function declarations are used to avoid this inconvenience.

Declaring a function just means informing the compiler of its name, the parameter types, and the return type -- the actual function code isn't required at this point.


How to use millis() in my code instead of delay()? I'm having issues trying to convert my code to non-blocking.
I was able to do so in some parts, but the rest aren't the same.
When I try to replace delay with an if statement like the spinning and sensors debounce it doesn't work at the right time, because the variable I subtract from cur_ms is not updated.
What I'm trying to do is to always switch_dir() and update_code(), and when second_btn.released() I want the other two functions to keep running but also to run a sequence of actions (those with the delay) without blocking.
I would love to get your help.
Thanks in advance :)
void loop()
{
    uint32_t cur_ms = millis();

    if (cur_ms - spin_ms >= SPINNING_MS) {
        switch_dir();
        spin_ms = cur_ms;
    }

    if (cur_ms - read_ms >= SENSORS_DEBOUNCE_MS) {
        update_code(get_sensors_state());
        read_ms = cur_ms;
    }

    if (second_btn.released()) {
        ball_servo.write(BALL_SERVO_MAX);   // drop the ball
        digitalWrite(BLOWER_PIN, LOW);  // blower on
        delay(BALL_DOOR_MS);
        ball_servo.write(BALL_SERVO_MIN);   // close ball door
        delay(BLOWER_MS);
        digitalWrite(BLOWER_PIN, HIGH); // blower off
    }
}

When second_btn.released is true, its two delay() statements will block the whole loop.  You can avoid this by rewriting so that the delay() statements are handled like you already handle spin_ms and cur_ms, which will involve some state-machine-type logic so that (for example) you set a state when you enter the BALL_DOOR_MS delay, then return to the main loop which will have a branch that is taken only if the BALL_DOOR_MS state is active.  When that state ends it sets a new state that enables a separate branch of the main loop to do the BALL_SERVO_MIN and start the BLOWER_MS state, and so on.  A switch/case chain may be
the best way to handle this, replacing the present second_btn.released.


Help: Using if-else on two switch state Problem
I'm stuck on triggering different switch. I'll explain what each of  my switch should do. Output of this setup : No output from relayPin
mainPin

Main power of the switch to control relayPin — keeps on/off
Override reedPin state
Let SecondState

reedPin

Secondary power switch to control relayPin — depends on mainPin on/off state
Overridden by mainPin
Let FirstState

*another explanation in comment
Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.
Code
const int reedPin = 8; // Reed Switch
const int mainPin = 9; // Main Switch
const int relayPin = 6; // Relay

int FirstState = 0;
int SecondState = 0;

void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(reedPin, INPUT);
    pinMode(mainPin, INPUT);

}

void loop() {
    FirstState = digitalRead(reedPin);
    SecondState = digitalRead(mainPin);
    if (FirstState == HIGH) {
        digitalWrite(relayPin, LOW);
    }
    else if (SecondState == HIGH) {
        digitalWrite(relayPin, HIGH);
    }
    else {
        digitalWrite(relayPin, HIGH);
    }
}

Only else if (SecondState == HIGH) { works in output.
Schematics

Draw a truth table and look at it from there.  From your words, it is confusing.  From your code it looks like this:

mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     HIGH

So:

void loop() {
      digitalWrite(relayPin, !digitalRead(mainPin));
}

If you want:

mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     LOW

then:

void loop() {
      digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
}


Why is there a need to ground a circuit? Please tell me why I have to connect one of the wires of arduino gnd to the gnd of a relay or a bluetooth module?

Electric circuits need to be closed. The hydraulic analogy might help you in this sense: suppose you have a garden fountain and want to recycle its water;  if you want water to circulate by means of a pump, you need a way to put the water back in the pump. That's what the ground connection is for.

Sometimes you have closed circuits using other wires, and a ground connection (or a shorter, direct ground connection) might be required to keep at bay the effect of EMI (electro-magnetic interference).
For example, this is the output of an Arduino Nano sensed by connecting only the tip of the oscillocope probe to pin 13.

And this is the same output when I connected the ground tip to Arduino's GND (actually to the USB frame):


Object composition (class uses class) I would like to write a class which utilises another class and it´s member functions. I found out that this is object composition and read some examples of how to do it but it ither doesn´t work for me or I just don´t understand it completely. Here are parts of my code.
#include <SPFD5408_Adafruit_GFX.h>    // Core graphics library
#include <SPFD5408_Adafruit_TFTLCD.h> // Hardware-specific library
#include <SPFD5408_TouchScreen.h>     // Touch library
#include <TriangleButton.h>        // TriangleButton library

I want to use an Adafruit_TFTLCD object and its member functions inside my own class TriangleButton. The object tft is initialised before setup.
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); //Class is part of SPFD5408_Adafruit_TFTLCD.h

I built the TriangleButton.h similar to this thread (Use object of other class within class) and used a reference to the tft object.
/*
  TriangleButton.h - Library for for constructing and reading triangle Buttons.
*/
#ifndef TriangleButton_h
#define TriangleButton_h

#include "Arduino.h"
#include <SPFD5408_Adafruit_TFTLCD.h>

class TriangleButton
{
  public:

    TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color) : _tft(tft){}
    boolean IsTriggered();
    void dash();
  private:

    Adafruit_TFTLCD &_tft;
    int16_t _coordX;
    int16_t _coordY;
    int16_t _orientation;
    int16_t _size;
    int16_t _color;
    int16_t _ru;
    int16_t _hc;
};

#endif

In the ccp. i put a coresponding constructor.
TriangleButton::TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color)
:
_tft(tft)

Now i get the following error message:
C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.cpp:19:1: error: redefinition of 'TriangleButton::TriangleButton(Adafruit_TFTLCD&, int16_t, int16_t, int16_t, uint16_t, uint16_t)'
TriangleButton::TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color)
^~~~~~~~~~~~~~
In file included from C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.cpp:7:0:
C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.h:14:5: note: 'TriangleButton::TriangleButton(Adafruit_TFTLCD&, int16_t, int16_t, int16_t, uint16_t, uint16_t)' previously defined here
TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color) : _tft(tft){}
^~~~~~~~~~~~~~
exit status 1
I don`t understand why ther is a redefinition. Can somebody explain it to me?

error: class 'TriangleButton' does not have any field named '_tft'

This should be self-explanatory. When you write in the constructor

_tft(tft)

It means “initialize the property _tft of this object with the
parameter tft.
It is not very clear what you mean by “object composition”. In the usual
sense, it means that object A either is or has an object B. In your
case, it seems like you want your TriangleButton to hold a reference
to an Adafruit_TFTLCD. This is not really composition, as your class
neither is nor has an LCD.
As an immediate solution, just add an appropriate data member to the
class:
Adafruit_TFTLCD &_ftf;

Assuming that holding a reference to the LCD is really what you want for
your class, this should be enough to solve your issue.

Edit: To answer the edited question.
“Redefinition” means you are defining again something that has already
been defined before. In this case, the constructor is defined inline in
the header file:
TriangleButton(Adafruit_TFTLCD &tft,
        int16_t coordX, int16_t coordY,
        int16_t orientation, uint16_t size, uint16_t color)
    : _tft(tft){}

(yes, that's a complete definition with an empty body).
And then you try to define it again in the cpp file. This is an error,
every method should be defined only once. At your choosing, it can be
either inline in the header or in the .cpp, but not both.


How can I change the speed of a stepper motor? I am new to Arduino and am trying to implement different rotational speeds for a stepper motor. I am using a Nema 17 bipolar stepper motor, a Big Easy Driver, and an Arduino Uno.

I've been trying to modify a tutorial code such that it will run at variable speeds:

//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN  7

//Declare variables for functions
char user_input;
int x;
int y;
int state;

#include <AccelStepper.h>
#include <Stepper.h>
Stepper stepper1 (1,stp,dir);

void setup() {

  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(MS3, OUTPUT);
  pinMode(EN, OUTPUT);
  resetBEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); //Open Serial connection for debugging
  stepper1.setSpeed(1);
  Serial.println("Begin motor control");
  Serial.println();
  //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. Turn at default microstep mode.");
  Serial.println("2. Reverse direction at default microstep mode.");
  Serial.println();

}

//Main loop
void loop() {
  while(Serial.available()){
      user_input = Serial.read(); //Read user input and trigger appropriate
function
      digitalWrite(EN, LOW); //Pull enable pin low to set FETs active and allow motor control
      if (user_input =='1')
      {
         StepForwardDefault();
      }
      else if(user_input =='2')
      {
        ReverseStepDefault();
      }
      else
      {
        Serial.println("Invalid option entered.");
      }
      resetBEDPins();
  }
}

//Reset Big Easy Driver pins to default states
void resetBEDPins()
{
  digitalWrite(stp, LOW);
  digitalWrite(dir, LOW);
  digitalWrite(MS1, LOW);
  digitalWrite(MS2, LOW);
  digitalWrite(MS3, LOW);
  digitalWrite(EN, HIGH);
}

//Default microstep mode function
void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

//Reverse default microstep mode function
void ReverseStepDefault()
{
  Serial.println("Moving in reverse at default step mode.");
  digitalWrite(dir, HIGH); //Pull direction pin high to move in "reverse"
  for(x= 1; x<4000; x++)  //Loop the stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

Adjusting the potentiometer on the Big Easy Driver will either stop the motor turning completely or run at a constant speed regardless of further adjustment.

Do you have any suggestions for debugging my code, or are there other functions I should be using in addition to/instead of those I have?

Do you understand how a stepper works?  You send it pulses and it steps for each pulse you send it.  The faster you send the pulses the faster it will run.  The slower you send the pulses the slower it will run.  You have lines in your code like this:

void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

Can you see the part that is sending HIGH and LOW to your step pin?  See the delay that is determining how fast those pulses go out?  Can you imagine how you might change that delay so that the pulses go out faster or slower?  Here's a hint, delay works in milliseconds, but if you want to go faster than this then you'll need to work in microseconds.  Can you find the version of delay that works in microseconds in the Arduino reference?


Arduino Nano /Uno USB is not getting recognized I have multiple Unos and Nano and recently due to some bad configuration the USBs are not getting recognised on my Mac Air Laptop. These were working models for almost 1-2 years. I used it to control motors and something must have happened and it stopped.

But strangely the small boot up LEDs on the Nano/Uno light up when connected so it seems that the connection from the laptop USB to the device is good - but the driver ports are not showing up on the Arduino IDE.
How do I go about resolving that it is not just a software issue and is a hardware issue ?

I reinstalled the CH340G driver.img and yet the device when plugged in - does not show the USB port on the IDE ?
Any thoughts or ideas on how to resolve this.

The Uno/Nano are Chinese Clones and have CH340 chipset on them.
Is there some firmware that may have gone wrong and can be reset ? or new boot loader that can be burnt to bring them back to life.

I want to be able to see the Tools-> Port -> /dev/cu.usbserial1410
and also be able to see /dev/cu.usbserial on the command xterm prompt .

Assuming that the atmega328p still works fine, you can still use the Nano. I have solved this a few times by just using a FTDI breakout board (remember to set it to 5V, though 3V3 upload works on a Nano), and connecting RX to TX, TX to RX. Press reset before each upload.


How to set string in the structure part of NRF24? Can anyone help me on how to correct my program ? I want to transmit value in string form.

I put this to TX code

struct payload_t
{

 String sensor1;
};

..................

At the loop part I put this code

String sensor1 = (String(x) + "," + String(y) + "," + String(z)) ;

In the RX part I put this code

 struct payload_t
{

 String sensor1;
};

At the loop part

RF24NetworkHeader header;
payload_t payload;
network.read(header,&payload,sizeof(payload));

Serial.println("Sensor1 ");

Serial.println(payload.sensor1);

Below is the Attach picture result of RX code.

Thanks in advance :)

Did you actually 'instantiate' the struct in the TX and construct sensor1 as payload.sensor1 = ...? Anyways, there's still a problem.

You are using String in your payload. The third argument to read is the maximum message length that can be stored in payload. In your read call, you passed the size of payload as MAX_LEN. You will receive incomplete payloads since the String object in the RX payload struct has no content in it yet and thus payload's size, which you passed as MAX_LEN, will be less than that of the actual payload that was transmitted. Just ditch the Strings and try:

TX:

int vals = {x, y, z};   // guessing they are ints

network.write(header, &vals, sizeof(vals));

RX:

int vals[3];
network.read(header, &vals, sizeof(vals));

Serial.print(vals[0]); Serial.print(',');
Serial.print(vals[1]); Serial.print(',');
Serial.println(vals[2]);


Arduino due - SAM-BA bootloader is it there even if you replace the original chip On this page http://playground.arduino.cc/Bootloader/DueBootloaderExplained it mentions the sam-ba bootloader is permanently burned into the rom of the chip.

Does this mean even if I buy a new chip from Farnell, it will still have the bootloader in or is just ones that are specifically made for the arduino due?

That is different from say the mega328, with the mega328 I have to burn the bootloader on manually using isp programmer/ buy it preprogrammed.

Yes, for the Due, but No, for a Zero or Adafruit Feather M0.

The Due uses the Atmel SAM3X8E featuring:

  16 Kbytes ROM with embedded bootloader routines

As a ROM the contents are fixed during manufacture, so would be there in a new chip.

However it is worth noting that many SAM devices including this one have the NVM bits that are much like the fuse bits on an ATmega.  Here GPNVM bit 1 defaults to 0, enabling the bootloader, but if set to 1 the bootloader will be skipped.   Hence it may well be possible to get one into a state where the bootloader is not available.  They also have an "erase" pin which if driven high during startup will restore the default state (bootloader invoked) of this NVM bit (and erase whatever you put in flash).

In contrast, the Arduino Zero and the Adafruit Feather M0 also use Atmel "SAM" chips with "SAM-BA", however, they use the SAMD21, where the situation is a bit different:

  Unlike
  existing SAM products, ROM monitor is not available in SAM D21 and SAM-BA will
  be loaded in Flash memory.

  SAM-BA bootloader is not factory programmed on SAM D21 devices and has to be programmed using an
  external programmer.

Incidentally, congratulations on being willing to step beyond the ATmega DIP packages - more people need to learn that surface mounts part (or at least the TSSOP and LQFP varieties) are something that can be worked with by hand.  If you do not have hot air tools, make sure to only solder one corner, check alignment, solder the opposite and recheck, etc.  But hot air will save you so many headaches and a solder station with it is now in the $60-70 range.

Finally, while you do have the bootloader available in the SAM, to really take advantage of all of its capabilities you will want to get an SWD interface - in addition to programming without reliance on the bootloader, this exposes things like breakpoint debugging, which while almost never "necessary" can still be quite convenient and useful.   Atmel used to offer a great deal on the PCB of the SAM-ICE pod less cables kit and housing, unfortunately there was a massive price increase after the Microchip acquisition.

SWD programming is effectively vendor-unique software operations performed on top of a standard signalling scheme, so you do have options for programmers from other sources - you can make a functional if quite slow CMSIS-DAP from an MBED board (or apparently an Arduino Pro Micro) that will work for debugging but be slow at flashing, you can probably use a Raspberry pi, or the more advanced FTDI devices with the MPSSE engine such as FT232H/FT2232H/FT4232H (but not the everyday FT232RL).  With alternate programmers you will probably need to use something like openocd for the host software - Atmel Studio likely only supports their own and perhaps a few pricey alternatives.


What is the best serial protocol for bidirectional communication with NodeMCU? Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.

Details:

I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.
I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending <=122 character strings to Arduino and possibly getting a short response.
I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).

My research shows that:

ESP8266 has obvious timing issues, having been designed for a different purpose.
Controlling the ESP8266 from Arduino via hardware serial works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.
The same via SoftwareSerial is unreliable
Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)

I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.
The Arduino already works as an I2C master.
I'm assuming I2C is the way to go, but wanted to ask for opinions first.

[EDIT]
Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 can't do very precise timing, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?

So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.

In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.

One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.

Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial.  For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin).  When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high.  When the APM detects & processes incoming data as I2C slave, it sets OK2SEND low.  NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low.  APM detects HAVESENT low which completes the handshake.  When APM is ready for another byte, it sets OK2SEND high again.  etc.  Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.

If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above.  The APM could be like a dedicated I2C peripheral, albeit a slow one.