How to read shiftOut function using arduino (I'm sorry for my bad English, but I will do my best)

I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)

After some research, I found that it can be talk to LED driver using shiftout function.

Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.

To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:

arduino UNO side (to send shiftOut function)

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

arduino mega side (to read shiftOut function)

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.

Please any one has any ideas?

You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.

You trigger it using the "STB" pin:

if (digitalRead(STB) == LOW) {
    uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
    Serial.println(val, HEX);
}

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.

Resources:

https://www.arduino.cc/en/reference/SPI
http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.


Arduino I2C communication between Raspberry Pi We are trying to communicate between multiple Arduino's (in this example a Nano and a Mega) and a Raspberry Pi. The Raspberry pi is defined as master and the Arduino's as slaves. We would also like that the Arduino's communicate between each other. For example: The Mega requests from the Nano and at some point, the Mega also communicates with the Raspberry Pi. This is the short version of what we are trying to accomplish but we ran into the problem that the i2c communication failed between the Nano and Mega upon the request from the Mega to the Nano.

Schematic

Problem

After some time the i2c bus 'fills' up...

Code Nano

(We send RFID data to Mega)

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

#define SS_PIN 10
#define RST_PIN 9
#define SP_PIN 8

MFRC522 rfid(SS_PIN, RST_PIN);

MFRC522::MIFARE_Key key;

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();

  Wire.begin(0x10);
  Wire.onRequest(requestEvent);
}

void loop() {

}

void requestEvent() {
  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
    return;

  // Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  // Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
      piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
      piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  String strID = "";
  for (byte i = 0; i < 4; i++) {
    strID +=
      (rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
      String(rfid.uid.uidByte[i], HEX) +
      (i != 3 ? ":" : "");
  }
  strID.toUpperCase();
  //81:AE:1D:29
  Serial.print("Send to Mega: ");
  Serial.println(strID);

  Wire.write(strID.c_str());

  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();

}

Code Mega

#include <Wire.h>

void setup() {
  Wire.begin(0x03);
}

void loop() {
  Wire.requestFrom(0x10, 11);

  String uid = "";

  while (Wire.available()) {
    char c = "";
    c = Wire.read();
    uid += c;
  }

  if (uid.indexOf(':') != 2) {
    return;
  }

  Serial.println(uid);

  delay(500);
}

We would like to communicate between the Arduino's when the Raspberry Pi is master.

Its a long time since I used a Pi, but isn't it a 3.3V device and the Arduinos are 5V devices.  I think you may need a logic level shifter (not a resistor divider).  I suspect that's the reason I2Cdetect isn't working and without that working, nothing else will.


Inconsistent response AT command I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters

Response
+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20

Expected response
+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,

Code:

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

String inputString = "";
char inChar;

const int powerkey =  5;
const int statuspin = 6;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(powerkey, OUTPUT);
  pinMode(statuspin, INPUT);

  mySerial.println("AT");
  delay(2000);
  leserial();

  //TURN ON GPS
  mySerial.println("AT+ CGNSPWR =1");
  delay(2000);
  leserial();
}

void loop() {
  //GET LOCATION
  mySerial.println("AT+CGNSINF");
  delay(4000);
  leserial();
  delay(5000);
}

void leserial(){
  inputString = "";
  while (mySerial.available()>0){
    inChar = mySerial.read();
    inputString += inChar;
  }
  Serial.println(inputString);
}

Basically you're sending a command that gives a response, then waiting 2 seconds for that response to arrive (which is completely the wrong thing to do to start with).

You have to ask yourself: where does that response go when it does arrive, while it's waiting for you to finally get around to reading it?

The answer is: into a small internal buffer that is considerably smaller than the response.

Thus most of the response just gets thrown away because there isn't room for it.

Instead you should most definitely NOT delay for 2 seconds waiting for the response, and instead keep looking to see if there are any characters to read up until you reach the end of the line.

It's all explained here: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


Arduino IDE loses programmer after installing Visual Micro I had this added to programmers.txt

mysmartusb.name=mySmartUSB light
mysmartusb.communication=serial
mysmartusb.protocol=stk500v2
mysmartusb.program.protocol=stk500v2
mysmartusb.program.tool=avrdude
mysmartusb.program.extra_params=-P{serial.port}

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.


ESP8266 GET REPLY ERROR 501 I am trying to build a home automation system and i am unable to get data from a website using the arduino sketch, however i am able to get data from the website when i enter the AT commands into the serial monitor.Below is my sketch:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(4,5);

void setup(){
  Serial.begin(9600);
  esp8266.begin(115200);
  esp8266.println("AT+CIPMUX=1\r\n");
  delay(2000);
  esp8266.println("AT+CIPSTART=0,\"TCP\",\"www.homeautomationserver.com\",80 \r\n");
  delay(2000);
  esp8266.println("AT+CIPSEND=0,75");
  esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
  esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");
}

void loop(){

  if (esp8266.available()){
    Serial.write(esp8266.read());
  }
  if (Serial.available()){
    esp8266.write(Serial.read());
  }
}

I get a 501 not Implemented error from the server.

Please Help.

Thanks

Your problem lies in these lines:

esp8266.println("AT+CIPSEND=0,75");
esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");

You are mistakenly using println() instead of print() when sending the data. That imposes its own <CR><LF> sequence on the end of the lines, yet you are adding the <CR><LF> manually.  You are also incorrectly specifying 75 characters to send, so the result of all that is:

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
\r\n                                                  2
Host:www.homeautomationserver.com\r\n                35
\r                                                    1
                                                   ----
                                                     75

I.e., your request is garbled. You need to change the println() to print() for the data printing and make sure the character count is correct:

esp8266.println("AT+CIPSEND=0,74");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Host:www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Host:www.homeautomationserver.com\r\n                35
\r\n                                                  2
                                                   ----
                                                     74

You should also include more detail and commands in your headers. Things like the length of the body (0 bytes) and the fact that the connection should be closed, and there really should be a space after the colon on the Host: header:

esp8266.println("AT+CIPSEND=0,113");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Connection: close\r\n");
esp8266.print("Content-Length: 0\r\n");
esp8266.print("Host: www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Connection: close\r\n                                19
Content-Length: 0\r\n                                19
Host: www.homeautomationserver.com\r\n               36
\r\n                                                  2
                                                  -----
                                                    113


Problems with Hardware Serial (UART) on Nano 33 BLE Sense my new Nano 33 BLE Sense arrived today.  I'm working on a project to send data from the the Nano via an Xbee S2C module to a receiver module connected to a Nano 33 IoT.  I had the project working before using an MPU6050 and Mega 2560 board which worked (using Software Serial on the Mega).  On the IoT side, I am using 'Uart XBeeRx  (&sercom0, 5, 6, SERCOM_RX_PAD_1, UART_TX_PAD_0);' to process the data from the Xbee.  Having tried this syntax on the BLE Sense I hit problems and after some Googling found a different syntax.  However my new code isn't working in so far as it compiles, uploads and then crashes the BLE Sense (serial port disappears from tools and the onboard LED blinks slowly and erratically).  I need to keep resetting the board and suspect there is some issue with my hardware serial implementation.  I've cut the code down to simply send accelerometer data.  My code is as follows - the EasyTransfer library simplifies the Xbee comms.  Any help appreciated!
#include <EasyTransfer.h>
#include <Arduino_LSM9DS1.h>

UART XBeeTx (digitalPinToPinName(6), digitalPinToPinName(5), NC, NC);

EasyTransfer ET;

struct SEND_DATA_STRUCTURE {

  float xAcc;
  float yAcc;
  float zAcc;

};

SEND_DATA_STRUCTURE myData;

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {

XBeeTx.begin(9600);

ET.begin(details(myData), &XBeeTx);

}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {

  float x, y, z;

if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);

  }

  myData.xAcc = x;
  myData.yAcc = y;
  myData.zAcc = z;

  ET.sendData();

}

You can't make calls to IMU if you haven't initialised it with IMU.begin()


Can a DC motor use more current than its datasheet? I am using small dc motors connected to the 5V of the arduino which is known to provide 200mA without damaging it.

The motor I am using is a very common one found in toys -> https://www.sparkfun.com/datasheets/Robotics/ROB-09608.jpg

As I see the maximum current of this motor is 170mA. Does it mean that the motor will not drain more current than that or it means that I need to use a resistor in series with my 5V in order to make sure the current will not pass 170mA?

YES (typically resulting in melting the coils). The current used by standard or brushless motors is related to the voltage applied and the load applied. As you approach the load limit, current rises over the limit. There are many ways to control this but controlling the load is the easiest way. DO NOT run the motor through the Arduino even if you think it will be under the 200mA limit. Motors produce a lot of spikes and back-flow.

Here's a tutorial on safely running a motor and controlling the speed: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview


Powering arduino sensors - what resistor should I use? Recently I have asked a question, why my sensors do not work on external power supply (link). I have found out, that I was limiting the current too much with the resistors. I have tried using two sensors:

DHT22, rated at 1.5mA max (picture of my module)
BH1750, rated at 190uA max (picture of my module)

My logic is, if they are rated at that current, I should put a resistor in the Vin, to restrict the current to given value. But it turned out that I was wrong, because they started working only after I removed my resistors.

My questions is - should I put a resistor in there? If yes, then how do I know what resistance should I have, if the data sheet values are misleading?

You should have NO resistor.

The datasheet states the current values the device will pull from the supply. Supplies DO NOT PUSH CURRENT.

Remove all resistors.

As long as the voltage is correct and the supply can provide at least as much current as all devices combined want to use then it will work.


Basic hardware debouncing I was watching Jeremy Blum's Arduino tutorial series, and he explained the need for debouncing in a simple circuit involving a pushbutton. Pressing the button once should mean the led stays on, and pushing the button again should mean the led should stay off, and so on.
He implemented hardware debouncing on this circuit: using an RC circuit along with an inverting Schmitt trigger.
https://www.youtube.com/watch?v=CRJUdf5TTQQ&list=PLA567CE235D39FA84&index=10 2:45-8:45.
However, the circuit isn't performing as expected, when I implemented the denbuncing. Its behaving as if the debouncing has no effect:-

If anyone wants to see the simulation:-
https://www.tinkercad.com/things/dniOQmnxJPY
Where exactly have I gone wrong? I have checked all the connections multiple times, it seems to be what Jeremy blum had in his video...

You did not change the lastbutton, but you compared it to HIGH. Change your code to the one below.
You can more easily avoid such mistakes, if you put spaces around operators.
//sp is switchpin, lp is ledpin

int sp=2; //interrupt enabled pin (interrupt 0)
bool ledon=LOW;
bool lastbutton=LOW;
int lp=9;
void setup()
{
  Serial.begin(9600);
  pinMode(sp, INPUT);
  pinMode(lp,OUTPUT);
}

void loop()
{

   if (digitalRead(sp)==HIGH && lastbutton==LOW){
      ledon=!ledon;
      lastbutton = HIGH; // previously here was lastbutton==HIGH;
   }

   else {
     lastbutton=digitalRead(sp);
      }
   Serial.println(ledon);
   digitalWrite(lp,ledon);

     }


Necessary torque of motor to move a door. I am building an automatic door opener and for its mechanism I need a motor with a high torque and low speed. My question here is how to measure the torque needed to move the door as I cannot really weigh the door and find its mass. Can anyone help me out?

You need a "hanging scale" preferably "analog one".

Mount it to any place of the door and slowly pool at 90 degrees. Check what value does the scale show when doors start moving. Static friction is always higher than dynamic friction.

Torque = Radius * Force

Raduis is the distance between mounting place and door hinges.
Force is 9.81 times max value shown by the scale in kilograms.

Do this many times for many mounting points then take average.
Use safety margin of 50% (motor should have at least 150% of required torque)


Adafruit Gemma unrecognised USB device on Windows 10 I have a V2 Adafruit Gemma from the Gemma starter pack, and I'm running Windows 10 Home (version 10.0.14393), on a 64-bit laptop. Following the  Introducing Gemma guide I've installed the Adafruit drivers and I'm now trying to get it to connect via USB.

After connecting, the board shows the green power LED, but not the pulsing red LED, and Windows shows the 'USB device not recognised' message.

Tried so far

I'm definitely using USB 2 ports, and I have tried it connected directly to the PC and via a USB hub.
I'm pretty sure the cable is working correctly (It works for exchanging data on a phone, and I've tried a few different ones).
Under Device Manager, the board shows as 'USB Device (Device Descriptor Request Failed)'.
'Update driver software' > 'Search automatically...' reports that 'The best driver software for your device is already installed'.
If I do 'Update driver software' > 'Browse my computer...' and point it to the manual Adafruit driver files (available on the link to the guide), I get the same message.

Can anyone suggest anything to try? Do I need to (re)install the bootloader itself, and if so, can you point me in the direction of how I do this?

Update

As mentioned in the comments I have posted on Adafruit's own support forum but got absolutely nothing yet. I have also tried it on my work PC (Windows 10 Pro, 64-bit) and got exactly the same behaviour.

I'm keen to get this sorted so bounty added for anyone who can at least come up with some suggestions of what to try!

I think, you've pretty much done everything. If you could gain access to another board, and try that one you could figure out more. Otherwise your symptoms remind me of a something called an ESD (Electrostatic Discharge) caused malfunction. This basically means one of the system essential chips on the board have been fried. It is very easy to ESD a chip without protection, just walk on a carpet or put on a sweater, and than touch the chip. Chances are you were electrostaticly charged with thousands of volts. The chip does not stand a chance. To prevent this from happening, touch something made out of metal before touching the board.More on ESD: Electrostatic discharge


Can I read two PWM signals and output two square waves on an UNO? My system requires that I read two independent PWM signals (60hz) and output two corresponding square waves. These output square waves vary in frequency according to their corresponding input duty cycle. The output frequencies will vary between 1-60Hz. (outside of tone() range)

I'm planning out the best way to approach this project.
My initial thought is to use the two available external interrupts set to CHANGE to measure the inputs. I believe I'll also need to reference a timer in this routine, to determine the time since the last change.

Unless I'm mistaken, it looks like I will also need a timer interrupt for each output, to control the frequency properly.

The Arduino UNO has 3 timers. timer0: 8bit (used internally), timer1: 16bit, and timer2: 8bit. In short, can I run all of these interrupts in the same code? Will I run out of timers, or can I multitask the timers between my requirements?

Thanks!

Your signals are slow enough that you may not need any timer. You can
just use the Arduino micros() function to handle all your timings. Of
course, micros() itself relies on Timer 0, but you don't need to
access any timer directly.

I would use the external interrupts in CHANGE mode to measure the duty
cycle. For example:

const uint8_t INPUT_0_PIN  = 2;  // digital 2 is also INT0
const uint8_t OUTPUT_0_PIN = 4;

// Measured duration of the HIGH level of input 0.
static volatile uint32_t input_0_high_time;

// Interrupt handler invoked when input 0 toggles.
static void on_input_0_change()
{
    static uint32_t time_rise;             // last time the signal rose
    uint32_t now = micros();
    if (digitalRead(INPUT_0_PIN) == HIGH)  // detected rising edge
        time_rise = now;
    else                                   // detected falling edge
        input_0_high_time = now - time_rise;
}

void setup()
{
    pinMode(INPUT_0_PIN, INPUT);
    pinMode(OUTPUT_0_PIN, OUTPUT);
    attachInterrupt(0, on_input_0_change, CHANGE);
}

For handling two inputs, you can duplicate everything that has a 0 in
its name and name it with a 1. If your signal is no slower than
60 Hz, you can also replace all uint32_t by uint16_t to make
the code slightly faster.

For generating the outputs, do something similar to the Blink Without
Delay example:

void loop()
{
    uint32_t now = micros();

    // Determine suitable period for output 0.
    uint32_t input_0_high_time_copy;
    noInterrupts();  // avoid race condition while reading
    input_0_high_time_copy = input_0_high_time;
    interrupts();
    uint32_t output_0_half_period =
            map(input_0_high_time_copy, 0, 16666, 8333, 500e3);

    // Toggle output 0 when needed.
    static uint32_t time_output_0_toggle;
    static uint8_t output_0_state;
    if (now - time_output_0_toggle >= output_0_half_period) {
        time_output_0_toggle += output_0_half_period;
        output_0_state = !output_0_state;  // toggle state
        digitalWrite(OUTPUT_0_PIN, output_0_state);
    }
}

Again, you can handle two outputs by duplicating the code and replacing
0 with 1. Note that you cannot replace uint32_t by uint16_t,
as it would not work for the slowest frequencies.

Edit: Now we may ask the question whether it is possible to use some
timers to make all this more accurate. The answer is yes, you could
achieve maximum accuracy by using four 16-bit timers:

You could use the input capture function of a 16-bit timer, with the
prescaler set to 8, to measure the transitions of one of your
inputs with a resolution of 0.5 µs.
You could use a 16-bit timer in CTC mode, with the prescaler set
to 256, to toggle one of your outputs at the desired frequency, with a
16 µs resolution.

For reference, micros() has a resolution of 4 µs. The 16 µs
resolution of the timer-generated output seems poor in comparison, but
the timer has the advantage of having zero jitter.

Now, for doing that that, you would need an Arduino Mega 2560. The Uno
has only one 16-bit timer, so it could help with only one of your two
channels.

There is still something you can do with a single 16-bit timer. Set it
to normal counting mode, with the prescaler at 8, and use it
instead of micros() for timing your inputs: in setup()

// Configure Timer 1.
TCCR1A = 0;          // normal counting mode
TCCR1B = _BV(CS11);  // clock at F_CPU/8

and in the interrupt handler, you replace uint32_t now = micros(); by

uint16_t now = TCNT1;

And now you have input_0_high_time (which should also be uint16_t)
in units of 0.5 µs.


Wemos D1 mini fatal exception I'm trying to flash a Wemos D1 mini ESP8266 board with the blink sketch, but get an error. The built in LED turns off when flashing starts.

Sketch uses 247872 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28000 bytes (34%) of dynamic memory, leaving 53920 bytes for local variables. Maximum is 81920 bytes.
warning: serialport_set_baudrate: baud rate 921600 may not work
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I tried changing the programming speed to most of the other options.

If I open the serial monitor and set the baud rate to 74880, I get the following message repeatedly.

Fatal exception (0):
epc1=0x400cd530, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

Is the board dead, or is there a way of reflashing it without using the serial port?

Flashing with the serial port is the only practical option. The flash chip can be removed, and it can be flashed off board, but that isn't practical.

Has the board ever worked? Have you used other RSP8266 boards before or is this the first you have? Do you have a different USB cable you can try? Marginal power can cause unpredictable operation.


Error compiling to teensy 3.6 Problem:

In short, the Arduino IDE won't compile a sketch for the Teensy 3.6. It gives the error:

exec: "A:\\arduino-1.8.5\\hardware\\teensy/../tools/teensy_post_compile": file does not exist
Error compiling for board Teensy 3.6.

What I have tried

-Re-installing teensyduino (And yes, I have it installed, along with a compatible Arduino IDE (version 1.8.5))

-completely wiping the IDE and re-installing

-using a different USB cable

Other information

The OS I'm using is Windows 10

A broken Teensy is not out of the question, as I have been doing some soldering on it and I may have slipped or something, although I don't think that's the problem

Thanks in advance.

I found a fix, it's not elegant or easy to use, but it works.

Steps to take

-Install a fresh version of teensyduino

-Make a copy of [arduino directory]/hardware/tools and save it anywhere as a backup (sometimes weird, buggy things happen)

-Make a copy of teensy.exe from the tools folder, and put it in the same directory as arduino.exe

-every time you run arduino.exe (don't double-click on a .ino file), first start teensy.exe and everything should work.

Sometimes, the tools directory gets deleted (It just seems a bit buggy), if that happens copy the backup and paste it where it should be ([arduino directory]/hardware/tools)

Also occasionally teensy.exe gets deleted, so make sure to have a backup of that as well.


ESP8266 Arduino Json object array deserialisation into struct I'm trying to de serialize an array of JSON objects into a struct.
Following the instructions given by the Arduino JSON assistant, I managed to produce this helper function:
void JsonPreprocessor(const char* buf)
{
  StaticJsonDocument<96> filter;

  JsonObject filter_ResponseData_Metros_0 = filter["ResponseData"]["Metros"].createNestedObject();
  filter_ResponseData_Metros_0["Destination"] = true;
  filter_ResponseData_Metros_0["ExpectedDateTime"] = true;
  filter_ResponseData_Metros_0["Deviations"] = true;

  StaticJsonDocument<512> doc;

  DeserializationError error = deserializeJson(doc, buf, DeserializationOption::Filter(filter));

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  JsonArray ResponseData_Metros = doc["ResponseData"]["Metros"];
  for (int i = 0; i < MAX_ELEMENTS; i++)
  {
    strcpy(dep_arr[i].destination, ResponseData_Metros[i]["Destination"]);
    strcpy(dep_arr[i].destination, ResponseData_Metros[i]["ExpectedDateTime"]);
  }
}

The function writes into an array of structs declared like this:
struct Departure {
   char* destination;
   char* departure;
   int  deviation;
} depart;

struct Departure dep_arr[MAX_ELEMENTS];

And the JSON passed as a constant character array to the preprocessor function. Uploading and running this function keeps crashing my ESP8266 without any debug output. Without posting the whole json object, which is long enough as is without the filters, My object array in JSON looks similar to this after filtering:
{
  "ResponseData": {
    "Metros": [
      {
        "Destination": "Destination_1",
        "ExpectedDateTime": "2021-04-29T05:15:30",
        "Deviations": 1
      },
      {
        "Destination": "Destination_2",
        "ExpectedDateTime": "2021-04-29T05:21:30"
      },
      {
        "Destination": "Destination_2",
        "ExpectedDateTime": "2021-04-29T05:30:30"
      },
      {
        "Destination": "Destination_1",
        "ExpectedDateTime": "2021-04-29T05:36:30"
      },
      etc...
    ]
  }
}

In my test code I've defined my MAX_ELEMENTS macro to be 3.
I'm at a complete loss due to not having any debug output. I'm using ArduinoJson6 and my code is written and compiled on Arduino IDE 2.0.0-beta.5

No memory is allocated for the strings.
You should declare your struct like so:
struct Departure {
   char destination[32];
   char departure[32];
   int  deviation;
} depart;

This assumes the max length for both strings is 31 characters.
Then, pass the max size to strlcpy():
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["Destination"], 32);
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["ExpectedDateTime"], 32);

If your strings are very long, you can use a String instead of char[].
See the example JsonConfigFile.ino, it shows all of this.


Need help modelling and coding a feedback scenario Above illustration is the basic setup for the question. The scenario will be the following:

  A potentiometer(providing 0 to 5V) is an analog input to A0. This
  potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which
  means the human controls directly the M1 fan speed.

  This directly speed-controlled M1 fan creates air pressure on a sensor
  Sen1.

  On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2
  should output the same voltage as Sen1. Which means eventually voltage
  at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.

Well, (very) simply you could slowly increase/decrease the PWM value driving M2 until the voltage at A1 equals that of A2. If you make the time between adjustments long enough you should not get any (significant) oscillations.

However, more likely you want to get to the correct M2 PWM value quickly and for that you need a Proportional, integral, Differential (PID) control algorithm. Explaining this in detail is outside the scope of a S.E. answer, but in summary:

You have a value that signifies the current state of the system - which will be the A2 reading.
You also have a value that states where you want to get to - which will be the A1 reading.
You also have a control value - which will be the PWM value of M2

The Proportial part looks at how far away the A2 reading is from the A1 reading.
The  Integral part looks at how quickly we (the A2 reading) are moving towards (or away from) the desired value (the A1 reading). The Differential part looks at how long we have been away from the desired value.

Each of these (PID) parts (with tuning values that you set) contributes towards determining a new value for PWM at M2 and this iterates around with new values getting the current state closer and closer to the desired value.

There are lots of Arduino PID examples around. I'd suggest you read up on the algorithm itself and have a look at the Arduino.cc samples here.


Programming Arduino via ICSP I'm trying to programming Arduino Nano with another Arduino Nano via ICSP. I have a 6-pin cable directly connected to the ICSP's pin of the second board:

ICSP NANO ISP 1
pin1 pin2 pin3
pin4 pin5 pin6

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

I have correspondingly wired pin 1 (ICSP) of nano1 to pin 1 (ICSP) Nano 2, pin 2 (ICSP) of nano 1 to pin 2 (ICSP) Nano 2, etc.

I make this step before flashing: getting the Arduino ISP with example sketch ArduinoISP, plug off the Arduino ISP and attach the 6-pin cable to the ICSP port of the second board, plug Arduino ISP to the USB port, in the Tools menu select Arduino as ISP, load with external programmer, and fail...

This is the log:

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

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

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

avrdude done.  Thank you.

I suggest you to try and read the Arduino page about ArduinoISP.

Particularly, you will notice that pins 11, 12, 13 and Vcc and GND are all common, BUT the reset pin is not common to both boards. So I suggest you to detach the pin 5 of ICSP from the ArduinoISP board and connect it to its pin 10. Or, if you prefer, connect

ISP - Target
+5V - +5V
GND - GND
11  - 11
12  - 12
13  - 13
10  - RST

Then try again


WS2812 (?) RGB LED matrix turns on white I have an RGB LED 8x8 matrix which is claimed to consist of WS2812. When turning it on, it automatically lights up all LEDs white with full brightness. The LEDs even light up without DIN being connected. I remember reading something about this behaviour and I think it was related to the LEDs being SK6812 or similar rather than WS2812, but I can't find this page anymore, nor anything else describing this behaviour.

My question is, how can I disable the LEDs lighting up when turning power on? Of course I could add some kind of relay to switch them on right before the signal is sent by the Arduino, but is there something simpler?

Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

simulate this circuit – Schematic created using CircuitLab


Bluetooth module vs wireless module Arduino My main question is, what is the main difference between HC-05 Bluetooth module and NRF24L0 wireless module?
Which should I buy?
Which makes these 2 modules different than each other?
Which one should I use in remote control arduino projects?
Which one is made for what purpose?

what is the main difference between HC-05 Bluetooth module and NRF24L0 wireless module?

The main difference is the protocol they use. While some attempts have been made with varying success to get the nRF24L01+ to emulate Bluetooth it is not designed for that. You can only really get rudimentary beacon mode working and that only partially.
nRF24L01+ modules can only communicate with other nRF24L01+ modules. They use their own proprietary protocol that is incompatible with any other system. That's not to say they're bad - they're great modules, and the same RF core and protocol is used in many many other devices by Nordic that are used all over the place - the most notable of which is wireless keyboards and mice.
The HC-05 though is a Bluetooth module which is designed to talk to anything else that also talks Bluetooth - such as your phone or computer. It presents an "SSP" profile and gives "master" mode operation to emulate a serial port connection between your Arduino and any other device that knows about Bluetooth and SSP.
The biggest difference in how they work though is when it comes to connecting devices together. Bluetooth devices have to be "paired" before they will communicate. nRF24L01+ devices don't. This means that getting Bluetooth devices to talk to each other takes a certain amount of time and effort, but nRF24L01+ devices are ready to go the moment they are powered on. It's then just down to your software to set up addresses and such to target the communication.
For Arduino-to-Arduino communication the nRF24L01+ is far less trouble as you set everything simply in your code. There are "LNA+PA" variant boards available that include an amplifier and antenna for longer range communication (I have had 300m+ out of those quite happily).
If you want to communicate with anything else, like your phone or computer, then you will want Bluetooth. Otherwise you will have to add an nRF24L01+ to your computer or phone through USB and (probably) another Arduino, which just gets messy.


127v/220v AC sensor - What's the role of this particular resistor? After searching for a very long time for a 127v/220v (AC) sensor without using any kind of transformers, I found this very nice idea (image below):

I'd like to understand how this module works because I'll have to replicate it in my project without actually using it. I can already tell what's the role of every component, except for both resistors. The first resistor (10k) is placed between the capacitor's legs and, therefore, I'm assuming it's just a bleeding resistor. Am I right? The second resistor (220k), between the AC source and the optocoupler, I have no clue. I was also thinking whether I can improve this sensor by adding a rectifier bridge between the AC source and the optocoupler, allowing me to use a smaller capacitor to normalize the signal. Does that make sense? Thanks!

The first resistor is working with the capacitor as an RC filter. Since you are sensing AC at 50~60Hz, you need this RC filter to get a constant output instead of a pulsed output. Remember your otpo-coupler has a LED (diode) inside, so it will only produce light when voltage is positive.

The second resistor is there to limit the current from your AC 220Vrms (which is 311V peak) so that is within the opto-coupler's LED forward current range. The voltage between your LED´s pins will always be it´s forward voltage (1.2V to 1.4V), so the resistor will bring down the 311V to 1.2 to 1.4V. Without this resistor, you would have 311V between the LED pins, and this would fry the poor thing.

The equivalent input circuit is something like this:

simulate this circuit – Schematic created using CircuitLab

Ok so how did they figure out the 220kOhms value?
First, take the worst case scenario: 220Vrms AC gives us 311Vpeak, and LED forward voltage is 1.2V.
So the voltage between the 311V and the diode is 311 - 1.2V = 309,8V

OHM Law: R = V/I        (R=resistance, V=voltage, I=current)

In this case, the current chosen for the LED was about 1.4mA or 0.0014A, so R = 309.8V/0.0014A

R = 221k Ohms. The closest we get to this is 220kOhms

With 127Vrms (179.6Vpeak), your LED current will be:
I = 178.4V/220000 = 811uA

I have simplified the calculations, because this is a simple case, but keep in mind that real life engineering calculations will be more complex than this.


32u4 timer 4 pwm frequency help I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.

I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)

void setup() {
    pinMode(6, OUTPUT);
    TCCR4E |= (1<<ENHC4); // enhanced pwm mode
    TCCR4B &= ~(1<<CS41); TCCR4B |= (1<<CS42)|(1<<CS40); // prescaler to 16
    TCCR4D |= (1<<WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode & top to 1023 but with enhanced pwm mode we have 2047

    TCCR4C |= (1<<COM4D1)|(1<<PWM4D); // connect pin 6 to timer 4 channel D

}

void loop() {
    //write out
    int value = 1500;
    TC4H = value>>8;
    OCR4D = (value&0xFF);
}

here is the new code so far working off the solution provided below:

void setup() {
    pinMode(6, OUTPUT);
    TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
    TCCR4B |= _BV(CS43) | _BV(CS41);
    TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
    TC4H = 624 >> 8; // B10 0x2
    OCR4C = 624 & 0xff;//B1110000 0x70
    TCCR4C |= (1<<COM4D1)|(1<<PWM4D);
}
void loop() {
    //write out
    //30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
    int value = 30;
    TC4H = value >> 8;
    OCR4D = value & 0xff;
}

the wave form i want:

Yeah... sometimes it's easier to scrap what's already there and start fresh.

We need to:

Pick a suitable prescaler to get close to the desired cycle length
Fine-tune the value in TOP in order to get an exact value

Assuming this is a 16MHz Leonardo, and we have Fast 10-bit PWM (PWM4x = 1, WGM4x = 0b00) available:

16MHz / 50Hz / (1 << 10) = 312.5

Therefore we need a prescaler of 512 (CS4x = 0b1010).

16MHz / 50Hz / 512 = 625

Therefore we need a TOP of 624 (OCR4C = 624).

TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 >> 8;
OCR4C = 624 & 0xff;

And then you set COM4xn and PWM4x to appropriate values for whichever pin(s) you want to output PWM on, and set OCR4x to a value between 0 and 624 (using TC4H appropriately; see the datasheet for details) to control the duty cycle.


2d 3*3 LED matrix code error I have  written a trivial code in Arduino IDE but while verifying its returning a error displaying "i was not declared in scope 12'

  int pinMatrix[i][j]= {{2,3,4},{5,6,7},{7,8,9}};
void setup() {
for (i=0;i<3;i++){
  for(j=0;j<3;j++){
    pinMode(pinMatrix[i][j],OUTPUT);
  }
}

}

void loop() {
for(i=0;i<3;i++){
  for(j=0;j<3;j++){
      digitalWrite(pinMatrix[i][j],HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j],LOW);
  }

  }

}

Variable i & j are not declared. They should be declared as 3. Try this:

const int x = 3;
const int y = 3;

int pinMatrix[x][y] = {{2, 3, 4}, {5, 6, 7}, {7, 8, 9}};

void setup() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      pinMode(pinMatrix[i][j], OUTPUT);
    }
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      digitalWrite(pinMatrix[i][j], HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j], LOW);
    }
  }
}


Building an EEZYBOTARM MK1 My bot arm building is complete, I'm using it with Arduino and 2 joysticks with 4 servos ( mg90s), running with the 9v battery, but still, the servos could not lift the bot arm once it is going down and the servo keeps fluctuating. It is a 3d printed bot so it is not so heavy. please help?

Even if your device is not so heavy, a 9V battery has a maximum practical current draw in the 10s of milliamps. It's not a good choice for operating motors.

A better choice would be AA, C, D, or Lithium-Ion/Lithium-Polymer batteries, wired in series to produce the desired voltage.


Flashing an ATtiny85 with a NodeMCU? I recently purchased a Digispark for some of my smaller electronics projects. After it initially being a great little board, I soon found myself unable to flash the board in the same way I had done before i.e. according to the method described here. I am still unsure as to why the previous flashing method stopped working but have been unable to overcome the issue, nor have I found many other accounts of similar problems online.

After a period of frustration, unable to even find a way to reset the board, it dawned upon me that I may be able to use an Arduino to flash the board as seen here. However, the issue is that all the tutorials I could find online assumed that an Arduino Uno could be easily accessed, which is not the case for me. Despite this, I do have a few NodeMCUs hanging around and would love it if I could use them to flash the Digispark.

My question is: how exactly would I flash the Digispark using a NodeMCU (if it is even possible)?

P.S. Whilst I am aware that the Digispark board has a number of other components aside from the ATtiny85 chip, the pinouts (not the USB) of the board allow for direct interfacing with the chip.

Thank you in advance for any help,

Kind regards,
Rocco

It can be done. Your Digispark has SPI pins, which are ISP pins. For the esp8266 there is an ESP8266AVRISP library for OTA upload to AVR. You can use the example of the library.

You must wire the SPI pins and ground together. Wire reset pin of Digispark to io 5 (D1) of NodeMcu. You should use level conversion, but esp8266 tolerates 5 V TTL (not recommended for long term). Do not wire the SS pin.


Arduino Due randomly slows down, serial communications stops I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.

I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.

I'm using Arduino-MemoryFree to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the ArduinoJson library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).

Could someone please advise me on what could be causing this slow down?

The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.

Here is the typical manifestation of heap fragmentation in an Arduino sketch.

Solution:

Remove as many Strings as possible and replace them with char[]
Use a StaticJsonBuffer instead of a DynamicJsonBuffer

If you remove all the Strings and use a StaticJsonBuffer, your program will run without any heap. No heap, no fragmentation! Not only it will be more reliable, it will also be smaller and faster.

If you must use String, then call String::reserve() to make sure the size is the same at each iteration. Indeed, repeated allocation of the same size doesn't increase fragmentation.


Interfacing TRRS headphone to Arduino Uno I have been working in a Arduino project lately which requires human voice input to Arduino with some processing Arduino need to perform specific task. Simple sampling of incoming signal and calculating average amplitude from it nothing complex.

My problem is I have tried using electret microphone to receive human voice input but failed since the Elec Mic is not sensitive to detect the voice even though i hooked up with LM386 amplifier circuit. So that option is out of the picture. Then i intend to use Android mobile headphones (TRRS) to receive the human voice which will provide great sensitivity for our voice.

Starting through simple internet searches i bought a product 3.5mm breakout module from Ebay. But am unsure of how to connect them to Arduino. Different sources in internet giving different information i couldn't figure out how to connect the headphone to arduino and read it's Mic output from headphone.

Seeing the pin out of TRRS headphones

i can't understand how could i possibly power my headphones with only GND pin available. I tried several wiring connections given in the internet to read the Mic output of my headphones through Analog pin A0 of Arduino but no luck so far. So my question is

1) How do i power the TRRS headphone using Arduino?

2) How can i read the MIC output of my headphone using Arduino? Is it even possible?
3) I have read somewhere the audio out from headphones will be of FSK modulated is it true?

Any help will be much appreciated. Please do provide if you have any links that might answer my questions.

Thanks in advance.

TRRS relates to the style of the jack plug used: Tip Ring Ring Sleeve. You still need to amplify the signal with a microphone preamp the same as your electret (in fact it will be an electret in there anyway).

And then the Arduino cannot process human speech. You may be able to use a voice recognition module to get it to respond to specific commands, but the Arduino by itself has no hope of even thinking about it.


How do you control the amount of times the void loop loops per second? int firstAnalogPin = 0;
int secondAnalogPin = 5;
int firstVal = 0;
int secondVal = 0;
void setup(){

  Serial.begin(9600);          //  setup serial

}

void loop(){

firstVal = analogRead(firstAnalogPin);
   // read the input pin

secondVal = analogRead(secondAnalogPin);
   // read the input pin

Serial.print(firstVal);

Serial.print("\t");

Serial.println(secondVal);

}

Basically, I want to know how to convert from the baud rate to the number of times loop() runs per second. How do I control the number of loop()s per second?

The number of times loop() runs every second depends on the time taken for the execution of the instructions within loop(). For instance, in your code, the time taken for one loop() is roughly equal to the time taken for the MCU to execute all the statements in loop() (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the Serial.print()s + the time taken for the analogRead()s (not considering any interrupts between statements).

That said, you generally don't want to control the interval between loop()s; I assume you actually want to control the interval between the execution of certain operations within your loop(). Say, you want to set the time between executions of analogRead(0) to 500 ms. This can be done like this:

#define INTERVAL 500   // time between reads
unsigned long lastRead = 0;

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

void loop(){
  //....your other code....

  if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
    val = analogRead(0);
    lastRead = millis();
    Serial.println(val);
    //...anything else
  }

  //...your other code...
}

With this code, you now have about 2 analogRead samples every second. Of course, this is only useful if loop() runs faster than your chosen interval. If there are function calls, or any operations otherwise, in loop() (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.


How to connect arduino with local network I am trying to connect Arduino with local network. This will act as a web server, client would be android mobile app or web browser. These are on same local network.

Do I need Ethernet Shield or ESP8266 to make Arduino accessible with local network IP ? Is there any way to connect without Ethernet Shield ?

To connect to a network you need a network interface.  This could be an Ethernet interface, a Wifi interface or something that supports TCP/IP.  The easiest way of doing this is with ether an Ethernet 'shield' of a WIFI 'shield'.

In either case there are a range of options, from full shields to smaller boards that connect via jumper wires.  One important consideration is the longer the wires the more chance for signal degradation and loss of comms.  So direct plug in boards are probably better.

Probably the easiest way to do it is to use a ESP8266-??, but using an ESP as a network interface is like only using your PC for email.  The ESP is faster and has more memory than the Arduino, so it would be better to program that as the web-server and get the Arduino to feed it the data.

You could use Bluetooth, radio, etc, but that's just making life hard for yourself.

You could also look at the Arduinos that have networking built in.


store multiple of float type on EEPROM I have 7 float variables.

float temperature, differential, calibration,hta,lta,hha,lha;

I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.

Thanks!

create a struct and store the struct

#include <EEPROM.h>

const int DATA_ADDR = 0;

struct MyData {
  float temperature, differential, calibration,hta,lta,hha,lha;
};

MyData data;

void setup() {
  data.temperature = 1.2;

  EEPROM.put(DATA_ADDR, data);

  EEPROM.get(DATA_ADDR, data);
}

void loop() {

}


Wire.endTransmission() hangs, but only, if wire.begin(); is called with an address (MKR WiFi 1010) This code runs without issues, scoped and seen from serial output:

#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin();
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

This one hangs on Wire.endtransmission():

#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin(10);
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

The problem starts as soon as I assign an address in Wire.begin(). As I understand, a slave is also allowed to send data and temporarily becoming a master when addressing another device.

I want to push data from the slaves to the master immediately when they receive said data.

So that means, that each slaves becomes master directly after it has received data from the MKR. This is still a multi-master setup, even while you are avoiding collisions through a fixed protocol. The Wire library does not support multi-master.

But I also don't understand, why you would need this. Your protocol does this: The MKR sends data to a slave (triggering it and maybe also sending some commands). Then the slave should send data back to the master. Then the transmission ends. This is normally done in I2C with just one master. The master does a master write (via Wire.endTransmission() and sends some command data to the slave. The slave will prepare the data, that the master requested, in it's buffer. Then the master will start a master read (via Wire.requestFrom()) which reads the data from the slave.

So you don't need a multi-master setup for this. It does exactly, what you described, but with only one master.


MAX7219 with Arduino UNO - LED control doesn't work I'm very new to Arduino and this is my first project, so I may misunderstand something simple.

As a hardware I'm using 4 MAX7219 connected to Arduino UNO and a single diod for tests.

As a software I have Waoyda's LedControl 1.06 for MAX72XX.

It seems, I'm completely missing something, because with the code below, the diod is never lit, regardless on matrix position it is connected to.

#include "LedControl.h"

LedControl lc=LedControl(12,11,10,4);

void setup() {
  int devices=lc.getDeviceCount();
  for(int address=0;address<devices;address++) {
    lc.shutdown(address,false);
    lc.setIntensity(address,8)
    lc.clearDisplay(address);
  }
}

void loop() {
  int devices=lc.getDeviceCount();

  for(int row=0;row<8;row++) {
    for(int col=0;col<8;col++) {
      for(int address=0;address<devices;address++) {
        lc.setLed(address,row,col,true);
      }
    }
  }
}

Some high res photos: 1, 2, 3

UPD: scheme added.

OMG, the only problem was a typo in LedController initialisation! I used LedControl lc=LedControl(12,11,10,4); instead for LedControl lc=LedControl(11,12,10,4);. It seems the library has no error detection if passed data pin isn't really a data pin. Now everything works fine.


Sparkfun CCS811 sensor not interfacing with arduino I have sparkfun indoor air quality sensor CCS811 which needs to be interfaced with arduino. I have soldered wires on the sensors and connected with arduino. Have checked the connection with multimeter so that part works. But even using example code on library still I am not getting reading from sensor.

Code:-

#include <Wire.h>

#include "SparkFunCCS811.h"

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  Serial.begin(9600);
  Serial.println("CCS811 Basic Example");

  Wire.begin(); //Inialize I2C Harware

  //It is recommended to check return status on .begin(), but it is not
  //required.
  CCS811Core::status returnCode = mySensor.begin();
  if (returnCode != CCS811Core::SENSOR_SUCCESS)
  {
    Serial.println(".begin() returned with an error.");
    //while (1); //Hang if there was a problem.
  }
}

void loop()
{
  //Check to see if data is ready with .dataAvailable()
  if (mySensor.dataAvailable())
  {
    //If so, have the sensor read and calculate the results.
    //Get them later
    mySensor.readAlgorithmResults();

    Serial.print("CO2[");
    //Returns calculated CO2 reading
    Serial.print(mySensor.getCO2());
    Serial.print("] tVOC[");
    //Returns calculated TVOC reading
    Serial.print(mySensor.getTVOC());
    Serial.print("] millis[");
    //Simply the time since program start
    Serial.print(millis());
    Serial.print("]");
    Serial.println();
  }

  delay(10); //Don't spam the I2C bus
}

Things I tried:-
1) different combination of  A4, A5 pins
2) 0x5A & 0x5B i2c address
3) using wake pin with ground
4) using 3.3 & 5V for powering sensor

What else needs to be done?

The problem was on the soldering part. SDA & 3.3V pin on sensor were slightly in contact. I modified it and started working fine.


connection between Arduino Uno with nRF24L01 and notebook with wireless card My project intend to command an Arduino UNO by my notebook without cable. I thought to use a RF Nordic nRF24L01 cabled on an Arduino UNO, and to use the wireless card of my notebook to send command to it. Is it possible? Any solution?
Is this hardware solution possible?

I need to send to Arduino four analog signals to setup the light of four led.

Absolutely no. Can you connect your bluetooth headset to the wireless router? No because even if they share the same band they "speak" different protocols. So why could you do that with the nRF24L01?

If you want to communicate with your PC you have three options:

Choose nRF24L01. In this case, since the PC does not have that device, you will need to make an adapter (the easiest one could be an USB adapter). You can connect a microcontroller to a USB to serial converter and to the nRF24L01 and use it as a bridge.
Choose Wifi. Then you'll need a new transceiver for the arduino UNO you are using (maybe the ESP8266, which is around 2$) but can be a bit more complicated for just sharing data (I never used it, though, so I can be wrong).
Choose bluetooth. Usually this is my preferred way to communicate with a board. Cheap (the HC-06 module is about 2-3 $) and easy to use (the interface is a plain serial).

Good luck ;)


Is it possible for a HC-05 Bluetooth module to have multiple slaves For a project I am interested in using the HC-05 Bluetooth module to control five LEGO Mindstorms Bricks simultaneously. For this to work the Bluetooth module will obviously have to be paired / connected with the five bricks at the same time. This means that the HC-05 Bluetooth module will have to be master in the piconet and the five bricks the slaves.

Is there anyone who has any experience with using the Arduino Uno and HC-05 Bluetooth module to send data to multiple, connected, slaves? If not, are there any alternative Bluetooth modules? And if Bluetooth modules compatible with the Arduino Uno cannot connect to multiple slaves at the same time, are there other ways that an Arduino can control multiple Bluetooth slaves at the same time?

After some research, it looks like multiple slaves aren't possible with this particular module.

According to Wikipedia the Bluetooth technology allows a master to communicate with 7 slaves, but this option isn't implemented in the HC-05.


Is it possible to digitally stop a moving motorbike using an Arduino module? I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.

Is it possible to do it using an Arduino and some other modules maybe?

Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.

Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.

Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.


Store RAM and PROGMEM strings in one variable I want to store a number of strings in an object. Currently I have:

class MyClass {
  int numStrings = 0;
  ??? strings[20];

  public:
    void addString(const char str[]);
    void print();
};

void MyClass::addString(const char str[]) {
  strings[numStrings] = str;
  numStrings++;
}

void MyClass::print() {
  for (int i = 0 ; i < numStrings ; i++) {
    Serial.println(strings[i]);
  }
}

Serial.println() works with strings in RAM and in PROGMEM alike.

Is there a type that I can give to my strings variable that allows me to store both types of strings?

MyClass s;

s.addString("This should work");
s.addString(F("This should work, too"));

Is there a type that I can give to my strings variable that allows me to store both types of strings?

No, but you could tag the pointer or add a vector with type information or ultimately use a class hierarchy (BaseString<-SRAMString, PROMEMString).

As a pointer is 16-bit (Arduino Uno) and there is limited amount of SRAM it is possible to add a magic number to pointers to determine the address space.

Obviously the print() member function will have to use the right type and you will also need a new addString for F() strings. Check how F() is defined.

Cheers!


square wave with serial plotter I have this code which produces a square wave:

int output_state = 0;
unsigned long start;

void setup() {
  Serial.begin(1200);
  start = millis();
}

void loop() {

  if((millis() - start) >=1000){
    output_state = ! output_state;
    //output_state *= 1023;
    start = millis();
  }

    Serial.println(output_state);
}

but should I multiply the signal by 1023:

output_state *= 1023;

this signal is produced by the Serial Plotter:

Mind that the timing is right, just the x axis speeds up in zero values. Why is that happening, and how can be solved?

Any thoughts would be appreciated.

It takes twice as long to print "1023" (6 bytes, including the CRLF line
terminator) than to print "0" (3 bytes). Thus, in the same time, you are
printing twice as many "0" than "1023".

If you want the data points to be printed at a consistent rate,
you can impose the printing timing just like you did on the
output_state. Keep in mind that you cannot print more than 20 samples
per second at 1200 bps. You could also pad the strings so that they
always have the same length:

char s[5];  // one byte for the NULL terminator
sprintf(s, "%4d", output_state);
Serial.println(s);

I would prefer the first solution (explicitly control the timing).


Arduino servo seems to time out after code runs for some amount of time I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?

Here is my code:

#include <Servo.h>

int servoPin = 9;
Servo servo;

int servoAngle = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    servo.attach(servoPin);
}

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

    int randnum = rand()%(40000-1000 + 1) + 1000;
    int randnumreturn = rand()%(600-350 + 1) + 350;
    servo.write(45);
    delay(randnum);
    servo.write(22);
    delay(randnumreturn);
}

int in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is > 32767, you would get a minus value, which may cause delay not to work properly.

In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.

Edit: I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.


how to know the channel i receive information from when i use nRF24L01 to connect between 3 of them i am using nRF24L01 to connect between 3 of them ( 1 is master and the others are slaves) and i am using nRF24 library , my problem is that when the master receive something from the other slaves and do not know from which channel the infromation come so is there is a way to know from which channel

//master channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[1]); // mastr
  radio.openReadingPipe(2, addresses[0]); // carwl
  radio.openReadingPipe(2, addresses[2]); // carwl2

//slave 1 channel code :
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // carw1
  radio.openReadingPipe(2, addresses[1]); // mastr

//slave 2 channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // 00003
  radio.openReadingPipe(2, addresses[2]); // 00002

library i use: https://github.com/nRF24/RF24

The nRF24 is highly versatile and can be programmed for a number of different network topologies.  It appears you want either

One-to-many network - where the master node sends data to the slave nodes
Many-to-one network - where the master receives data from many slaves.

Both networks are achieved with the same radio channel (RF_CH) on all nodes.

For a one-to-many network you need to have a different RX address for each slave node.  Set the master TX address to the RX address of the corresponding slave  that you want to receive the data.  Done.

For a many-to-one network you are limited to 6 slave nodes.  On the master radio you will need to set the addresses of data pipes 0-5 to the slave TX addresses.  The master will be listening for data on all pipes and signal an interrupt whenever data is received on any of them.

To achieve bi-directional communication with a (practically) unlimited number of slave nodes, your best bet is to use the in-built ACK PAYLOAD feature of nRF24.  In addition to configuring a one-to-many network, you need to enable ACK payload on each radio node.  The procedure to follow is given in the nRF24L01 data sheet.  I can't recommend strongly enough how important that is to read and learn from.  You will be able to send a message from the master to one slave, and get data back from that node in the same radio transmission, auto-retransmit etc included in the bargain.  This way you also know which node the data are coming from - without needed to encode the identity of the slave node in the message.  It's incredible what these little radios will let you achieve!


Arduino Modbus Slave Library Needed We are building a circuit based on ATMega328* that :

Reads 32 current transducers, multiplexed into one Analog Input,
Reads 12 voltage transducers, multiplexed into one Analog Input,
Reads 6 temperature sensors, multiplexed into one Analog Input,
Manipulates all the readings with some math (like scaling, averaging etc.),
Calculates new variables (power, crest factor, etc.),
Tracks trends (max/min/avg) of certain (calculated) readings,
Stores some events (peaks/dips - max/min values) etc. with time stamps from RTC,
Generates Alarm Flags (by comparing readings to software-set thresholds),

The circuit should be connected as a ModBus Device (Slave) to an existing
Modbus network with several other devices on an RS485 interface.
The circuit should communicate all these calculated values and alarms
as well as some other info, like peak/max values with date and
time stamps that were recorded at their time of occurrence, to the
Modbus Master. We have the freedom of allocating the register numbers
and their formats etc. (Modbus Map) to the controller's vendor (SAUTER).
For example we tell them Register 30001 is the current sensor x,
30002 is voltage sensor y, etc.
We think that sending time stamps (of certain events) will be based on
"agreed-upon" coding of register values (MM, DD, YYYY, etc.) and the
same for alarms (to be sent as hex codes).
We have searched for libraries and got really confused from the
multitude of libraries out there, as well as the lack of documentation -:)
Can you please kindly help us :
select the proper Arduino Modbus Slave Library that :

Has MAX485 support,
Assigns Modbus registers to any arbitrary variables,
Issues Exception Responses to Modbus requests (e.g. non-existing registers
or un-supported Function Codes.
Complies to Modbus Standards
Has a manual !!

We found the "yaacov" library on Github but it assigns registers directly to "Pins".
Also we looked at its "issues" and one of them was very serious : in which frames
coming from the Master with corrupted CRC gets responded to and causes collision
with other slaves. We dont like that ! as it indicates that the library was not tested
in true industrial environment.
We also found that the Library at :
https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/
somewhat fits to our requirements, however it lacks the RS485 support, and more
important, it has no documentation.
We really appreciate any kind support.

The ATmega328 will be probably replaced with a larger CPU, but we are still
in development phase.

Thank you.

With my post approaching one month without a single reply  :smiley-confuse: !
(for whichever reason) I would like to post for those who may need this library :

https://drive.google.com/file/d/0Bx5wWRfN_z7oMDlZMDhWbXM2VFU/view
The library is based on the original one written by Jason Vreeland [CodeRage]
Released 3/7/2010 under GNU license
and was used (and possibly modified) by "jhottell" on electronhacks.com :
https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/
The major difference is the use of RS485.
I have written code and tested it on an "UNO" which worked perfectly with more
than one ModBus Slave Simulator under windows, including DAQ Factory which
is a professional package used in actual industry.


How do i get stored Midi to Play back without the notes sounding sustained? How can i get my stored midi notes to play back without sounding sustained like in this video : https://youtu.be/zc1zbwheyE0?t=2m30s. Here is some of my code:

// Callback function to for recording note played is called upon reception of a NoteOn.
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

if ((currentState != STATE_R) || (noteIndex >= MAX_NOTE))
      return;

  // Record the note
  noteList[noteIndex].channel = channel;
  noteList[noteIndex].pitch = pitch;
  noteList[noteIndex].velocity = velocity;
  noteList[noteIndex].deltaT = millis() - lastNoteTime;

  lastNoteTime = millis();
  noteIndex++;

 }

 void StateMachine(void)
{
  static uint16_t  nextNote;

MIDI.read();   // keep this going as fast as possible and empty buffer all the time

  switch (currentState)
  {
    case STATE_I2P:    // Set up for playback

      nextNote = 0;
      lastNoteTime = millis();
      SwitchState(STATE_P);
      break;

    case STATE_P:      // Play the notes back
   lcd.clear();
 lcd.setCursor(5,0);
  lcd.print("Playing Recorded Song");
  if (nextNote >= noteIndex) SwitchState(STATE_P2I);  // we are done

       if ((millis() - lastNoteTime) >= noteList[nextNote].deltaT)
       {
         MIDI.sendNoteOn(noteList[nextNote].pitch, noteList[nextNote].velocity, 1); //noteList[nextNote].channel);  // Send the note
        noteOn(0x90,noteList[nextNote].pitch,100);
         nextNote++;
         lastNoteTime = millis();
       }
      break;
   }

You need to store and send out the 'note off' messages in addition to the 'note on' messages.


How do you convert a formatted print statement into a string variable? I'm using the following routine to print the current time on the com port. I would like to capture this as a string so I can display it using ePaper.

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

produces - Saturday, May 12 2018 12:18:27

To achieve what you want you probably want to use the "string format time" function strftime (docs). You would write the result in a character buffer, which you can also print directly without having to convert it to String object.

So, the following code should work:

void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
  char timeStringBuff[50]; //50 chars should be enough
  strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
  //print like "const char*"
  Serial.println(timeStringBuff);

  //Optional: Construct String object
  String asString(timeStringBuff);
}

The overload for Serial.print also does this exact same thing:

size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}


What's taking up so much RAM in an almost empty sketch? I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:

int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:

#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

I've changed SERIAL_BUFFER_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:

struct ring_buffer
{
  unsigned char buffer[SERIAL_BUFFER_SIZE];
  volatile unsigned int head;
  volatile unsigned int tail;
};

ring_buffer rx_buffer = { { 0 }, 0, 0};
ring_buffer tx_buffer = { { 0 }, 0, 0};

So when the SERIAL_BUFFER_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= 73 bytes)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.

First off, a sketch that uses Serial cannot really be considered an empty sketch as Serial drags along a lot of function definitions, at least one Serial class instance (more on Arduino Mega, for instance), plus probably some more global variables...

sizeof Serial may be interesting to display as Serial is not limited to the TX and RX buffers, as you seem to believe. Its class also has a couple of additional data members on its own, plus members inherited from its superclasses, Stream and Print.

In addition, the Arduino IDE comes with the various "utilities" which you normally can't get rid of, like the millisecond timer that uses at least 9 bytes (see reference in wiring.c file).

So in the end, even an empty sketch (even without Serial) takes some SRAM space for global variables.

I think there is some way, with avr-size, to check out, with fine details, the size of data (not accounting for the runtime stack) after the sketch has been fully built.

Arduino IDE already displays some of this static memory information (at the end of "verification").

For example, on my IDE (1.5.8) for Arduino UNO, a really empty sketch, once compiled is mentioned to use 9 bytes of SRAM. Actually those 9 bytes are for 3 global variables, used by the millisecond timer. This number, of course, does not account for runtime memory usage, in particular the stack.

Then, just adding Serial.begin(9600); makes it use 182 bytes (ie 173 more bytes than an empty sketch). So you get the culprit.


Is possible use Macro F() with Integer and Other types of variable? i have a sketch that is using very memory RAM of my Atmega2560 (is a giant project), and i need use various "println" because i have a TFT screen and i need to show data on the screen to user see. So, i'm using macro F() to use less RAM memory (example: Serial.println("Hi Naruto-kun") to Serial.println(F("Hi Naruto-kun")). But, it only work if the data entered in F() were to Const String, when i need, by example, show a array of integers, nothing work.

Example:

tft.print(F(mediaTotPg[1]));

This do not work because mediaTotPg is a Integer Array and the errors returned are:

" #define F(string_literal) (reinterpret_cast(PSTR(string_literal))) "

Finally, is possible show integers not const with Macro F()?

For a constant array of integers you need to use PROGMEM and the various pgm_read_*() functions.

You can read more, and find examples, on the Arduino PROGMEM manual page.


Receive data using ESP8266 I have connected ESP8266 to my Raspberry Pi's WiFi network and assigned a static IP.

My Arduino code

#include "SoftwareSerial.h"

String ssid = "Rpi";
String password = "raspberry";

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

String server = "192.168.50.1"; //my Host

void setup() {
  esp.begin(115200);
  Serial.begin(115200);
  connectWifi();
  httpget();
  delay(1000);
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  if (esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    Serial.println("Cannot connect to wifi ! Connecting again...");
  }
  connectWifi();
}

/////////////////////////////GET METHOD///////////////////////////////
void httpget() {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",1234");//start a TCP connection.
  if ( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  /*
    String getRequest =
    "GET " + uri + " HTTP/1.0\r\n" +
    "Host: " + server + "\r\n" +
    "Accept: *" + "/" + "*\r\n" +
    "Content-Type: application/json\r\n" +
    "\r\n";
  */
  String sendCmd = "AT+CIPSEND=";
  esp.print(sendCmd);
  //esp.println(getRequest.length() );
  delay(500);
  if (esp.find(">")) {
    Serial.println("Sending..");
    //  esp.print(getRequest);
    if ( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String response = esp.readString();
      }
      esp.println("AT+CIPCLOSE");
    }
  }
}

void loop() {
  httpget();
}

I get this message

    Cannot connect to wifi ! Connecting again...

In my Raspberry Pi I am constantly sending a signal to this IP address.

import socket

TCP_IP = '192.168.50.1' #Local Host
TCP_PORT = 1234            #Listening Port
BUFFER_SIZE = 12

SERVER_IP = '192.168.50.18'  #Arduino IP
SERVER_PORT = 3007            #Server Port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#(conn,addr) = s.accept()
#print 'Connection address: ',addr
while True:
    print 'Sending message'
    s.sendto('1',(SERVER_IP,SERVER_PORT))
    print 'Waiting for response'
    data,addr = s.recvfrom(BUFFER_SIZE)
    if not data: break
    print 'received data: ',data
    print 'data recieved from: ',addr
    conn.close()
s.close()

But I can not see it in my Serial Monitor. Do I need to create a separate program for getting from WiFi?

You are recursively calling connectWifi() and therefore your setup function results in an infinite loop.
You must not implement loops and for processes, which take some time, you should set and ask a flag.
Btw. why don't you use the official ESP WiFi library?


Why is Serial.begin(9600) interfering with my multiplexor functioning? I have an Uno hooked up to a sparkfun 8 channel multiplexer (https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide). I have it wired up like this:

Arduino0 --> S0
Arduino1 --> S1
Arduino2 --> S2
Arduino3 --> Z
Arduino 5v --> VCC
Arduino GND --> GND

I'm running a simple code to blink two different LED's, one attached to Y7, and one attached to Y6.

//Define MUX pins
int pin0 = 0;
int pin1 = 1;
int pin2 = 2;
int zOutPut1 = 3;

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

    // Set controll pins
    pinMode(pin0, OUTPUT);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(zOutPut1, OUTPUT);
}

void loop() {
    samplerStarter();
}

void samplerStarter() {
    sample(1); // Takes sample for 5 min
    delay(1000);
    sample(2);
    delay(1000);
}

void sample(int noidNum){
    //MUX 1
    if(noidNum == 1) {
        digitalWrite(pin0, HIGH);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y7
    }
    else if (noidNum == 2) {
        digitalWrite(pin0, LOW);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y6
    }
    delay(500);

    //Set everythign back to Low
    digitalWrite(pin0, LOW);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(zOutPut1, LOW);

    delay(500);
}

But when I run this code, only the first LED attached to Y7 blinks. But if I remove the Serial.begin(9600) line:

//Serial.begin(9600);

Everything works fine. So I have no idea why this one line dealing with Serial Communication is affecting my multiplexor.

(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.

With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.

Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.


How to pass value of a function from the RFID-RC522 library into a variable then be sent into either serial or ethernet? I'm using an RC522 RFID reader with an Arduino UNO. There is a function?? (or whatever it's called :)) in Miguel Balboa's new MFRC522.h library which is mfrc522.uid.uidByte[i] that prints the bytes of the unique ID. The repetition of the function results in 8 piece of HEX digits that are from the 2 numbers that each function outputs (2+2+2+2=8). Whenever I use the line of codes that are commented out, the serial monitor outputs them successfully. So for example, 12345678 is the unique id, each array displayed 12, then 34, then, 56, then 78 which is 12345678 in the serial. which is fast and unnoticeable besides that there are no spaces included when on output. The thing is, I want to output all of these into a single variable.(Please help me also on how to concatenate) How can I do this? An attempt was done below (not commented out) but it outputs only the number 16, consistently, which is I think due to a data type problem. The variables are initialized as int. The "function" which I found in the library is initialized as byte (correct me If I'm wrong). But when the variables are initialized as byte, I cannot upload the sketch since there are errors. Please help. :( (The reason I need it to be saved into a single variable is because I am placing it in the GET method of an Ethernet Client. I don't think the bare function can do that. (Or if it can, can you please help with the code? :)) Thanks

// Dump UID
        //Serial.print("Card UID:");

            //Serial.print(mfrc522.uid.uidByte[0], HEX);
            //Serial.print(mfrc522.uid.uidByte[1], HEX);
            //Serial.print(mfrc522.uid.uidByte[2], HEX);
            //Serial.print(mfrc522.uid.uidByte[3], HEX);

            serNum0={mfrc522.uid.uidByte[0], HEX};
            serNum1={mfrc522.uid.uidByte[1], HEX};
            serNum2={mfrc522.uid.uidByte[2], HEX};
            serNum3={mfrc522.uid.uidByte[3], HEX};
            Serial.print(serNum0);
            Serial.print(serNum1);
            Serial.print(serNum2);
            Serial.print(serNum3);

As far as I can understand, you expect to receive byte data from the RFID reader, you would like to store this data into a single variable, and eventually print its content, or manipulate it in some way. You could do this maintaining a byte array (or uint8_t array).

Let's suppose, for example, to receive a unique ID of length 4 from the RFID reader. In this case you could simply store it into a serNum[serNum_size] array, where serNum_size is just the number of data you are expecting to receive, and later access its content for whatever manipulation you would like to do.

int serNum_size = 4;        // reader data size
byte serNum[serNum_size];   // reader data content

for(int i = 0; i < serNum_size; i++){
 serNum[i] = mfrc522.uid.uidByte[i]; // store reader data block
 Serial.print(serNum[i], HEX);       // hexadecimal form
}

As far as the print is concerned, you can simply print the byte entry and apply the HEX format. In this way, the stored value will be considered as its hexadecimal value.


Rc car which returns to middle when left or right button is not pressed Hi i am currently working on a school project , my only problem is that i want my RC car to return to middle direction (which i have set to 66 in the servo motor) when the left or right button is not pressed . i used if statements but it doesn't work. Are there any function that i can use ?
Here is my code for the transmitter i used the RC-Switch Library (https://www.arduinolibraries.info/libraries/rc-switch)

#include <RCSwitch.h>
#include <Servo.h>

const int IN1 = 3;
const int IN2 = 4;
const int trigPin = 5;
const int echoPin = 6;
const int Buzzer = 8;
int distance = 0;
int value = 0;
long duration;
RCSwitch mySwitch = RCSwitch();
Servo myservo;

void setup () {
  mySwitch.enableReceive(0);
  myservo.attach(7);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(Buzzer,OUTPUT);
  Serial.begin (9600);    // Debugging only
  Serial.println ("Receiver Ready");
}

void loop () {

  delayMicroseconds(10);
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  //Serial.print("Distance: ");
  //Serial.println(distance); //distance is the returned integer,

 if (mySwitch.available()) {

    value = mySwitch.getReceivedValue();
    Serial.println (value);

      if(value == 1) {
        forward ();
        Serial.println (" = forward");
      }

      if(value == 2){
        backward ();
        Serial.println (" = backward");
      }

      if(value == 3) {
        left ();
        Serial.println (" = left");
      }

      if(value == 4) {
        right ();
        Serial.println (" = right");
      }
      Serial.print(" ");
    }
  mySwitch.resetAvailable();
  //myservo.write(45);
}

void forward () {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

//value = mySwitch.getReceivedValue();
void backward () {

  if ((distance < 50)&& (value == '2'))
  {
    digitalWrite (IN1, LOW);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, HIGH);
  }
  else if ((distance > 50)&& (value == '2'))
  {
    digitalWrite (IN1, HIGH);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, LOW);
  }
}
// 66 is middle

void right () {
  if (value == 4){
    myservo.write(110);
  } else
  myservo.write(66);
}

void left () {
  if (value == 3){
    myservo.write(50);
  }else
 myservo.write(66);
}

And Here is The transmitter code

// TRANSMITTER CODE

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
// Assigning controller buttons to Digital Pins
 int forward = 11;
 int reverse = 10;
 int rightTurn = 9;
 int leftTurn = 8;

void setup () {
  pinMode (forward, INPUT_PULLUP);
  pinMode (reverse, INPUT_PULLUP);
  pinMode (rightTurn, INPUT_PULLUP);
  pinMode (leftTurn, INPUT_PULLUP);
  mySwitch.enableTransmit(7);
  Serial.begin (9600);         // Debugging only
  Serial.println ("Transmitting");
}

void loop () {
  if (digitalRead(forward) == LOW) {
    mySwitch.send(1, 24);
    Serial.println ("Forward");
  }

  if (digitalRead(reverse) == LOW) {
    mySwitch.send(2, 24);
    Serial.println ("Reverse");
  }

  if (digitalRead(leftTurn) == LOW) {
    mySwitch.send(3, 24);
    Serial.println ("Left Turn");
  }

  if (digitalRead(rightTurn) == LOW) {
    mySwitch.send(4, 24);
    Serial.println ("Right Turn");
  }
}

You send values from your transmitter when you press a button but not when you release them. The simplest solution would be sending the state of all buttons in every iteration if the transmitter has enough capacity. (I think it has for just these four values)

Add an enum to make the code more readable:

enum {
    FORWARD_ON = 0,
    FORWARD_OFF, // It will be 1.
    BACKWARD_ON, // It will be 2 and so on...
    BACKWARD_OFF,
    RIGHT_ON,
    RIGHT_OFF,
    LEFT_ON,
    LEFT_OFF
};

So a sending function will be like this:

if (digitalRead(forward) == LOW)
    mySwitch.send(FORWARD_ON, 24);
else
    mySwitch.send(FORWARD_OFF, 24);
// And so on for every button...

Then by reception you should add some state variables and store the received values:

int steer_right = 0;
int steer_left = 0;

// ...

loop() {

// ...

value = mySwitch.getReceivedValue();

switch (value) {
    case RIGHT_ON:
        steer_right = 1;
        break;
    case RIGHT_OFF:
        steer_right = 0;
        break;
    case LEFT_ON:
        steer_left = 1;
        break;
    case LEFT_OFF:
        steer_left = 0;
        break;

    // ... (throttle)

    default:
        break;
}

// ...

}

Then you evaluate what you got:

if (steer_right && !steer_left)
    right();
else if (!steer_right && steer_left)
    left();
else
    straight();

// ... (throttle)


I want to reset a variable after each 1 second on an Arduino I want to reset this counter variable which I created after each 1 second, but I don't want to disturb the if statement.

Here is the code:

int button=A0;
int val;
int count=0;
int presss;

void setup() {
  pinMode(button,INPUT);
  Serial.begin(9600);
}

void loop() {
  val=analogRead(button);
  if(val>1000){
   presss=count++;
   delay(200);
 }
  Serial.println(presss);
  delay(1000);
 }

I would do it the following way:

Use a variable declared as: unsigned long time_passed;
In the setup() section I would add the line time_passed = millis();
In the loop() section I would add the if condition:

if(millis()-time_passed > 1000) {
   time_passed = millis();
   presss = 0;
   }

I think this is still not working properly with your example, I recommend to make two changes in your code:

you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop
I cannot understand how presss = count++; should work. For proper counting I would suggest to do it this way: presss = presss + 1;
Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms


How to Set RTC in ES32 using NTP server? I am working on ESP32 And want to set RTC from the NTP server. How can I get epoch value I have done this thing on CC3200 launchpad and used an NTP server library to obtain epoch value.

this snippet from setup() sets on esp32 the NTP for internal RTC and uses epoch seconds to set time to TimeLib library.
  configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org");
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }
  setTime(now);

The ESP32 examples library in IDE examples folder has example SimpleTime.


convert String to unsigned long long i want to convert string for example
"68976543210" to unsigned long long(64 bit) in mega2560,
 do is possible?

String x="68976543210";
unsigned long long y=?;

avr-libc lacks strtoull() that I would normally use for such a conversion. You will have to do it manually.

Fortunately it's quite simple - just start with y=0 and, for each character in the string, multiply y by 10 then add the numeric value of the character in the string:

String x = "68976543210";
unsigned long long y = 0;

for (int i = 0; i < x.length(); i++) {
    char c = x.charAt(i);
   if (c < '0' || c > '9') break;
   y *= 10;
   y += (c - '0');
}

Note that the Arduino Print API has no method for printing a 64-bit integer.


From Exploring Arduino Text I am working thru the Exploring Arduino text mostly with success up until chapter 4. I have most of the parts required but for Figure 4-3 I used the following:

100nF Capacitor, (In place of 1uF Capacitor)

1N4007 Diode Rectifier, (In place of 1N4004 Diode)

S8050 NPN Transistor, (In place of PN2222 NPN)

DC Motor rated for 3V with a Reference Current of 0.35 to .4 Amps (Text lists "DC Motor")

Im aware that the Capacitor was undersized, Diode was a 4 series (so I assumed it was compatible), and the Transistor also the same but of a different manufacturer. Im also aware that the motor is underrated compared to the 9v input, but I didnt think this would cause a problem for a small time period.

My problem is that after about 10 seconds of running (both with the motor free spinning as intended, and sometimes just staying put but making a high pitched noise) the bread board started smoking. So, I disconnected everything and gave up for the day.

What was it that caused the breadboard to start smoking? Do you think I damaged my Arduino?

Link to companion site with diagrams: http://www.exploringarduino.com/content/ch4/

If you used the 9 V battery as described in the diagram, but with a 3 V rated motor, then the motor starts smoking and you might damage it. Use e.g. 2 AA batteries with 1.5 V instead of the 9 V battery, then it should work without smoke and your motor will survive much longer.