How to calculate required amperage of multiple motors? I a very simple question about calculating the amperage I need to run 5 stepper motors from my Arduino Uno.
If I have 5 28BYJ-48 stepper motors(which are 5V and are said to require about 240mA each) all plugged into 5 separate ULN2003 driving boards, and I wire 4 signal wires from the boards to the Arduino, and connect the two power wires for the board to 5V and GND on the Arduino. What voltage and amperage I need to supply to my Arduino for everything to run properly?
I'm worried because I read that the Arduino cannot handle over one amp but 0.24*5>1, although I don't know if the amperage is additive with each additional motor.
Thanks for any answers!

I don't know if the amperage is additive with each additional motor

Yes, amperage is additive.

the Arduino cannot handle over one amp but 0.24*5>1

That is correct. But the stepper motors should never be powered through the Arduino. You should connect a fitting power supply directly to the stepper drivers. That way the needed current flows past the Arduino, not through it.

What voltage and amperage I need to supply to my Arduino for everything to run properly?

The Arduino runs at 5V, though you can provide 7-12V to Vin/barrel jack. When your motors are rated for 5V, you should provide them with 5V. So it would be fitting to buy one 5V power source to power the Arduino (through the 5V pin or USB) and the stepper drivers.
For the current: A good measure is the stall current of a motor, so the current, that flows, when the motor is driven, but cannot move (due to being physically stuck). Add a bit headroom to this. The mentioned motors are often badly documented, so that you might not be able to find a stall current value. Add more headroom in that case. So I would suggest adding up all the amps and then multiply this value with 1.5 or even 2. Let's take 250mA per motor (for ease of calculation) with 5 motors gives 1.25A. Take at least a 2A power supply. When you want to make sure go directly to 3A. The price difference in that range isn't that much anyway.


Communication between Genuino Zero and Arduino Uno using UART I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.
For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.
My connection is as below:

Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
Genuino Zero (TX) pin1  ---------------- Arduino Uno pin 10
Ground ----------------------------------   Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.
The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.
My code is here:
https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0
https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0
-------------------receiver---------------------
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
   mySerial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  char a[8];
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.write(byteRead);
    }
  }
  if (mySerial.available()) {
    /* read the most recent byte */
    byteRead = mySerial.read();
    mySerial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      mySerial.write(byteRead);
     }
  }
}

-------------------transmitter----------------------------------

/*
  DigitalReadSerial
 Reads a digital input on pin 2, prints the result to the serial monitor
 This example code is in the public domain.
 */

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 7;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println("a");
  delay(1000);
  // delay in between reads for stability
}

Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.

So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial1.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial1.println("a");
  delay(1000);
  // delay in between reads for stability
}


Conveyor and Counter Project I am new to Arduino and looking for advice if Arduino is the right microcontroller for this project.

My project is quite simple, I want to build 3 conveyors using 3 DC motors. At the end of each conveyor I plan to implement 3 IR break beam sensors to each respective conveyor to count when an object passes through. When n objects passes through each respective conveyor and falls into a catching mechanism the DC motor stops until object(s) are cleared. For the catching mechanism for each conveyor, I plan to use IR break beam sensors to detect if it’s cleared or not as well. (If you have an alternative suggestion to IR break beam sensors, please advice)

Question: Can a single Arduino uno microcontroller board handle this project? From what I know, Arduino can only run one program at a time and I’m not sure if my project can be run in one program; I believe it can. Additionally, what if I wanted to add a LCD display?

Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)


What boards have integrated USB charging? I've been building wearables, using the adafruit trinket, which I love, its small size is easy to tuck away. But I hate having to unplug the battery to charge it every time. I wired in a SPDT switch, and a small USB charger, but it's kind of a cockamamie solution.

I've seen some devices with a battery adapter, and integrated USB charging,
but they are larger, and harder to tuck away.

I don't need more than 4 IO ports, I'm just looking for a tiny microcontroller platform with integrated USB charging. I just saw the mkr1000 today, which looks decent, but is still larger than I would like. If you know of a product that meets this description, please let me know.

The Feather mainboards are fairly small and have integrated LiPo/Li-ion charging. They're not as small at the Trinket but if you don't need the space on the proto boards then you can examine the design files to see what can be cut away.


Matlab interfacing with arduino ERROR I installed the MATLAB support package for arduino in my MATLAB r2013a today.
Now I plugged on my Arduino in my usb port.

And ran the command:

    a = arduino()

    Error: Undefined function or variable 'arduino'.

When I get:

    a = arduino('COM18')

    Undefined function 'arduino' for input arguments of type 'char'.

I have checked that this package has been installed.

It is grey.

Any help will be appreciated.

Thanks very much

Anupam.

Arduino support within MATLAB came with Matlab-2014a onwards, you are using R2013a

Arduino support within SIMULINK came with Matlab-2012a onwards

for your release you can only interact via a simulink model


Time remaining with os_timer_t The Ticker library for the ESP chips is quite useful, which wraps a os_timer_t object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha os_timer_t object?

The library just calls os_timer_setfn and os_timer_arm which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the Ticker class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing uint32_t remaining = timestamp_now() - timestamp_started.

A good function to hook would be the _attach_ms in Ticker.cpp. Add a uint32_t timestamp_started variable in the Timer.h header for the class. Then set timestamp_started = system_get_time() (from user_interface.h). Then write a function uint32_t remainingUs() { return system_get_time() - timestamp_started; }. Beware of integer overflows -- system_get_time returns passed microseconds since µC startup.


Which Arduino board to buy? I need an Arduino Mega 2560 (that is the one that has more pins). I went to eBay and there are a lot of different boards. I'm thinking of buying an ATmega2560-16AU CH340G MEGA 2560 R3 Board + Free USB Cable for Arduino
. Is this one good? I mean, does it do the work? Is it compatible with the Arduino IDE? Anything I need to know?

The Arduino creators have spelled out their position on clones in a fairly lucid blog post a few years ago.

Your board comes pretty close to being a legitimate clone, but the claims about being manufactured in Italy are almost certainly false and possibly illegal.

I bought a CH340G based board myself, and apart from needing to install a different driver, it's pretty close to the original (There are a few projects that reprogram the 16U2 on a real Arduino board, but the vast majority of projects use the 16U2 as a straight serial converter, and the CH340G seems to do that job OK).

As other answers have pointed out, clone makers don't contribute to the community, so consider buying a real board occasionally. On the other hand, Arduino Mega clones are literally 25% the price of the original, so for that board, going with a clone is certainly tempting.


Esp 8266 doesn't reply to AT commands I am working on esp8266 module with arduino uno board.  This is my program.

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
   Serial.print("START");
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    Serial.println(esp8266.print(command)); // send the read character to the esp8266

    long int time = millis();
    while( (time+timeout) > millis())
    {

      while(esp8266.available())
      {
        Serial.print("Coming");

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

the problem is  i am not getting any output from esp module but arduino is transmitting the data.  power supply for esp is given by 3.3v regulator (LD3.3)feeding 12v from arduino power supply adapter  to regulator input .
TX esp to rx arduino
arduino tx to esp rx by voltage divider (R1=1k and R2=1.8k)
esp gnd  to arduino gnd
chpd and esp vin are 3.3v from regulator
Can anyone tell me where the problem is ?

Try powering the ESP from an external 3.3V power supply if possible - some people say the Arduino 3.3V regulator may not provide enough power for it (it is quite power hungry at startup).
Another option worth trying is to put a 100uF capacitor between ESP VCC and GND. Put some small delay at the beginning of your setup() function if you do that just in case.
Also, there are several pins you need to pull UP: CH_PD, RESET, GPIO0. If you have GPIO15 broken out (depends on the board), pull it to ground. I have also noticed the ESP won't boot properly if GPIO2 is LOW - either leave it floating or pull it up.
Here is a picture you can use as a guide
Of course, you should make sure the ESP is flashed with the AT commands firmware (they usually are) and your baud rate is correct. If you don't know - try 9600, 57600, 115200.
If you have a USB to TTL converter, it might be better (easier) to test your setup using it, without Arduino. Any serial terminal program (including Arduino IDE Serial Monitor) will be fine. Just make sure you send both CR and LF for new lines. If you send "AT" and receive "OK" your wiring is correct, if you don't - it is not.


Controlling DC motor using the Servo pins I have a L293D motor shield for arduino uno. It has capability of controlling 2 servo motors and 4 DC motors. But I want to control 5 DC motors for my project. So my question is can I use the 3 pins that are there in motor shield ( to control servo motors) for controlling a DC motor? Or any other solution if any without using any other hardware?

No. A servo motor has its own built-in driver and you just send a low-level PWM signal to control it. That cannot directly drive a DC motor.

If you want more DC motors you will need more DC motor driving hardware.  For simple speed control in one direction that could be as simple as a NPN transistor (or N-channel FET), a base resistor, and a flyback diode (just like driving a relay). For direction control you will need a H-bridge like the L293D (which incidentally is a very poor choice of driver by today's standards - very inefficient and lossy. I wish people wouldn't persist in selling it.)


Program crashes when I use Serial.println()? I'm working with a fuzzy logic controller with Arduino, I'm trying to emulate an AC by entering inputs [temperature and humidity] using two potentiometers and the output is the AC power.

This is the basic part of the program, every thing is good, I can print the values of Temp and HU. But when I try to print the value of the Power, nothing happens, and the serial monitor displays nothing. By trial and error, I can see that Serial.println with power or any variable related to power crashes the program. What may be the reason?

    void loop()
{
    // Read Input: Temperature
    ttemp = analogRead(temp);

    Serial.println("the analoge Tempreture is ");
    Serial.println (ttemp);

    ttemp = map(ttemp, 0, 1023, 5, 65);
    ttemp = constrain(ttemp, 5, 65);

    Serial.println("the actual Tempreture is ");
    Serial.println (ttemp);
    Serial.println("-------------------------");
    delay(100);

    g_fisInput[0] = ttemp;

    // Read Input: Humidity
    hhu = analogRead(hu);
    Serial.println("the analoge Humidity is ");
    Serial.println (hhu);

    hhu = map(hhu, 0, 1023, 16, 100);
    hhu = constrain(hhu, 16, 100);

    Serial.println("the actual Humidity is ");
    Serial.println (hhu);
    Serial.println("-----------------------");
    delay(100);
    g_fisInput[1] = hhu;

    g_fisOutput[0] = 0;

    fis_evaluate();

    // Set output vlaue: Power
    int ppower1 = g_fisOutput[0];
   // Serial.println("the actual Power is ");
   // Serial.println (ppower1);
    ppower = map(ppower1,100,3000,0,255);
    ppower = constrain (ppower, 0,255);
    analogWrite(power , ppower);

   // Serial.println("the analoge Tempreture is ");
    //Serial.println (ppower);
   // Serial.println("--------------------------");

}

You should have provided your full Arduino code. Without setup() part of Arduino code, we can not exactly tell what might be wrong. Please provide it and I'll revise my answer as well.

Check if you have this code in your setup() function:

Serial.begin(9600);

9600 is baud rate and it could be any other supported baud rate(you can see those by opening a Serial monitor and clicking on 9600 baud rate on bottom right edge).

Related to to comments above, from experience and it can be easily "counted", RAM shouldn't be a problem in such short code.


Producing a sine wave with the DAC? Its being a few days i am trying to achieve something that I dont really know if possible.
Using the Samd21 chip(Arduino Zero), I am using a timer and a DAC to produce a sine wave.

The required frequencies are 100Khz to 3Mhz. I know its sounds too much, but according to my calculations its possible- I would like to know if I am wrong with my software approach.

Pseudo is this :

1.I create a look-up table of a sine wave = array of a sine samples that holds N samples
2.I use a timer with a pre scale of 1, where the clock speed is 48Mhz
3.Each timer tick I produce from the DAC 1 sample from the sine wave
4.To change frequencies I am changing the timer top counter value.

If we try to speak about the max frequency, according to Nyquist , a 3MHz sine must be sampled with at least 6MHz sample rate, and my sine array has 15 samples, means 45Mhz sampling rate.(=good)

Then the sine frequency is :

sineF= TimerF*sineSamples = TimerF*15

Than means I need a timer frequency of :

TimerF=15*sineF = 15*3Mhz=45MHz

So, both are good, the timer max f can be 45Mhz, and the sampling rate is good according to Nyquist.

The only concern here, is if the DAC can do that(speed), and if changing the timer frequency fast enough (even every period) is acceptable.

Is this whole software approach true ?
If its not, producing a square wave probably possible,since it requires much less speed, but then, can you turn it into a nice clean sin wave with filters?

Thanks.

First, I have to say I am not familiar with the Zero hardware, so I am
answering in quite general terms. Hopefully you will also get some
answers with hardware-specific information. That being said, here are my
first thoughts:

Your approach seems reasonable to me, but you are too optimistic
regarding the achievable sampling rate.
DACs are usually fast. It's unlikely that the DAC will limit the
frequency you can achieve.
You cannot achieve a sampling frequency of 45 MHz in software
with a CPU running at 48 MHz: your code to output a sample would
have to run in less than 1.07 CPU cycles.
You may achieve a higher sampling rate with an array of
16 samples rather than 15, as wrapping the array index modulo 16
can be optimized by the compiler into a bitwise AND, which is likely to
be faster than computing index%15.
Fastest would probably be to use a busy loop with constant execution
time and interrupts turned off (I know how to do that on AVR, but not on
ARM). Problem is: the program cannot do anything else than outputting
samples.


Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters When I am using RF 433 MHz module with ARDUINO MEGA then it is transmitting any text or anything in ASCII values. Now how to decode those ASCII values to alphabets? If I use ASCII conversion programme then what if I send a number and that conversion program converts that number also to text or related ASCII character? please suggest any way.

Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0.  When 8 ones or zeros arrive you have a byte.  A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.

In your case your sending program is sending a letter, lets say A.  Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII [code] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65.  Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.

To show that A you might need to cast the data you receive to a character i.e.

unsigned char rxData = 0;
Radio.ReceiveData (&rxData, 1);
Serial.println((char)rxData);


Sending multi-byte data over I2C between different processors I have been attempting to read data from an ATTINY84 via an ESP8266. Both are programmed via the Arduino IDE, though as PlatformIO is a proxy for that, I'm not certain what version of the ATTINY core is in use.

I have both devices connected to the I2C bus, with the Arduino as a slave.
The ESP sends a code requesting a particular type of data, then calls Wire.requestFrom() to get 8 bytes of data. I am concerned over both my implementation and about potential endian-ness issues (even if it should turn out not to be an issue on these two particular devices, I'd like to know my future options).

The ATTINY code is a complex function that is called when there is a request (and the right option code, but that's probably not very relevant). It writes eight bytes using Wire.write after uncompressing them from the relevant arrays. (I have a lot of ADC data that technically should not fit in RAM.)
Since this is is a callback function or possibly an interrupt, do I need to be concerned about data corruption if the code is too slow to write the values onto the bus? I have to imagine it's trying to read them even as it writes. I can also provide code snippets if it would help.

I am also unsure if I am running into Endian-ness issues by using bitshift to grab the 2 and 8 bits from the ADC return value. Would this always give me the correct values, or does the C++ compiler (as I assume it does not) simply refuse to handle differences between the data order?
Specifically, if I shift a uint16_t (or any non-trivial datatype) right by 8 bits, and mask out the bottom 8 with &0xFF, do I always get the second-least-significant (in this particular case, high) byte, or can the compiler produce alternate outputs based on byte order?

Does Arduino have an equivalent of network byte order (or does Wire automatically do so for its overrides of the functions) that I can get around this potential issue with?

There seems to be multiple questions in what you are asking. Here I try
to answer specifically this one:

  if I shift a uint16_t (or any non-trivial datatype) right by 8 bits,
  and mask out the bottom 8 with &0xFF, do I always get the
  second-least-significant (in this particular case, high) byte, or can
  the compiler produce alternate outputs based on byte order?

Short answer: yes, you get the second-least-significant byte,
irrespective of the platform's native endianness.

Now, I'll expand on this answer by showing the different ways you
can convert an uint16_t to a sequence of bytes, and the implications
on the byte order.

If you want to control the endianness, and you want your code to work
independently of the native endianness of the platform, then bit
shifting is the way to go. Let's assume you want to convert this:

uint16_t data;

into this:

uint8_t bytes[2];

You can do it this way in order to get the least significant byte first:

bytes[0] = data >> 0;  // least significant byte
bytes[1] = data >> 8;  // most significant byte

Or you can instead do the assignments the other way around
(data >> 8 goes to bytes[0]...) if you want MSB first. Note that
there is no point in masking, as the assignment does it implicitly.

In contrast, if you wanted to put the bytes in native endianness (the
endianness of the platform), the traditional way to do it is to cast the
address of the number to a pointer to bytes, then read from this
pointer:

bytes[0] = ((uint8_t *) &data)[0];  // first byte
bytes[1] = ((uint8_t *) &data)[1];  // last byte

You can swap the indices on one side of the assignments if you want to
instead reverse the byte order. But note that this kind of casting is
now frowned upon, as it violates aliasing rules. A common alternative is
to have the number and the byte array share the memory within an
union:

union {
    uint16_t data;
    uint8_t bytes[2];
} x = { .data = some_16_bit_value };
do_something_with(x.bytes[0]);  // use first byte
do_something_with(x.bytes[1]);  // use second byte

These are the main byte-splitting idioms you may come across. If your
purpose is to have an endianness that you control and is independent of
the platform, then stick with the first option: the old good bit
shifting.


I2C and SPI at the same time? I would like to ask a question relating to the following communication setup:

STM32 -- Arduino Pro Mini -- ADNS3080 sensor

The interface between STM32 -- Arduino is I2C and the interface between Arduino Pro Mini--ADNS3080 is SPI.

I have tested the communication between the STM32 and the Arduino Pro Mini, and between the Arduino Pro Mini and the ADNS3080 sensor. Both of them work fine; I can successfully send and receive data in both cases.

Now, I want to read the register of the ADNS3080 sensor using the STM32. First, I start an I2C communication between the STM32 and the Arduino Pro Mini, then I send the register address of the ADNS3080 to the Arduino Pro Mini. The Arduino Pro Mini reads the register address and in the same function starts a communication, using SPI, with the ADNS3080 sensor.

But I receive I2C errors in the STM32. Is it possible to use I2C and SPI at the same time? Do I have to introduce delays between the I2C and SPI commands?

Regards, Ali

is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

  Do I have to introduce delays between the I2C and SPI commands?

No you don't.


Same Arduino Sketch when uploaded from a Linux machine does not work I am trying out some code using the Arduino IDE. The code basically tries to connect to a server and push some data to it.

When I upload the sketch to the Arduino from Mac (Apple PC running on Mac OS) the code works as expected without an error.

However, when I upload the same code/sketch from a Linux machine on Ubuntu, the arduino does not operate as expected.

I tried taking a diff comparison of the HEX files created in both machines to check whether there are any differences (expecting very few). But found that there a lot of differences.

What am I missing? Why isn't my code working when uploaded via the Linux PC!!!!!

Got this sorted.

The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!

Thanks Guys


Which is faster, Serial or DigitalWrite? I am working on an Arduino Uno battle bot that uses a Sabertooth moter controller. Right now it is connected to the Arduino through Serial communication. Which is would be faster (So I can increase response time on my robot) Serial, or pwm using DigitalWrite?

Using digitalWrite() is the slowest by far.

Using PWM could be the fastest.

Using Serial could be the fastest.

PWM:

You have to filter the PWM output to be a smooth analogue signal for it to be of any use. The filtering adds an inherent sluggishness, or response time, to the system - the harder the filtering the slower the reaction to changes in the PWM duty cycle. Adjusting the filter component's values will give an optimum point between smoothness and response time. Bear in mind that the motors may respond erratically if there is insufficient damping of the signal. This will probably give the Sabertooth a hard time, too. The datasheet recommends are filter response time of greater than 1ms.

Serial:

If you are considering the 2x 60Amp version (thanks for adding plenty of information in the question, by the way) then the fastest baud rate is 384kbps - or 48k commands per second. The Arduino will of course not be churning data continuously because it'll be busy running the rest of the program, but using serial it is theoretically possible to send commands faster than the motor controller's output PWM.

So which is faster?

No idea. Only you can determine this, and I doubt you'll be able to determine the answer without wasting your time on some experiments.

The motors will have an inherent mechanical dampening thus creating an overall bottleneck in the whole system response time. I can almost guarantee that both PWM and Serial methods will be much faster than the response time of the motors themselves.


ATMega32u4 SLEEP instruction I was reading the ATMega34u2 datasheet and trying to figure out Sleep Mode. I know most people recommend using avr/sleep.h library. But I wanted to try out using the registers. I am fairly new to all this so sorry if this an easy question but I can't seem to really find anybody doing it like this.

When checking which registers to adjust it says this:

  The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.

Now I understand setting the bit but what exactly is the sleep instruction? How do I call it in my arduino program?

SLEEP is an assembly instruction.  You can execute assembly with GCC's Inline Assembly facility.

In short:

asm volatile("SLEEP");

will do what you want.

The avr/sleep.h file has sleep_cpu() defined as:

#define sleep_cpu()                              \
do {                                             \
  __asm__ __volatile__ ( "sleep" "\n\t" :: );    \
} while(0)

Which is essentially the same thing - just wrapped in a block to isolate it from the rest of your code somewhat.


SerialPort Node.js stuck in 'Error' I am trying to get my Arduino to send data to my computer using Node.js Serial port. Everything compiles, my Arduino is working well and sending data in the serial monitor, but the program always goes into myPort.on('close'), and I can't figure out why.

//import serial port js package
const SerialPort = require('serialport');

//opening a port
var myPort = new SerialPort("/dev/ttyS2", {
  baudRate: 9600,
  //parser: SerialPort.parsers.raw
});

//how to pass the readline
const Readline = SerialPort.parsers.Readline;
const parser = new Readline();
myPort.pipe(parser);

myPort.on("open", onPortOpen);
myPort.on("data" , onData);
myPort.on("close" , onClose);
myPort.on("error" , onError);

function onPortOpen(){
    console.log("Port open");
}

function onData(data){
    console.log("data transfer completed..");
    console.log(data);
}
function onError(){
    console.log("Error. something went wrong..")
}
function onClose(){
    console.log("Port is closed. Communication terminated");
}

Would anyone know what are the potential reasons? I double checked my port and it really is COM3, therefore, /dev/ttyS2 for Windows 10.

I see two issues in your code. I cannot say for sure they are related to
the problem you experience, but anyway:

The Readline parser's line terminator defaults to "\n", whereas
Arduino's Serial.println() uses "\r\n". In order to get the line
terminators match, you should invoke the Readline constructor with
{ delimiter: "\r\n" } as an argument.
Piping the flow through the parser returns a new stream. You should
watch for data events on that stream rather the original port.

Thus I suggest you try:

const parser = new Readline({ delimiter: "\r\n" });
const parsedStream = myPort.pipe(parser);

myPort.on("open", onPortOpen);
parsedStream.on("data" , onData);
...


Which sensors to choose to detect movement direction So I'm planning to build a sort of light switch for my Philips Hue bulbs with an Arduino. This project will be mounted on a shelf next to my door to the room, parallel to the walking direction. In order to detect the movement direction to either turn on or off the lights when a person is entering or leaving the room, I need one or two sensors. I've tried HC sr04 before but got inaccurate results which resulted in random changes of the lightstate.

So what sensors will be best for my application? I was thinking about the Sharp IR sensors (i.e. Sharp GP2Y0A60SZLF) but I'm not sure about any possible interference that comes with it when I mount to of these right next to each other. Any ideas?

Thanks in advance!

The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.

The raw sensor looks like this:

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.

Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read this article and look at the sensor response graph.


I bought ATmega328p with bootloader and I can't erase it I bought an online deal which had 10x ATmega328p with bootloader installed. I thought I can erase the bootloader once I got the order (I want to write custom task without a bootloader) but my programmer does not seem to find the ATmega328p. I know it is the problem of the microcontroller because I have another ATmega328p which works fine and I can upload code to it. Is there a flag or switch I am missing when trying to overwrite the bootloader on the microcontroller?

Here are the components I am using:

ATmega328p with bootloader
SparkFun Pocket AVR Programmer (usbtiny)

Here are the commands I am using:

To compile: avr-gcc -std=c11 -mmcu=atmega328 -O -o main.o main.c
To generate hex: avr-objcopy -O ihex main.o main.hex
To upload: sudo avrdude -c usbtiny -p m328p -U flash:w:main.hex

Here is the output of the avrdude command:

avrdude: Using SCK period of 10 usec
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Anyone encountered similar situation before? How did youu managed to fix it? I appreciate any help :)

Thank you

Edit #1 I tried setting the -B flag to various values but nothing seems to solve the problem.

Edit #2 Here is the circuit I am using while programming the ATmega328p

2x Capacitors 22pf
1x Crystal oscillator 16Mhz
1x Resistor 10K ohm
1x ATmega328p
1x SparkFun Pocket AVR Programmer

Your connections to the ATmega328p are incomplete.
You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.
You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.
Additionally you should use supply bypass capacitors.
Please see the minimum wiring at Arduino on a Breadboard, however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have directly across each pair of power pins.
That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.


Sending sensor readings from Arduino to Raspberry Pi over 433 MHz I'm building a garden monitor, so I got myself an Arduino Nano, a soil humidity sensor, an air humidity and temperature sensor as well as a luminosity sensor. Since I had not one but two Raspberry Pis laying around I thought I'll handle the receiving end with one of them. I also got a 433 MHz RF kit.

The trail of the information will look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 MHz - - - 433 MHz Receiver -> Raspberry Pi

Now my question is, what libraries should I use? I checked rc-switch (it has libs for both Arduino as well as RPi) and managed to send some codes but it seems that I'll need to write my own protocol to use this to transmit even simple data as it wasn't developed for sending data, rather simple switch on / switch off signals to simulate remotes.

VirtualWire would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.

Any suggestions?

You could look into the RadioHead library - there might be a port for RPi, though I couldn't find one with a (very) quick google. This library works well, I use it actually with RFM69H 433 MHz radios (from Moteinos), a little more expensive than the simple 433 kits, but also supports encryption which might be important down the line. If you can't find a good library for RPi one solution could be to have a second Arduino acting as a receiver and sending data serially to RPi. This is what I use with a regular desktop PC which is my home server.

I also found a discussion about connecting a RFM69 to the RPi here which might give you more information about the process in general, even if you won't use the same radio.


ESP8266 - does it really have terrible wifi range by default? ESP8266  - does it really have terrible WiFi range by default??

First time to try this module out and we're disappointed with the range.. as per our testing we can only get max 5m WiFi range line of sight (LOS) to our regular WiFi router (TPlink and other routers we tried)

LOS Distance (Test results based on RSSI):

at 6 meters NO CONNECTION
at 5 meters  -77
at 4 meters -70
at 1 meter -56
at 3 meters -59

We also tried using different WiFi Channel from 1-11
We also tried removing wifi password (no password) and WEP password
We tried also using different modes B G N

NO change ..

Are we doing something wrong here?  Or is this module just that bad?

Any solution not requiring hardware change? (because we already bought a lot)

here's our little module

Interestingly, I saw these guys test the module and it seemed to work well .. Could we have a fake chip?

https://www.youtube.com/watch?v=7BYdZ_24yg0

We have really hit a stumbling block. hope you guys can help

The very first thing I notice is that your WiFi antenna is shielded by the PCB. That is the antenna is placed right over the top of the ground plane of the PCB and your range is going to be severely limited.

You will notice on the NodeMCU design below that they have placed a PCB cutout where the antenna is located. In other pictures you can also see that the ground plane does not go past where the antenna starts.

On other boards the antenna sits proud of the main PCB such as this one from Tronixlabs:

If money is tight and new hardware is out, you could try cutting a cutout where the antenna sits using your Dremel (or other rotary tool). If there are any traces underneath the antenna you will need to fix them up with wire worms. Of course it is best to remove the ESP module first.

Alternatively, you could redesign the PCB and send it out for another manufacturing run. I use PCBShopper.com to find the best price for the bare PCBs.

Edit:
Something else you could do is to unsolder the ESP and mount it 90 degrees to the PCB. You would need to solder wires from the base PCB to the terminals of the ESP. This should work and you won't need to cut the base PCB.


Arduino Mimicking Voltage Dividing Keypad / Matrix Still very new to Arduino, so bare with me. I've been all over Google looking for ways to hack my alarm keypad. This is my first time using the Arduino to hack something  :smiley-confuse:

The keypad has a 13.7v input. Every other contact I can touch shows 5v or less. I realized quickly that the key buttons were producing various voltages. A quick search revealed that it was a voltage divider. I can see the resistors on the ladder. I though about mimicking the ladder via the Arduino and using a common ground.

I can see two shift resistors that say HEF4094BT. My guess is that these power the led's on the board.
I can also see a chip that reads KSL1 r1342 that I can't seem to find a datasheet on.

I have a few questions, but I guess I need to tell you my end goal. I want to make my keypad an IoT device. I want to be able to read the status of the alarm, and possibly mimick the keypresses to disable the alarm or activate it.

1st. I was thinking I could share a common ground, and read a led state for high/low. Like the "Armed" Led. Thought I'd ask the community before I go and short something  :(

2nd. How can I mimick the keypad's output voltages? Maybe a DAC? If so, what do you recommend?

Other Information: It's a DSC PC1550 - 6 zone alarm. (...and I'm also guessing the Rx/Tx are some DSC proprietary serial connection for security :/ )

Cheers,
Robert.

Reading the leds would work. Depending on the voltage going out of the shift register, you might need to add a buffer chip, to lower the voltage.

For the keypad I'd probably go with a variable resistor, better known as a digital potentiometer.

You could probably add a way to also read the keypad, from the arduino. Which might be useful, maybe.


How to avoid report of unsuitable sketch names? I bought a kit of 37 sensors for Arduino, and downloaded all the example sketches. Now, when I try to start up the Arduino IDE I get a lot of frustrating messages like this:

... and I have to click "OK" on every one in turn before the IDE will start up.

Obviously I do not want to delete the sketches and their accompaniments, so I have tried to rename all the files and directories, with a shell script, to remove non-alphanumerical characters, but my understanding of shell programming is not good enough, so I have had no success.

I have made backups of the files in case things went awry with my scripting, and now see that these messages are repeated, as in the image, for the backup copies as well. I cannot find out how the Arduino IDE finds them, they are not in my Sketchbook folder.

I would be grateful for advice on either how to avoid these messages, or to edit the names so that they do not occur: I would be happy to edit the names of each sketch as I come to try it out, but I baulk at doing the lot at once.

I am using Linux Fedora 20.

That message is actually a hang-over from when the IDE was Processing.  The name of a file had to match the name of the Java class within that file, and there are strict rules about what can be in a Java class name.

They just basically haven't got around to deleting that piece of ancient code yet.

So you have 3 options:

Rename all the folders and files.
Edit the IDE's source code to delete that old code
Use a different IDE.

The first option can be long winded if you don't know how to do good scripting, as you have found out.

The second option requires knowledge of Java coding.

So that leaves the third option.  Now, I'm going to be shamelessly advertising my own work here ;)  Why not try a better IDE?  Such as the popular and powerful UECIDE (yes, written by me). It's based on the Arduino IDE, so it will mostly be familiar to you, but the whole of the insides have been ripped out and re-written.  If you're feeling brave you might want to give the beta version a go - it has some really really cool features not found in any other IDE in the history of mankind.


What bootloader is present by default on Arduino Uno? Or where can i find information of default bootloaders present on each Arduino board. All I could look up was it could be one of these bootloaders on the atmega chip :-

.Atmega
.Atmega8
.bt
.caterina
.caterina-Arduino_Robot
.caterina-LilyPadUSB
.gemma
.lilypad
.optiboot
.stk500v2

This was the list present in the folder ~\Arduino\hardware\arduino\avr\bootloaders.

It is defined in the file "boards.txt" (arduino-1.8.7\hardware\arduino\avr\boards.txt).

For example the Arduino Uno is called "Arduino/Genuino Uno" and it has the bootloader: uno.bootloader.file=optiboot/optiboot_atmega328.hex

You can find that hex file in the folder arduino-1.8.7\hardware\arduino\avr\bootloaders\optiboot.

The official Arduino boards are shipped with the newest bootloaders.
Sometimes the bootloaders are improved or changed. That is mentioned in the Release Notes.
For example the latest change to a bootloader is that the Arduino Nano has now the same optiboot bootloader as the Arduino Uno.

When buying a Arduino clone board, anything is possible.

Some companies make there own Arduino-compatible boards with their own bootloaders.


Error compiling for Arduino Nano 33 BLE with LiquidCrystal library I recently started coding in the Arduino IDE for the Arduino Nano 33 BLE I bought.
When I choose the Nano 33 BLE as my board, I get the following Error:

Arduino: 1.8.11 (Windows 10), Board: "Arduino Nano 33 BLE"

In file included from C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token

 class LiquidCrystal : public Print {

                                    ^

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared

   using Print::write;

         ^~~~~

exit status 1
Error compiling for board Arduino Nano 33 BLE.

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

I do not get this error when compiling for a normal Arduino nano board.
This is my code:

#include <Arduino_LSM9DS1.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

//pins:
const int measurePin = 13, calibratePin = 14, xHighPin = 15, xLowPin = 16, yHighPin = 17, yLowPin = 18;

//constants:
const int interval = 10;
const float delta = 10;

//variables:
boolean measureSts = LOW, calibrateSts = LOW, xyOK = true;
int count = 0, timer = 0;
float measurements[100], current, x, y, z, xZero, yZero, zZero;

//programm:
void setup() {
  lcd.begin(16,2);

  pinMode(measurePin, INPUT);
  pinMode(calibratePin, INPUT);
  pinMode(xHighPin, OUTPUT);
  pinMode(xLowPin, OUTPUT);
  pinMode(yHighPin, OUTPUT);
  pinMode(yLowPin, OUTPUT);
}

void loop() {
  if ( IMU.accelerationAvailable() ) {
    IMU.readAcceleration(x, y, z);
    calibrate();
    checkXY();
    measure();
    current = z - zZero;
    printValues();
  }
  else lcd.print("--geen  sensor--");
}

void checkXY() {
  xyOK = true;
  if ( x < xZero - delta ) {
    xyOK = false;
    digitalWrite(xLowPin, HIGH);
    digitalWrite(xHighPin, LOW);
  }
  else if ( x > xZero + delta ) {
    xyOK = false;
    digitalWrite(xLowPin, LOW);
    digitalWrite(xHighPin, HIGH);
  }
  if ( y < yZero - delta ) {
    xyOK = false;
    digitalWrite(yLowPin, HIGH);
    digitalWrite(yHighPin, LOW);
  }
  else if ( y > yZero + delta ) {
    xyOK = false;
    digitalWrite(yLowPin, LOW);
    digitalWrite(yHighPin, HIGH);
  }
}

void measure(){
  if ( digitalRead(measurePin) == LOW && measureSts == HIGH && xyOK ) {
    measurements[count] = z - zZero;
    zZero = z;
    timer = interval;
    count++;
  }
  measureSts = digitalRead(measurePin);
}

void printValues() {
  if ( timer >= interval ) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Meting: " + String(measurements[count]) + (char)223);
    lcd.setCursor(0,1);
    lcd.print("Huidig: " + String(current) + (char)223);
    timer = 0;
  }
  timer++;
}

void calibrate() {
  if ( digitalRead(calibratePin) == LOW && calibrateSts == true ) {
    xZero = x;
    yZero = y;
    lcd.setCursor(0,3);
    lcd.print("kalibreren");
    lcd.setCursor(1,4);
    lcd.print("voltooid");
    digitalWrite(xHighPin, HIGH);
    digitalWrite(xLowPin, HIGH);
    digitalWrite(yHighPin, HIGH);
    digitalWrite(yLowPin, HIGH);
    delay(100);
    lcd.clear();
    digitalWrite(xHighPin, LOW);
    digitalWrite(xLowPin, LOW);
    digitalWrite(yHighPin, LOW);
    digitalWrite(yLowPin, LOW);
  }
  calibrateSts = digitalRead(calibratePin);
}

For context: I am trying to create an angle-measuring device using the built-in accelerometer and a 2x16 LCD.

I hope someone can help me fixing this.
Thanks in advance.

-Niels

The Arduino core for Nano 33 BLE is based on Mbed and can be used in Mbed as library. To achieve this, the Arduino API classes in this core are put in a namespace arduino::. This causes problems for libraries which include individual includes of Arduino API historically copied into cores for different MCU architecture platforms. The Arduino.h file includes the API files in the right way so in this case replacing #include"Print.h" with #include <Arduino.h> in LiquidCrystal.h solves the compilation problem.


Arduino/DuinOS vs Normal C/ARM Programming I'm trying to understand the difference between programming Arduino hardware (Atel/ARM based) versus 'normal C-based ARM programming'.

My understanding is that the Arduino language is cross-compiled into C-compatible binary, and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip, which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

I'm sure I'm mucking up a few things here, but this is my general understanding: can someone correct/clarify these things for me?

My understanding is that the Arduino language is cross-compiled into C-compatible binary,

There is no "Arduino language". Programs are written in C++ or C, and the IDE mangles them in certain ways in order to ease development by beginners (and on occasion frustrate development by veterans).

  and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip,

No. The uploading of the compiled code is done using a separate program, usually AVRDUDE or bossac, and the code is uploaded into flash. Data can be optionally uploaded into EEPROM via the same program, but this is not required.

  which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

Not by default. If you want to use DuinOS then you will need to download, compile, and upload it yourself.

  My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

Nope. Any system can be run without an OS.


Arduino Nano burns with ESP-01 in parallel So I have an Arduino Nano powered in parallel with an ESP-01 (for the ESP there is an extra LM1117-5.0 voltage regulator in series).

+12V ---------+---------+
              |         |
             Reg        |
              |        NANO
             ESP        |
              |         |
 GND ---------+---------+

My problem is that after a while, the Nano burns (my guess is the difference in current that both devices draw).

In any case, what could be the reason and what could I do to fix it?

Thanks!

Use the 5v regulator to power both the ESP and the Nano. Those onboard regulators have minimal heat dissipation and if they burn out you lose the whole Nano. Check how hot your external regulator gets and mount it on a heat sink if it gets too hot to touch.
NB Connect the regulator output to the Nano 5v pin directly


Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible? Is it possible to sandwich an XBee shield between Arduino Mega and Ramps 1.4 without damaging any of the boards or lose of Ramps functionality ?

I am not trying to make a 3D printer it is rather a completely different project and I am afraid of burning my XBee or losing some functionality of ramps.

Since XBee shield has the form factor of Arduino UNO I had to 3D print the rest of the shield and use some connectors to completely cover the Mega.

Yes, it would seem like folks on the RepRap forums have gotten this to work with the following setup that should work in general:

  Attach the XBee shield to the RAMPS board by attaching 4 pins on AUX-1 (namely, 5V, Gnd, D1 and D0) to the 5V, Gnd, Rx and Tx pins on the XBee Shield

  Switch the UART / DLINE switch on the XBee Shield to UART

Source: RepRap Forum: Printing completely wirelessly - can it be done?

This forum thread may also be useful.


Reading setting from microSD I modified the SD sketch for ESP8266 to read WIFI setting from a file named CONFIG.TXT. The text file's content format is SETTING=VALUE. Ex.

SSID=AP001
KEY=AP001

I manage to separate the SETTING and VALUE
My code:

#include <SPI.h>
#include <SD.h>

File myFile;

void readWifiConfig() {
  Serial.println("Initializing SD card...");
  char temp;
  bool isSetting = true;
  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (isSetting == true) {
        if (temp == '=') {
          Serial.print("="); //Writes '=' to console
          isSetting  = false;
        }
        else {
          Serial.print(temp); //Writes SETTING part to console
        }
      }
      else {
        if (temp == '\n' || temp == '\r') {
          isSetting = true;
          }
        else {
          Serial.print(temp); //Writes VALUE part to console
          }
        }
    }
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
}

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

}

Output:

Initializing SD card...
Initialization done.
CONFIG.TXT
SSID=AP001
KEY=AP001

I want to write the values to their corresponding variables and I don't know how.

char* ssid;
char* key;

Somehow I managed to do it but my code is un-optimized. Please let me now if I've done something that isn't good.

I changed the content format to this so it's much easier for me. (CONFIG.TXT)

SSID%&WIFIAP001&%KEY%&PASS1234&

New Code.

#include <SPI.h>
#include <SD.h>

File myFile;
char wifiSsid[63];
char wifiKey[63];
char temp;
char settingSsid[5] = "SSID";
char settingKey[4] = "KEY";
char settingTemp[10];
char valueTemp[63];
int settingTempLastPos = 0;
int valueTempLastPos = 0;
int percentCount = 0;
int andCount = 0;
bool isSetting = true;
bool ssidValueFound = false;
bool keyValueFound = false;

void readWifiConfig() {
  Serial.println("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (temp == '%') {
        percentCount++;
        isSetting = true;
        if (percentCount == 2) {
          //Serial.println(settingTemp);
          if (strcmp(settingSsid,settingTemp) == 0) {
            Serial.println("SSID SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            ssidValueFound = true;
            }
          else if (strcmp(settingKey,settingTemp) == 0) {
            Serial.println("KEY SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            keyValueFound = true;
            }
          memset(&settingTemp[0], 0, sizeof(settingTemp));
          settingTempLastPos = 0;
          percentCount = 0;
        }
      }
      else if (temp == '&') {
        andCount++;
        isSetting = false;
        if (andCount == 2) {
          //Serial.println(valueTemp);
          if (ssidValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiSsid,valueTemp,63);
            //Serial.println(wifiSsid);
            ssidValueFound = false;
            }
          else if (keyValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiKey,valueTemp,63);
            //Serial.println(wifiKey);
            keyValueFound = false;
            }
          memset(&valueTemp[0], 0, sizeof(valueTemp));
          valueTempLastPos = 0;
          andCount = 0;
        }
      }
      else {
        if (isSetting == true) { //setting
          settingTemp[settingTempLastPos] = temp;
          settingTempLastPos++;
        }
        else if (isSetting == false) { //value
          valueTemp[valueTempLastPos] = temp;
          valueTempLastPos++;
        }
      }
    }
    //Serial.println(settingTemp);
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
  Serial.println(wifiSsid);
  Serial.println(wifiKey);
}

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

}

Output:

Initializing SD card...
Initialization done.
CONFIG.TXT
SSID SETTING FOUND
KEY SETTING FOUND
WIFIAP001
PASS1234


What are a few good ways to connect multiple I2C busses? I have an issue with a project. I have a backplane with an Atmega328P based microcontroller controlling an I2C bus with multiple peripheral devices. One such peripheral is a removable card with another Atmega328P based microcontroller as the peripheral. I have a TCA4311ADR I2C hotswap buffer on the backplane connected to the port that connects to the card. The card is supposed to be a peripheral device that sends processed data from a sensor to the backplane.
Here’s my issue: one of the sensors I intend to use on the card is an I2C breakout board. To control it, the microcontroller on the card needs to act as a controller, but it also needs to be a peripheral to communicate with the backplane controller. Every time I try to make this work and the card tries to communicate with the sensor, it tries to start a new I2C bus and everything starts glitching.
I’ve tried a few options. Software used to turn normal digital pins into I2C pins didn’t work since the libraries don’t seem compatible. I can’t seem to get the card peripheral to wait until the controller starts the bus before trying to control the sensor to avoid a conflict.
I had an idea to use an I2C multiplexer like the TCA9543A to create two busses but I don’t know if that would work. I also don’t wanna just use SPI or Serial to connect the microcontrollers cause I’d have to undo months of work on coding and custom PCBs. Also using Serial would complicate the connection to the computer and using SPI wouldn’t work if I use an SPI sensor breakout later.
Is there any other way to make this system work?

In an ideal world you would have your other sensor on a separate I2C bus. It can be done with software, but chances are you will have to re-write the library that supports it to use bit-banged I2C.
Yes, you could use an I2C MUX to share the single hardware I2C channel, however that will both be awkward and the results will be sub-optimal anyway.
Most I2C MUX chips, including the TCA9543A, are controlled themselves by I2C, so you can't really use them in your environment, since you really need to switch it to isolate your main bus from the MCU before you switch it from slave to master, which you can't do until after you have switched it from slave to master. If you switch to master before isolating the bus you risk a collision with the main master on the bus and everything going horribly wrong.
These MUX chips are really designed for allowing one master to talk to multiple slaves that share the same addresses.
And on top of that when you've isolated the bus the main master will no longer be able to communicate with that slave board, which will either cause the whole bus to lock up or other strange and unwanted things to happen.
So have another go at using software I2C to communicate with your sensor. Most I2C communication to sensors is pretty straightforward and follows the same rough format, so it really shouldn't be too hard to implement.
Either that or consider replacing the ATMega328P with a more capable microcontroller that has multiple I2C busses.


Asynchronous control framework Can anyone recommend an Arduino-based asynchronous scheduling library for controlling a small mobile robot?

I'm writing the control code for a small 2-wheeled Arduino-Uno based robot. It has a few bumper sensors, IR sensors, and ultrasonic sensors. I've written an initial pass from scratch, using loop() to read sensors and set motor values appropriately and then wait for the motor to have effect, but I'm finding this cluggy. Some of the sensors, like the ultrasonic range finders, require a small delay to operate, and the motors require a delay to have an effect. Blocking loop() is the simplest way to achieve this, but it wastes cycles, and can be difficult to time each action properly without throwing off other behaviors. Writing an asynchronous scheduler would be more efficient, but a lot more complicated, and I expect I would be reinventing the wheel.

I found this list, of existing scheduling libraries, but I'm not sure which, if any, would be appropriate.

I recommend writing your own in C++.  Arduino works well with C++ as it is written in C.  You can focus on getting the asynchronous behavior to do what you need instead of writing drivers.  I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.

Igor points out the advantages of going to a real time operating system.  I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.


Stepper motor with HCSR-04 sensor I want to make a stepper motor increase and decrease speed working with a HCSR04 sensor. The idea is that if the sensors detects an object the stepper motor is going to decrease, and stop as close as possile to the object.

I have made some code, and it is sorta working..

My current code looks like this:

if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

But I thought it could be easier, So I made a function:

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

Now my question is: Can I manipulate the delayMicroseconds to change if the distance changes? Is there a formula to do so?

Entire code:

int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm ");
 Serial.print (distance);

//eigen creatie

if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

//Own functions
}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

void rotateleft()
{
 digitalWrite(12,HIGH); // Set Dir high
 for(int x = 0; x < 200; x++) // Loop 200 times
  {
    digitalWrite(13,HIGH); // Output high
    delayMicroseconds(1000); // Wait
    digitalWrite(13,LOW); // Output low
    delayMicroseconds(1000); // Wait
   }
  }
  void rotateright()
  {
   digitalWrite(12,LOW); // Set Dir high
   for(int x = 0; x < 200; x++) // Loop 200 times
   {
     digitalWrite(13,HIGH); // Output high
     delayMicroseconds(1000); // Wait
     digitalWrite(13,LOW); // Output low
     delayMicroseconds(1000); // Wait
   }
 }

Assuming you have a distance variable containing the distance measured from your sonar sensor in cm. You can use that value to adjust the delay times in between your steps.

EDIT Modified code to increase speed when distance increases

int time = 0;
int timeWait = 1000; //interval in milliseconds between each distance reading
int maxDelay = 1000;

void velocity(int speed){
   int trim = 10;
   digitalWrite(13,HIGH); // Output high
   delayMicroseconds(maxDelay - speed*trim); // Wait
   digitalWrite(13,LOW); // Output low
   delayMicroseconds(maxDelay - speed*trim); // Wait
}

int readDistance(){
 //code to read distance
 return distance;
}

void setup(){
time = millis();
}

void loop(){
   if(millis()-time > timeWait){ //only read distance if 1000ms has elapsed since the last reading
     time = millis();
     int distance = readDistance(); //your distance reading code;

   }
   velocity(distance);
}`

EDIT 2
You'll also need something to handle upper and lower limits for delays (i.e. you don't want delayMicroseconds(0) or any negative numbers and  you don't want to include extraneous distance readings)


RFID RF522 kit for access control I am trying the RFID RC522 reader kit with an Arduino UNO to built a controlled access system for a door.

Using the code below, I am able to read the UID of my card and light up an LED when the reader detects the card or the badge, however it will light up whatever card is presented to it even if the UID of this card is not entered as a String in my program.

My question is how can I enter hundreds of cards (depending on memory) that will unlock the door and have all the others set as unknown if not in my program.

Thank you very much for your help

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

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         //(or SDA) Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
// ===========================================================================
String read_rfid;
String ok_rfid_1 = "C5 12 E3 52"; // for the badge
String ok_rfid_2 = "9A 48 3A D5"; // for the card
// ==========================================================================
int led = 3;
// ===========================================================================
void setup() {
 Serial.begin(9600); // Initialize serial communications with the PC
 //while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
 SPI.begin(); // Init SPI bus
 mfrc522.PCD_Init(); // Init MFRC522
 mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
 Serial.println(F("Scan PICC to see UID, SAK, type, and data bleds..."));
  pinMode(led, OUTPUT);
}
// ===========================================================================
 void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid="";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
 }
// ==========================================================================
void unlock() {
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}
// ======================================================================
void loop() {
 // Look for new cards
 if (! mfrc522.PICC_IsNewCardPresent())
 return;
 // Select one of the cards
 if (! mfrc522.PICC_ReadCardSerial())
 return;

  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);

  if (read_rfid == ok_rfid_1 || ok_rfid_2) {
    Serial.println("Open");
    unlock(); // turns LED on
  }

  else {
    Serial.println("Stay Closed");
  }
}

Your IF statement is the problem. if (read_rfid == ok_rfid_1 || ok_rfid_2) always evaluates to True. Your condition should be:

if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.

This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:

#define ALLOWED 2   // no of allowed cards
byte read_card[4];   // same purpose as before
bool found = false;  // to know when a valid card match occurs
byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                         {0x9A, 0x48, 0x3A, 0xD5}};

Then you should get rid of dump_byte_array() and compare cards like this:

memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

for (int i = 0; i < ALLOWED; i++){
  if (memcmp(read_card, cards[i], 4) == 0){

      found = true;
      break;
  }
}

if (found){
  Serial.println("Open");
  unlock(); // turns LED on
  found = false;
}
else {
  Serial.println("Stay Closed");
}


Serial device file no longer shows up in /dev/ after working fine for months I am using an Arduino MEGA connected to my Linux workstation via USB. I have been using this setup for several months with no issues.

A few days ago, the usual serial device file (/dev/ttyACM0) stopped showing up when I plug in the device)

Haven't re-flashed recently.
Unable to reflash.
Removing the devices only shield does not do anything.
Have not changed my physical setup recently.
Connector cable is confirmed working with a different device.

Is this a case of bad hardware, or is there a possible fix other than buying a new device?

dmesg results: None (cleared buffer and re-ran dmesg after plugging / unplugging device)
usb-devices:

T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1a.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1d.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=02 Prnt=02 Port=03 Cnt=01 Dev#=  3 Spd=480 MxCh= 0
D:  Ver= 2.00 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1bcf ProdID=2805 Rev=20.15
S:  Manufacturer=6047B0021601A0218M7NB
S:  Product=HP HD Webcam [Fixed]
C:  #Ifs= 2 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=0e(video) Sub=01 Prot=00 Driver=uvcvideo
I:  If#= 1 Alt= 0 #EPs= 0 Cls=0e(video) Sub=02 Prot=00 Driver=uvcvideo

T:  Bus=02 Lev=02 Prnt=02 Port=05 Cnt=02 Dev#=  4 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=0bda ProdID=0001 Rev=68.17
S:  Product=CSR BS8510
C:  #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
I:  If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb

T:  Bus=03 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=04 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=5000 MxCh= 2
D:  Ver= 3.00 Cls=09(hub  ) Sub=00 Prot=03 MxPS= 9 #Cfgs=  1
P:  Vendor=1d6b ProdID=0003 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

ls-usb:

Bus 002 Device 004: ID 0bda:0001 Realtek Semiconductor Corp.
Bus 002 Device 003: ID 1bcf:2805 Sunplus Innovation Technology Inc.
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

The fact that dmesg gives you nothing at all is the most telling fact.  The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"

We can ignore the main ATMega2560 chip since that has no bearing on the USB interface.  Instead we're interested in the ATMega16U2 (or whatever is on your board version).

So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

Check that there is power to the board through the USB.
Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
Grab the datasheet for your ATMegaxxU2 chip and get the pinout.  Check that there is power on the pins there should be power on.
Check that the RESET pin of the ATMegaxxU2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID.  Try to re-flash the USB interface firmware.

Another thing to check is the USB socket itself.  Those big chunky USB sockets look strong, but they're actually quite flimsy inside.  The metal leaves that the plug presses against can bend with time and not make a good contact.  Using a fine needle try lifting them up slightly so they make better contact with the cable.  I think Arduino are the only people that still use them in an active product these days ;)


Multiple transmitters and problem with ref There are three Arduinos on a model. Each of them has a DS18B20 Dallas temperature sensor and an nRF24L01 antenna wireless communication. There is also an independent device consisting of an Arduino and an nRF24L01 antenna. Device acts as a receiver. Arduino and antenna play the role of transmitter. The code is:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Wire.h>

int temp1;
int WindSpeed;
int temp2;
int temp3;
RF24 radio(7, 8);
const uint64_t pipes[3] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL};
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(0, pipes[1]);
  radio.openReadingPipe(1, pipes[2]);
  radio.openReadingPipe(2, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&temp1, sizeof(temp1));
     Serial.println("Temp1:");
     Serial.println(temp1);
     delay(50);
     radio.read(&WindSpeed, sizeof(WindSpeed));
     Serial.println(" WindSpeed Bf : ");
     Serial.println(WindSpeed);
     delay(50);
     radio.read(&temp2, sizeof(temp2));
     Serial.println("temp2:");
     Serial.println(temp2);
     delay(50);
     radio.read(&temp3, sizeof(temp3));
     Serial.println("temp3:");
     Serial.println(temp3);
     delay(50);
  } else {
    Serial.println("No radio Data avaliable");
  }
  delay(3000);
}

The problem is that the code sends some values but the correspondence isn't right in AnalogRead. How can I watch each pipe with the antenna of corresponding Arduino in order to have the right results, and each Arduino sends to the receiver through its own antenna the value of its sensor?

Thanks all for your time!

You want to send data from 3 (or 4?) different Arduino transmitters to one Arduino receiver and you want to be able to distinguish the packets sent by each transmitter as they are received. The most straightforward way is to create a struct for your data and attach a unique header and trailer that can be used to identify the sender.

typedef struct {
  uint8_t header = 0x01;
  int temp1;
  uint8_t trailer = 0x10;
} PACKET;

Something like this should be present in each transmitter but with unique header and trailer for each one. Then the receiver should have the header and trailer bytes for all the transmitters and, whenever it receives data, it checks the first received byte against the list of header bytes to know who sent the data before it continues. Finally, it checks the last byte to know if it's the correct trailer byte for the assumed sender and also as an additional (but perhaps unnecessary) layer of error detection to know if the received packet is a complete valid one.


Why need a delay between readings? When I learn the tutorial in

Analog Read Serial
Digital Read Serial

both of the code examples have a line of code of delay(1) and I cannot understand the comments clearly:

 delay(1);        // delay in between reads for stability

The stability for/of what?

Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).

Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".


How to stop OLED flicker when using SSD1306Ascii.h? Why does the OLED display flicker when using the SSD1306Ascii.h library? The Adafruit library does not have this issue, but I've been told uses a lot of memory and so I'm trying to use Ascii to conserve memory resources. The problem manifests itself when the void loop() begins. When using similar code with the Adafruit library, the display stays steady as a rock.

Here is my example code. many thanks in advance.

// Edit AVRI2C_FASTMODE in SSD1306Ascii.h to change the default I2C frequency.

#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
//------------------------------------------------------------------------------
void setup() {

#if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(System5x7);
  oled.clear();
  oled.print("Hello World!");
  delay(2000);
  oled.clear();

}
//------------------------------------------------------------------------------
void loop() {

  oled.setFont(System5x7);
  oled.print("Hello fuuuzzzzyyyy world!");
  delay(1);
  oled.clear();

}

Your loop is repeatedly writing and clearing the display, nearly as fast as possible (minus the 1ms delay at the bottom), which is the reason for the flicker you're seeing. If instead, you only update the display when something changes, it will look much smoother. Even a clear-and-rewrite the entire display when something changes (assuming the changes are infrequent) will be a major improvement. Of course this assumes you'd eventually be writing dynamic data; your test program, of course, writes and re-writes static data.

Update:

  If I run the same code structure with Adafruit library there is no
  flicker, even with no delay in the loop.

Can you compare the two libraries to see what they do differently?

  The Adafruit library does not have this issue, but I've been told uses
  a lot of memory

There's a likely clue: Adafruit may be buffering the display contents in memory so it can find out which character positions changed and update only those. That would be a classic time/space trade-off.


Will writing to serial when no serial is available cause problems? I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?

No, that will not cause any problem.

What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected and the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.

This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.


Unable to receive data when using multiple SoftSerial on Arduino Nano I am trying to use several (four) software-based serial ports to talk to different peripheral hardware. However, I am unable to receive data through the SoftSerial when using more than one software serial port.

I tested each pair of pins be defining it to the first port. All pairs are working as desired. In addition, I am only interested in bridging/piping from a software serial port to the hardware serial (for debugging reasons).

My code is as follows:

#include <stdint.h>
#include <SoftwareSerial.h>

#define SOFT_SERIAL_A_RX        5
#define SOFT_SERIAL_A_TX        6
#define SOFT_SERIAL_B_RX        7
#define SOFT_SERIAL_B_TX        8
#define SOFT_SERIAL_C_RX        9
#define SOFT_SERIAL_C_TX        10
#define SOFT_SERIAL_D_RX        11
#define SOFT_SERIAL_D_TX        12

#define SERIAL_BAUD_RATE        9600

SoftwareSerial softwareSerials[] = {
    SoftwareSerial(SOFT_SERIAL_A_RX, SOFT_SERIAL_A_TX),
    // Unable to receive data on first software serial when un-commenting following lines.
    // All pins are working when declaring each pair for first software serial (tested pins by doing this)
    // SoftwareSerial(SOFT_SERIAL_B_RX, SOFT_SERIAL_B_TX),
    // SoftwareSerial(SOFT_SERIAL_C_RX, SOFT_SERIAL_C_TX),
    // SoftwareSerial(SOFT_SERIAL_D_RX, SOFT_SERIAL_D_TX)
};
const uint8_t numberSoftwareSerials = sizeof(softwareSerials)/sizeof(*softwareSerials);

void initHardwareSerial()
{
  Serial.begin(SERIAL_BAUD_RATE);
}

void initSoftwareSerials()
{
    for(uint8_t i=0; i<numberSoftwareSerials; i++) {
        softwareSerials[i].begin(SERIAL_BAUD_RATE);
    }
}

void setup()
{
    initHardwareSerial();
    initSoftwareSerials();
}

void loop()
{
  // Only one software serial can be used (receive/transmit) at once.
  // So just using a single software serial port (first element from array)
  if (softwareSerials[0].available()) {
    Serial.write(softwareSerials[0].read());
  }
  if (Serial.available()) {
    softwareSerials[0].write(Serial.read());
  }

}

How can I narrow down the issue of being unable to receive when defining several serial ports? If there is no suitable solution I might switch to an Arduino Mega with its four hardware ports (would need only one additional software serial in that case), but an Arduino Nano is strongly preferred due to smaller footprint.

You cannot receive on more than one SoftwareSerial port. It's sad, but that's the way it is.

You can manually select which port you are listening to at any time with the softwareSerials[x].listen() function, but only one can ever listen at a time.

SoftwareSerial is a fudge at best and should only be used for one port and even then only if you really have to.


How do you configure ADC7 on the Arduino Pro Mini as a digital output? I'm attempting to use the pin labeled 'ADC7' from the Atmega328p TQFP package. The Atmega documentation suggests that can be used either as an analog or digital I/O point. I'm trying to configure it as a digital output.

Referencing the documentation (and specifically arduino_pins.h), I determined the associated pin number was 21. Thus I called pinMode(21, OUTPUT). However, this pin does not appear to be working with my SPI device. I previously tested that the device worked, but I made a last second change of pin and am now using ADC7.

So my question, is there an additional step required to configure this pin as a digital output? I noticed that this pin doesn't exist on the DIP Atmega328p (used on the Arduino Uno), so I'm not sure if I have to add another line of code somewhere.

Any ideas?

Regards,

This may be a little left field, but I use the ADC6 and ADC7 inputs to detect switches.  I just don't use the digitalRead() function, but instead use analogRead() function.  Using a resistor network and switches and some decoder software code in our sketch, we can use a single input pin to interface with many more switches.  The switches can only be on one at a time, but in many instances, this would be OK.


How do I use two I2C LCDs with 4 pins? I have two I2C LCD screens:

one with 2 lines
one with 4 lines.

Both have 4 pins each: GND, VCC, SDA, SDL. I connect SDA and SDL to A4 and A5 respectively, and I display text on each one of them with:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,4);

But how can I use both of them at the same time?

I connected the second one's SDA and SDL to A2 and A3, but apparently I have to provide the right address for them (like 0x27), right?

However, while both are connected, using I2C_Scanner only shows one device:

Scanning...
I2C device found at address 0x27  !
done

What am I missing?

With the I2C backpack there are three pairs of landings, A0, A1, A2, which determine the 3 LSB of the device's address, using inverted binary.

Left alone, they generate part of the F or 7 part of the address.  0x3F is common, as is 0x27.

To use more than one device it is necessary to jumper them all uniquely.

The upper bits that generate the 0x3 are hard-wired.  So is the highest bit of the lower byte.  Only the three lowest-order bits can be changed.

Since these address bits are inverted, jumpering the A0 will subtract 1 from the address.  0x3F will become 0x3E, 7 will become 6.

You have control enough to make up to 7 LCD modules on the same I2C bus.

The only caveat is that if you have more than one device writing to the various LCDs you might get collisions, which can mess up the display pretty good.

There are questions on I2C collision avoidance and detection on http://RaspberryPi.StackExchange.com if that is your situation.

Jumpering one or more of them is pretty easy - just pre-tin some wire and solder it quickly then cut off the excess.

Wire the SDA and SCL wires of the LCDs in parallel and to the SDA and SCL pins on the Arduino, usually A4 and A5.  (I always begin with a breadboard for this).  Make sure you have discrete pull-up resistors (10K is common) on each, in only one place on the bus.

If you have a DS3231 RTC module in the system, you do not need to add pull-ups because it has them internally.

If one LCD is already working then you know you have proper pull-up voltage on the bus.  (The signals are switched to the ground state to send data on the I2C bus)

So, to Summarize:

If you have two LCDs in your system you can use LCD modules that already come with different addresses, like

LiquidCrystal_I2C lcd1(0x27,....);

for the first one, then

LiquidCrystal_I2C lcd2(0x3F,.....);

for the second one.

Note that the parameters for these definitions are

LiquidCrystal_I2C lcdname(addr,en,rw,rs,d4,d5,d6,d7,bl,blpol);

0x27 and 0x3F are the most common stock addresses and 0x27 modules are getting harder to find.

If you have a 0x27 then it is very likely that if you buy a newer one it will be 0x3f. Problem solved.

The d4 and d5 in the definition specifies the pins to use for I2C.

You can run the i2cscanner program to see what it finds, once they are wired together.  If you see two different addresses, say 0x27 and 0x3F, then you are good to go.

If only 2F shows, then you want to consider soldering A0 together on one module then run the scanner again to make sure it worked.

Here is how I usually do it when both come set as 0x3f:

I have a Yellow one which is a stock 0x3F and a Blue one where I jumpered A0 to make it 0x3E.  They both are 20 x 4 displays.

Here are my definitions:  (remember, the 4,5 define SDA, SCL pins)

LiquidCrystal lcdblue  (0x3e,2,1,0,4,5,6,7,3,POSITIVE);
LiquidCrystal lcdyellow(0x3f,2,1,0,4,5,6,7,3,POSITIVE);

Then in setup() I use this:

lcdblue.begin(20,4);
lcdblue.backlight();
delay(250);
lcdblue.nobacklight();
delay(250);
lcdblue.backlight();

lcdyellow.begin(20,4);
lcdyellow.backlight();
delay(250);
lcdyellow.nobacklight();
delay(250);
lcdyellow.backlight();

And it's good to go, using pin A4 as SDA and A5 as SCL.

You know they are working as they wink their backlights at you.

If one of yours is 20 x 2 then use lcd2.begin(20,2); of course.

If you REALLY want to use other pins for your I2C bus then just change the 4,5 in the LiquidCrystal_I2C definition to the pins you want to use.  I never have met anyone who would want to do this.

Hope this helps.


Sending to Arduino UNO multiple values from Python code I'm starting to learn how to work with Arduino, particularly communication between a Python code running on a PC and an Arduino Uno.

So I decided to start with what I thought to be a easy task. That is, sending the user input from Python. There are 2 values, one delay between Arduino LED (port 13) and the servo angle.

It didn't work and I couldn't find any answers, hope you can help me.

Arduino Code -

#include <Servo.h>

const int ledPin = 13; // pin the LED is attached to
int incomingByte = 1000;      // variable stores  serial data
int pos = 0;
int incoming[2];
Servo myservo;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  myservo.attach(9);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);
   myservo.write(180);
   delay(1000);
   digitalWrite(ledPin, LOW);
   myservo.write(0);
}

void loop()
{

  if (Serial.available()>=2)
  {
     for (int i = 0; i < 1; i++)
     {
      incoming[i] = Serial.read();
     }
    digitalWrite(ledPin, HIGH);
    delay(incoming[0]);
    digitalWrite(ledPin, LOW);
    myservo.write(incoming[1]);
  }
}

Python (3.7) code -

import serial
import time

ser = serial.Serial('COM5', 9600, timeout=1)

user_input = '1'
while user_input != 'q':
    user_input = input("'Blink time is or q = quit' : ")
    servo_input = input("What position servo go? ")
    byte_command = str.encode(user_input)
    ser.write(byte_command)
    servo_command = str.encode(servo_input)
    ser.write(servo_command)
    time.sleep(0.5)

print('\nq entered. Exiting the program')
ser.close()

Well I did it in the simplest way.

I just sent a string to C++ and deconstructed it with sscanf().


ESP8266 Wifi.setOutputPower - original/default value? I'm working on dynamically adjusting the ESP8266 WiFi power using the following function, such that it's as low as possible, yet sufficiently reliable:

WiFi.setOutputPower(x)

I've been trying unsuccessfully to find out what the original/default value is before that function is called? There is no function WiFi.getOutputPower(). I know the range of values is 0 to 20.5, but I'm curious to know what it is initially? I guess it could depend on the particular Arduino? I have the following: ESPduino, Wemos D1R2/D1R1/D1R1 mini, NodeMCU, Yun sheild.

I plan to use iwconfig & iwlist on a Pi3 to measure the RSSI, but I'd like to know the baseline if possible.

The best similar idea is expressed in here: : How to optimise TX power for ESP8266?

Thanks in advance ;-)
Geoff

I was looking for the same answer. I found this link: https://gitlab.com/painlessMesh/painlessMesh/issues/51

Someone dug deeper into the code and found it's set to the max value on init


Ignore event until x minutes I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.

Here is the code I come up with:

if (digitalRead(sensor_event)==HIGH)
  {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute > time_pushed+5)
                           time_set=0; // Unlock
                 }
               else
                 {
                        if (tm.Minute >= 55)
                          time_pushed=0;
                        else
                          time_pushed=tm.Minute; // Set global volatile min value

                        print("Sensor event");
                        time_set=1;
                 }
      }
  }

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.

The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).

Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.

Thanks

Use the millis() function instead if you can accomodate a rollover after 50 days.

Take a reading of millis() at the start time.
time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.