Error in I2C Communication Between Arduino and Raspberry Pi The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between writeData?
Error:
> Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
> <module>
> writeData("360")   File "rpi-I2C.py", line 12, in writeData
> bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

Python code:
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue)
    #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending test")
    writeData("left")
    time.sleep(0.02)

    #print('Sending OPEN-00-00');
    writeData("right")
    time.sleep(0.02)

    #print('Sending WIN-12-200');
    writeData("360")
    time.sleep(0.02)

Arduino code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);
  Serial.begin(115200);
  Serial.println("Ready!");
}

void loop() {
  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0';  //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];
    receiveFlag = true;
  }

A RPI uses 3.3v logic while an arduino uses 5v logic you can use a logic converter but by now it's probly to late and maybe your arduino or RPI is broken (Sorry!)


Does an Arduino 101 come with bluetooth HID capabilities? I would like to prototype an Ergodox-like keyboard. My take on this good design would be to affix each half of the keyboard to my chair's armrests, so that the arms are always in a natural relaxed position. In order to achieve this, bluetooth capabilities seem necessary in order to avoid cable mayhem each time I move the chair.

I am aware that the Arduino Leonardo has USB-HID capabilities, but will that translate to the additional USB module that would be required? I saw that Adafruit has an EZ-key bluetooth module that seems to fit the bill, but even so, it would require more cabling and complexity, for a project that is already very near my threshold (or above it).

What would be easy is if the Arduino 101 had HID capabilities. I would just need to solder the matrix of keys, and almost be done. Does it?

Thanks for your attention.

The Arduino 101 has HID capabilities. I found example code for using the Arduino 101 as a keyboard, as well as some other discussions saying that the Arduino 101 has HID capabilities.

Here is some example code on GitHub.


Why is my pushbutton always reading LOW? I know this is ridiculously simple task but I spent the last two hours trying to get this to work and it is not working.  I don't have an Arduino but I have an ESP8266 Huzzah Feather which is programmable via the Arduino IDE.  So, I don't think I can provide a Fritz diagram but in any case, I'm just trying to hook up a pushbutton and be able to read a HIGH or LOW (via my Serial monitor).  Currently, everything is 0.

As best I can describe it is:

5V from Feather into resistor into one terminal of the pushbutton.  Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.  Feather is also grounded.

My code is:

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

void loop()
{
  int button_val = digitalRead(12);
  Serial.println(button_val);
}

It shouldn't be this hard for me.  Whenever I open and run the serial monitor, it reads 0s.  What am I missing?

Oh, an issue that I faced is determining which 2 out of the 4 terminals of the pushbutton to use.  Some resources I find say that it is the same side as the terminal the voltage is flowing into; other resources say it is the terminal opposite to the side the voltage is flowing into.  I currently have it opposite.

The pins on each side of the button are shorted, the "button" is between the sides of the button. Else your code looks alright.

Edit: Here's an image which shows how a push button is connected internally, make sure you're using the correct pins.


How can I understand the circuit diagram for Arduino Starter Kit Project 4? I have acquired the arduino starter kit project book, and the explanations seem at times confusing and difficult to understand.

Concerning the above circuit diagram, the book states (I am translating from French): "The resistor and the photoresistor are in series and together they divide up the voltage. The voltage at the point where they meet is proportional to the ratio of their resistances, according to Ohm's Law."

What does "the voltage at the point where they meet" mean? The voltage/ p.d. is always supposed to be across something, e.g. a certain component. This statement makes no sense to me at all.
The above misunderstanding leads on to me not understanding what the input pins A0-A2 actually receive. I understand that they receive a voltage, but don't know across what. Also, if the voltage inputs from these pins are used later on, are they digital? (these pins have an analogue-digital converter).

The important thing to remember, which will help you understand everything else, is that voltage is measured with respect to another point.

In this (and almost every) case it is measured with respect to ground. So when you say the voltage at point X is Y volts you are actually saying that the difference in voltage between point X and GND is Y volts.

So on your schematic A0 measures the difference in voltage between it's IO pin (the junction between the 10KΩ resistor and the LDR) and ground. And looking at it, what is between its IO pin and ground? The 10KΩ resistor. So it is actually the voltage across that resistor that you are measuring.

Doing the sums:

Assume there is enough light falling on the LDR to make it have a resistance of 5KΩ.  Current flows through both the LDR and the 10KΩ resistor in series, so it has a total resistance of (10,000 + 5,000) 15KΩ. With 5V across the whole lot (5V -> LDR -> 10KΩ -> GND) you get:

I = V/R = 5/15,000 = 0.000333... or 333µA.

333µA flowing through 10KΩ drops how much voltage?

V=RI = 10,000 × 0.000333... = 3.333...V

So A0 would be measuring 3.333V at that point.

Now, you turn out the lights, and the resistance of the LDR rises to, say, 50KΩ. What happens to those sums now?  Well, let's look:

Total resistance = 50,000 + 10,000 = 60,000Ω
I=V/R = 5/60,000 = 0.00008333...
V=RI = 10,000 × 0.00008333... = 0.8333...V

The formulae can be simplified into just the ratio of the two resistances:

           R2
Vout = --------- × Vin
        R1 + R2

So that is, with the lights on:

        10,000
Vout = --------- × 5 = 0.666... × 5 = 3.333...
        15,000

And with the lights on:

        10,000
Vout = --------- × 5 = 0.1666... × 5 = 0.8333...
        60,000

From that measured voltage, of course, you can then calculate what the resistance of the LDR must have been at the time. Rearranged the formula looks like:

      R2 × Vin
R1 = ---------- - R2
        Vout

Plug in the numbers for the voltage with the lights on:

      10,000 × 5              50,000
R1 = ------------ - 10,000 = -------- - 10,000 = 5,000Ω
       3.333...              3.333...

The kind of circuit is known as a Voltage Divider or Potential Divider and you can read more about them here: https://en.wikipedia.org/wiki/Voltage_divider


Arduino Memory Best Practice So I have been diving deep into AVR programming and have seen several different ways of defining constants. I know that some of these methods are from "C" and others are from more modern "C++" methods. So my question here is what is the preferred method?

Method 1:

#define MAX_ARRAY_LEN 3

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

Method 2:

const int MAX_ARRAY_LEN = 3;

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

In my searches online I have ran across several pages that mention using PROGMEM in the declarations to load the variable into Flash memory instead of SRAM. The thing I am unclear about using PROGMEM is what should be loaded into Flash and what should be loaded into SRAM? Should I be loading all const into Flash? Are there any performance hits using Flash?

Edit

I guess I was not clear on what I was asking. I understand that #define and PROGMEM are not related. My question is there are a couple of methods that can be used to define constants. One is #define (Method 1) and the other is const (Method 2), with the const type comes the PROGMEM, when using Method 2 there are now 2 areas where you can store variables, Flash and SRAM so when do you want to use PROGMEM and when do you want to just leave it, when using method 2? Is there any performance hits when reading from Flash vs SRAM?

I understand that when using method 2 it is now scoped and typed, but are there any other advantages? Are the programs smaller using one vs the other? Are there times that you would want to use one over the other?

(Duplicate of this.)
In your example, neither definition of MAX_ARRAY_LEN will use program space nor RAM.  If you were to use the definition somewhere, it will certainly use program space in the instruction that uses that constant:
for (int i=0 i<MAX_ARRAY_LEN, i++)
  Serial.print( my_array[i] );

In this case, a CPU instruction will load the constant 3 into a register.  So you can say that the 3 "used" a byte in the CPU instruction, and is part of the program size.  Most people ignore that, because a loading a variable into i uses both RAM and program space.
The primary advantage of using const instead of #define is that the former allows additional compiler type-checking.
C++ has introduced another keyword, constexpr, which tells the compiler that an entire expression can be evaluated at compile time and reduced to a single constant value.  Read all about it here.
To answer your comment, #define's are not stored anywhere.  They are a simple string substituion that happens before the compiler processes the C++ code.
When you build your sketch, the source files are processed in several phases.  First, there's a preprocessor phase that consumes all the lines that start with '#'.  The results of the preprocessing are sent to the C++ compiler.  The compiler will see all the included files inline, and all #define's will be substituted.
UPDATE
For example, #define XXX 3 will cause the preprocessor to replace all occurrences of XXX in the C++ file with 3.  The C++ compiler will never see XXX, it only sees 3.  You could do a search and replace with your editor, and the C++ compiler would not know the difference.  (Well, there are a few more tricks the preprocessor can do for you, but you only asked about defining a numeric constant.)  The generated code would be identical.
There is no "global space" for #define symbols.  There is a "dictionary" in the preprocessor that is used to perform the substitution, but that is ephemeral.
PROGMEM is not related to #define or const at all.  It is an attribute of a variable that indicates it is to be stored in FLASH, not RAM.  I think the key is that #define is just string substitution, but const is a C++ attribute of a C++ variable.  All of these are equivalent:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
int array[ maxArraySize ] = { 1,2,3 };

#define FOO 1,2,3
int array[] = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] = { 1,2,3 };

#define BAR = { 1,2,
int array[] BAR,3};
#define MAX_ARRAY_SIZE sizeof(array)/sizeof(array[0])

I hope that last 2 goofy examples help illustrate what a #define is... string substitution.
The PROGMEM attribute is a separate thing.  It can only be added to C++ variables, and it now requires the variable to also be const.  Extending the above, you could do this:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
const int array[ maxArraySize ] PROGMEM = { 1,2,3 }; // a flash array, not RAM

#define FOO 1,2,3
const int array[] PROGMEM = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] PROGMEM = { 1,2,3 };

#define BAR PROGMEM = { 1,2,
const int array[] BAR,3};
#define MAX_ARRAY_SIZE 14

Again, in that last goofy example I used PROGMEM in the #define BAR, but it's just some characters as far as the #define is concerned.  And the last define is just plain wrong, but it will compile.
Because there is no validation of a string substitution, it is usually better to use a const type var = value; that can be validated by the compiler, both when it is defined and again when var is used in some context.
UPDATE 2
You say,

with the const type comes the PROGMEM

Not really.  const is the "read-only" attribute, and the compiler enforces that.
PROGMEM tells the AVR compiler that, if storage is required for this variable, put it in FLASH memory (a special address range) instead of RAM (a different address range).  Because of the AVR architecture, you must access FLASH differently, with special instructions.  The avr.pgmspace.h include file has some routines (macros and inline assembler) for reading from those address spaces.
I emphasized the "storage space required", because the compiler can optimize away the storage.  The literal 3 constant MAX_ARRAY_LEN does not need any storage space.  For this example program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( MAX_ARRAY_LEN );
}

void loop() {}

This is the generated code:
  Serial.println( MAX_ARRAY_LEN );
156:    50 e0           ldi r21, 0x00   ; 0
158:    63 e0           ldi r22, 0x03   ; 3
15a:    70 e0           ldi r23, 0x00   ; 0
15c:    82 e2           ldi r24, 0x22   ; 34
15e:    92 e0           ldi r25, 0x02   ; 2
160:    f7 c2           rjmp    .+1518  ; 0x750 <_ZN5Print7printlnEii>

The compiler knows that storage is not required.  The value "3" is pushed directly onto the stack at program location 0x158.  It did not go to RAM nor FLASH (PROGMEM) to load a 3 into a register, and then push that register's value onto the stack.
The compiler knows the value, so it uses the "immediate" form of the instruction to push the 3.
However, for this program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
}

void loop() {}

The following code is generated:
  e4:   03 00           .word   0x0003  ; ????
     .
     .
     .
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 158:   50 e0           ldi r21, 0x00   ; 0
 15a:   64 ee           ldi r22, 0xE4   ; 228
 15c:   70 e0           ldi r23, 0x00   ; 0
 15e:   82 e2           ldi r24, 0x22   ; 34
 160:   92 e0           ldi r25, 0x02   ; 2
 162:   b5 c2           rjmp    .+1386      ; 0x6ce <_ZN5Print7printlnEji>

Because I took the address of MAX_ARRAY_LEN, the compiler knew that it had to have storage... in order for it to have an address.  The compiler dutifully locates it in the program space, at 0xE4.  You can see that address being pushed onto the stack at 0x15A.
Without the PROGMEM attribute, the following code is generated:
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 156:   50 e0           ldi r21, 0x00   ; 0
 158:   60 e0           ldi r22, 0x00   ; 0
 15a:   72 e0           ldi r23, 0x02   ; 2
 15c:   84 e2           ldi r24, 0x24   ; 36
 15e:   92 e0           ldi r25, 0x02   ; 2
 160:   b5 c2           rjmp    .+1386      ; 0x6cc <_ZN5Print7printlnEji>

This is a RAM address, 0x200.  Long before setup, a 3 is copied from the program space into RAM.  It is using both program space and RAM.
But this is only because I took the address of MAX_ARRAY_LEN.  In almost all cases, you will be using these as scalar values.  The compiler will not allocate any storage space for them, and the PROGMEM attribute is irrelevant.
You have another question:

Is there any performance hits when reading from Flash vs SRAM?

Yes.  Reading from flash takes twice as many CPU cycles.  It's always a juggling act.  If you need to squeeze every cycle out, make sure your constants do not even need storage space (i.e., don't take their address).  And if it's a PROGMEM array or structure, consider using a cached value (i.e., loaded into a RAM array or structure).  Sometimes you don't have a choice.  If you are out of RAM, you will have to load them from PROGMEM every time you need them, with a small penalty.  RAM, SPEED, SIZE... pick two.


Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in my earlier post. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.

The accelerometer data is stored in arrays of xArray[k] for the x-coordinate values, yArray[k] for the y-coordinate values and zArray[k] for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

I hope this is helpful to you.

First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.

Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20

Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.

This is what I did in Matlab. YPR = Yaw, Pitch, Roll

data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

Then you have to set up the plot and force matlab to update the plot in real time.

%set() is used to set graphic object properties
       set(plotGraph1,'XData',time,'YData',Y,'color','r');
       set(plotGraph2,'XData',time,'YData',P,'color','g');
       set(plotGraph3,'XData',time,'YData',R,'color','b');
       drawnow;           %force matlab to updata plot instantaneously

The link below is a good place for you to get going. But you need to make some modifications to it though.

https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/


How to generate Chirp Signal using Arduino i would like to generate Chirp Signal (Frequency Sweep) using Arduino. i have searched a lot in internet but didn't find anything.

Basically, any parameters is also ok. But the concept is what i am searching for.
The signal will be sent to the DAC of the Arduino board.

Edit
I would like to generate sine wave signal from 3kHz up to 100kHz sweep frequency with amplitude peak to peak 1.5 volt.

thanks for your support.

If you're ok with starting with square wave signals, this can be done on an Arduino.
You need to do the following:

Configure a 16-bit Timer to CTC mode
Select the right prescaling
Add a RC low pass filter to the output and voltage divider

Configure a 16-bit Timer to CTC mode

Assuming I'm using Timer 1 and OCR1A:

TCCR1A |= (1<<COM1A0); // Toggle OC1A on match
TCCR1B |= (1<<WGM12); // Clear to Compare mode
TCCR1B |= (1<<CS10); // No prescale

Select the right prescaling

In case you're wondering, prescales are used when the MCU clock is much faster than the output you desire.
Without prescaling, the highest frequency is 16MHz/2 = 8MHz, and the lowest frequency would be 8MHz / 2^16 = 122Hz . Which covers the range of frequencies that we want.

Setting OCR1A value to 80 gives you a frequency of 100kHz
Setting OCR1A value to 2667 gives you a frequency of 2.9996kHz

You can then control the chirp like so:

// Linear rise in wave period
int x = 10;
for (int x=80; x < 2668; ++x){
  OCR1A = x;
  delay(10); // 10ms delay
}

Add a RC low pass filter to the output and voltage divider

Making the perfect sine waves may be too troublesome, so we'll resort to the poor man's sine wave.

Here's the poor man's implementation by TI (still require quite a few parts.)

Personally, I'm cheap so I'd go for the RLC approach. ;-)


Can't store time over 9 hours and 10 minutes I am making a clock on my Arduino Uno using the time library http://playground.arduino.cc/Code/Time

I let the user set a time. Which is then converted to seconds and used in the

setTime(s);

function.
When the value is over 9:10h, the seconds evaluate to 4 294 941 360 seconds (=
1 193 039.27 hours)

A code snippet:

void timeChange() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Change time");
  lcd.setCursor(0, 1);
  lcd.print("00:00");
  int hoursSet    = 0; //Stores the hours added.
  int minutesSet  = 0; //Stores the minutes added.
  String printTime;
  bool timeComplete = false;
  while (!timeComplete) {
    int buttonVal = analogRead(A0);
    if (buttonVal >= 490 && buttonVal <= 520) { //Indicates button 3 is pressed. It's function is to add one hour to the time.
      hoursSet = (hoursSet + 1) % 24; //Adds one hour to the hours.
      delay(100);
    } else if (buttonVal >= 5 && buttonVal <= 10) { //Indicates button 4 is pressed. It's function si to add 5 minutes to the time.
      minutesSet = (minutesSet + 5) % 60; //Adds minutes to the minutes.
      delay(100);
    }

    lcd.setCursor(0,1);
    String strHr = String(hoursSet);
    String strMn = String(minutesSet);
    if(strHr.length() == 2){
      lcd.print(hoursSet);
    } else if(strHr.length() == 1) {
      lcd.print("0");
      lcd.setCursor(1, 1);
      lcd.print(hoursSet);
    }

    lcd.setCursor(2,1);
    lcd.print(":");
    lcd.setCursor(3,1);
    if(strMn.length() == 2){
      lcd.print(minutesSet);
    } else if(strMn.length() == 1) {
      lcd.print("0");
      lcd.setCursor(4, 1);
      lcd.print(minutesSet);
    }
    delay(100);

    if (buttonVal >= 990 && buttonVal <= 1010) { //if button 2 is pressed again, the timecomeplete is set to true, and the script continues.
      timeIsSet = true;
      timeComplete = true;
    }
  }
  lcd.clear(); //Clear the screen
  lcd.setCursor(0, 0);
  lcd.print("The time"); //Print text, move cursor and print the time
  lcd.setCursor(0, 1);
  String strHr = String(hoursSet);
  String strMn = String(minutesSet);
  if(strHr.length() == 2){
    lcd.print(hoursSet);
  } else if(strHr.length() == 1) {
    lcd.print("0");
    lcd.setCursor(1, 1);
    lcd.print(hoursSet);
  }
  lcd.setCursor(2,1);
  lcd.print(":");
  lcd.setCursor(3,1);
  if(strMn.length() == 2){
    lcd.print(minutesSet);
  } else if(strMn.length() == 1) {
    lcd.print("0");
    lcd.setCursor(4, 1);
    lcd.print(minutesSet);
  }
  lcd.print(" is saved!");
  setTime((hoursSet * 3600) + (minutesSet * 60));
  timeIsSet = true;
  delay(5000); //Wait five, seconds then proceed

}

Added this to the code:

      Serial.print("hours ");
  Serial.println(hoursSet);
  Serial.print("hours in s ");
  Serial.println(hoursSet * 3600);
  Serial.print("minutes ");
  Serial.println(minutesSet);
  Serial.print("minutes in s ");
  Serial.println(minutesSet * 60);
  Serial.print("Combined:  ");
  Serial.println( (hoursSet * 3600) + (minutesSet * 60) );

When I input 5:15 it results in:

  hours 5
  hours in s 18000
  minutes 15
  minutes in s 900
  Combined:  18900

When I input 9:15 it results in:

  hours 9
  hours in s 32400
  minutes 15
  minutes in s 900
  Combined:  -32236

So, it looks like the library only holds an Int. But that seems odd, as the function expects seconds.

Here's a hint: 32767 seconds is 9 hours, 6 minutes and 7 seconds.

What is the largest value that an int can hold?

EDIT: I can't add comments on this computer (old browser), so I have to respond to your question here.
time_t is an unsigned 32-bit value, but all of your input values are signed 16-bit values. When you take a product like 3600*10, you get a bit pattern of 1000110010100000, which is 36000 when interpreted as an unsigned value, but is -29536 when interpreted as a signed value.

When assigned to a time_t, the value is sign-extended to 32 bits, which makes it 11111111111111111000110010100000, which is 4294937760 when interpreted as an unsigned value.

If you want to write a statement like

time_t x = (hoursSet * 3600) + (minutesSet * 60);

you need to type-cast your input arguments to the correct type first:

time_t x = ((time_t)hoursSet * 3600) + ((time_t)minutesSet * 60);


Will Setting Interrupt Pin High Damage Bluetooth Module? I want my HC05 Bluetooth Module to trigger an interrupt when it receives a signal. So I've followed suggestions from the Arduino Forum and connected the Bluetooth TXD pin to the Arduino RX Pin and the Interrupt Pin (2), which I set to high. It is set to detect a FALLING voltage, presumably when BT transfers data. When I connected it this way a funny thing happens. I can clearly see that the interrupt is being called because power consumptions goes way up when Android sends a message to BT module, meaning the device wakes up. However the serial port no longer appears to work on the Nano. I think I narrowed down the possible cause to me damaging the board by removing lineage regulator or damaging serial port somehow with the interrupt. Is the way I wired up the interrupt pin as described correct? Your help would really help me narrow down my problem.
#include <avr/sleep.h>

#define ledPin 7
#define intPin 3
int state = 0;
int stateData = 0;
int ultraPin = 10;
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
long duration, cm;
unsigned char inches;
unsigned long timer;

void setup() {
  pinMode(ultraPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(intPin, INPUT);
  digitalWrite(intPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(intPin), interrupt, FALLING);
  digitalWrite(ultraPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
}

void interrupt(){
  Serial.println("interrupted");
  sleep_disable();
  Serial.write(50);
  delay(500);
  timer = millis();
  digitalWrite(ultraPin, HIGH);
  while (true){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);
      cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
      inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
      Serial.write(inches);
      delay(50);
      stateData = Serial.read();
      if (stateData != 49){
        // receipt from android
        unsigned long timeElapse = millis() - timer;
        if (timeElapse > 5000) {
          break; // exit and SLEEP
        }
      }
      else {
          // reset the timer
          timer = millis();
        }
      }
    sleep_enable();
    sleep_cpu();
}

void loop() {

}

I'm not sure, if you can rule out the hardware damage (you wrote, that you removed the linear voltage regulator, but didn't explain more there). But with that code you won't get what you want.
I see multiple issues, all boiling down to the same problem: You cannot do that inside of an ISR:

delay() relies on interrupts to happen during its execution. As of my knowledge this leads to delay() never ending, blocking your code. Also it is very bad design to have a long running ISR. So much is depending on interrupts to work and when you have something long running, you can just easily do that inside the main code, triggered by an interrupt flag variable.
millis() will not increment during the run of the ISR.
delayMicroseconds() will work, but you still should keep the ISR very short. Reading an ultrasonic sensor is a no-go.
Serial.write() will fill the libraries internal TX buffer, but the actual transmission of the data also relies on interrupts. You won't get your data that way.

Instead of doing all that inside the ISR, you should just let the Arduino wake up, then set a (single byte) flag variable. In your main code you need to check for that flag with an if statement. In that if statement, you are doing all what you need to do and at the end you are resetting the flag and going to sleep again.


Inaccurate PWM Signal Frequency and Timing I have a Teensy 3.2 and I am using the Arduino IDE to program it. I am trying to generate 8 pulses with the frequency of 40 kHz and this needs to be repeated every second. I have written 3 different codes and none of them is working quite the way I wanted. The duty cycle of the pulses are not always constant (i.e. the falling edge often shifts in the time axis), indicating an inaccuracy with the delay between the analogWrite commands. There seems to be an issue with delays not being consistent and changing within the 8 pulses and between the 8 pulses. This inaccuracy is different between the 3 different codes, but exists in all of them. Changing the processor speed between 16 MHz and 120 MHz does not appear to change the problem (except in code 3 where NOP is dependent on it). Is there a way to make the cycles more consistent at 40 kHz? Do I need to use an external timer or oscillator? The two images below display the two problems. The first image shows the differences in time delays and output frequency. The red dashed lines are provided to show the discrepancy in the same pulse at successive iterations of the code. The second image shows a recurring issue where the square wave is not in fact a square, and doesn't seem to be caused by software problems.

Image 1:

Image 2:

The codes I have written can be found below:

Code 1:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  analogWriteFrequency(pin1, 40000);
  analogWriteFrequency(pin2, 40000);
}

void loop() {
  analogWrite(pin1,128);   //for 50% duty cycle
  delayMicroseconds(188);  //It takes 187.5us to generate 8 pulses at the given frequency
  analogWrite(pin1,0);
  delay(1000);
}

Code 2:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayMicroseconds(10);
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayMicroseconds(10);
      analogWrite(pin2, 0);
  }
}

Code 3:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

// Variable N determines the length of the delay.
// Execution of NOP corresponds to 62.5ns delay
// when the processor speed is 16 MHz.
const int N = 50;
#define NOP __asm__ __volatile__ ("nop\n\t")

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayNOP();
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayNOP();
      analogWrite(pin2, 0);
  }
}

void delayNOP(){
  for(int j =0; j<=N; j++){
    NOP;
  }
}

it seems in the first picture that the two pulses have different duty cycles which is why it appears shifted. It looks like the 'on' part stays on for less time than the 'off' so your duty cycle is probably <50 but your frequency might still be 40kHz.

I think the most accurate way of getting 40kHz just with a teensy is to use timer interrupts as Majenko suggested. Check out the documentation for it here, its pretty straight forward,you set the timer to go off every 12.5us and in the ISR simply toggle a digital pin and keep count of how many times you've toggled it. If your teensy needs to run other interrupts you should change the priority using myTimer.priority(number); to possibly give the 40kHz interrupt a higher priority. One thing, don't use digitalWrite in the ISR as its slow af, either try digitalWriteFast or use assembly language to toggle it as pointed by Majenko.

Alternatively you could use a 555 timer which is easy to setup and I'm pretty sure it's been used to gerate 40kHz at 50% duty cycle, although it might be a bit tricky finding the correct capacitor/resistor values if they're too small/non-standard. Then you would hook up the output of the 555 timer to whatever you're hooking it up to and also to a digital input pin on the micro. Then you would have to set an external interrupt on that pin so whenever the 555 goes high the interrupt on the pin would fire and you would keep track of how many pulses have been generated.

Alternatively, you could use a digital signal synthesizer. I used the ad9837 for one of my projects. It can generate something like 0-3Mhz with a 5Mhz external clock at a resolution of 0.02 which is pretty good. I've got an altium design for it if you don't want to buy the module and an adapted version of the adafruit miniGen library which works with teensy3.5 link. Then you'd need to do the same feedback loop as the 555 to keep track of how many pulses have been produced (or your way of waiting X microseconds). The module is actually pretty low power so you could power it from a digital pin and turn that pin on/off every second.

I think you should try the interrupt method first, as it's the easiest. Also, I get that you want 8 pulses evey one second but maybe for debugging purposes have the 40kHz pulse go constantly and change your scope to measure frequency so you can see how far off you are from 40khz.Then once you know you're actually getting 40khz have it run every 1second.


Converting ESP32 SPI code to Arduino for MAX6921 IV-18 driver board I purchased a IV-18 VFD tube driver module, which came with some example code for an ESP32 board. The driver module has a 20 output MAX6921 serial chip to drive the vacuum tube. I want to use this driver module with an Arduino Uno and then eventually a Raspberry Pi.
I think I have a very rough understanding of the electronics and demo code, but cannot seem to get my SPI calls to work. Rather than trying to translate the demo code in its entirety, my first goal is to just get one segment to light up.
Quick background
The IV18 tube has 9 grids. The first grid has only a dot and a dash, but the remaining 8 grid have 7 segments and a decimal point.

To light a segment, you provide power to the segment pins / decimal point and to the grid for that segment. To display several numbers, you have to quickly cycle through lighting each of the grid positions and the relevant segments for that position. If you cycle through this fast enough, the human eye sees the whole grid with numbers (persistence of vision).
What I have tried
So far, I have made the connections from the Arduino Uno to the driver board
Driver GND   - Uno GND
Driver 5V    - Uno +5V
Driver Din   - Uno digital pin 11 / MOSI
Driver CLK   - Uno digital pin 13 / SCK
Driver LOAD  - Uno digital pin 2
Driver BLANK - Uno digital pin 3
Driver Dout  - Not connected

The example code has hex codes which I believe are then translated to a 24 bit buffer (although only 17 bits are required) to send via SPI to set the MAX6921 outputs HIGH or LOW.
I think the bits required are as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

G7
G6
G5
G4
G3
G2
G1
G0
SEG_G
SEG_F
SEG_E
SEG_D
SEG_C
SEG_B
SEG_A
SIGN

DP

So to light the number 8 in the righthand most grid, I assumed I'd need the 8th bit high (grid) and bits 9,10,11,12,13,14 and 15 for the 7 semens for the "8".
In my setup function, I call SPI.begin and then SPI.transfer with what I assumed was the matching binary data (from right to left, I think because of the bit order LSB/MSB?):
SPI.transfer(0b000000000111111110000000);
This lights the first grid (the one after the degree and minus sign) but not what I want - I see some segments in the leftmost grid (the full grid, not the grid with the dot and minus) but these light in a different pattern each time  (varies each time I reset or re-upload which I think is to be expected as I'm pushing data to the MAX6921 each time).
This is my code so far
#include "SPI.h"

#define DISP_CLK 13   // White - SPI SCK
#define DISP_DATA 11  // Yellow - SPI MOSI
#define DISP_LOAD 2   // Blue
#define DISP_BLANK 3  // Green

void setup() {
  Serial.begin(9600);
  Serial.println("IV18 Test");

  SPI.begin();

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

  pinMode(DISP_LOAD, OUTPUT);
  digitalWrite(DISP_LOAD, HIGH);

  SPI.transfer(0b000000000111111110000000);
}

void loop() {

}

I'm pretty sure the two fundamental things I have wrong here are the bits of data to send and then the correct use of the SPI.
Can someone please help me to understand the ESP32 code properly, and ideally help me get the correct data to send via SPI so that I can light up the segments & grid positions that I expect to.

So it turns out that I got a few things wrong.
UPDATE: Working code is now on my GitHub if anyone is interested.
Firstly, I misunderstood the example code and made a mess of the bits to send to the MAX6921. To work out the correct mapping, I went and probed each pin of the IV-18 and noted the connection to the pins / outputs of the MAX6921 which gave me this table:

BIT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

IV-18
G9
G8
G7
G6
G5
G4
G3
G2
G1
A
B
C
D
E
F
G
DP

MAX6921
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Note that the MAX6921 value is the OUTPUT number and not the PIN number
This then gave me the correct order for each bit to send, as noted in the top row of the table.
The next mistake was trying to send all 24 bits in one go. Instead, I broke each byte into a separate SPI.transfer() call which finally let me display the segments in the grid position that I expected.
For example, to display "HELLO", my loop function has this:
void loop() {
  //             XXXXXXXDP                 GFEDCBA1                  23456789
  SPI.transfer(0b00000000); SPI.transfer(0b11101100); SPI.transfer(0b10000000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b11110010); SPI.transfer(0b01000000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00100000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00010000); delay(1);
  SPI.transfer(0b00000001); SPI.transfer(0b01111110); SPI.transfer(0b00001000); delay(1);
}

I have setup TIMER1 to use instead of the loop/delay code, so hopefully I can finish converting the rest of the example code to Arduino.


Frequent ON OFF in SSR I am working on a project on Arduino OLED MAX6675 thermocouple and SSR for my oven.
My problem is when my SSR goes in LOW or HIGH state it  turn ON and OFF several times before going to permanent HIGH or LOW state.
This make my load(Heater) on and off many times. Since the temperature crosses the set-point to change the output state, the process temperature will be cycling rapidly, going from below set-point to above, and back below.
This frequent ON OFF will damage my SSR and heater.
My Question.
Is there any hardware or software solution. To reduce the frequency of ON OFF .
I can’t increase  the delay() time because it make my button input slow.
My codes are below.

#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include "max6675.h"

//oled
//oled i2c addresss
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(-1);
// 128 x 64 pixel display
#define SSD1306_LCDHEIGHT 64

//MAX6675
//Pin initialization
int so = 2;
int cs = 3;
int sck = 4;
MAX6675 thermocouple(sck, cs, so);
float current_temp;
int set_temp;
int const h_temp = 2;

//Button
int button_up = 7;
int button_down = 8;
int button_upv;
int button_downv;

//SSR
int ssr_u = 10;
int ssr_d = 12;

void setup() {
    Wire.begin();
    delay(1000);

    // initialize and clear display
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(8, 20);
    display.println("Welcome..");
    display.display();
    display.clearDisplay();
    delay(1000);

    //Button
    pinMode(button_up, INPUT);
    pinMode(button_down, INPUT);
    set_temp = 20;
    pinMode(ssr_u, OUTPUT);
    pinMode(ssr_d, OUTPUT);
}

void loop() {
    current_temp = thermocouple.readCelsius();
    delay(100);
    button_upv = digitalRead(button_up);
    button_downv = digitalRead(button_down);

    //button
    if (button_upv == HIGH && set_temp < 180) {
        set_temp = set_temp + 5;
    }
    if (button_downv == HIGH && set_temp > 20) {
        set_temp = set_temp - 5;
    }

    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.println(current_temp);
    display.setCursor(5, 30);
    display.println(set_temp);

    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(30, 40);
    if (button_upv == HIGH) {
        display.println("Up");
    }
    if (button_downv == HIGH) {
        display.println("Down");
    }
    display.display();

    //SSR
    if (current_temp < set_temp - h_temp) {
        digitalWrite(ssr_u, HIGH);
        digitalWrite(ssr_d, HIGH);
        delay(500);
    }
    if else(current_temp > set_temp + h_temp) {
        digitalWrite(ssr_u, LOW);
        digitalWrite(ssr_d, LOW);
        delay(500);
    }
}

Thanks in advance for help

You need to implement hysteresis. Set two temperature points around set_temp. One a little higher to be a limit for turning the heater off and a one a little lower then set_temp to turn the heater on.

You only need to change your if else condition a little

if (current_temp < set_temp - HYST_VALUE) {
  digitalWrite(ssr_u, HIGH);
} else if (current_temp > set_temp + HYST_VALUE) {
  digitalWrite(ssr_u, LOW);
}

you could start with

int const HYST_VALUE = 1;


What's the fastest way to periodically communicate via serial? I will be using an Arduino as a bridge between a computer high-level Java client and some low-level hardware computing units (e.g. other Arduinos). I need to find a solution to periodically communicate in both ways. It should be possible to send digital, analog inputs to the PC and receive digital, analog outputs from the PC via serial.

I have very specific requirements for my project to work:

Lowest possible latency in both ways. High latency would cause
instability of controlled systems.
Extremely constant, possibly user-defined update period. Varying
sample rate would cause inaccuracies in the control.

I need a very fast solution possible for update frequency of 100 Hz and higher.

So far I have tried to send data via Firmata to my java client using time interrupt.

ISR(TIMER1_COMPA_vect) {
  Firmata.sendAnalog(analog, analogRead(analog));
}

The messages however don't come at a very constant rate and are sometimes held up for twice the sample period or more which is unnaceptable. For higher frequencies this happens even more often. I suspect some kind of a buffer. Do you have any idea where should I look for bottlenecks? Would it be benefiting to design my own communication protocol and ditch Firmata?

EDIT: Look at the attached diagram . Blue lines are "inputs", green lines "outputs". Right now I am trying to design the "Arduino (Bridge)"

Lowest possible latency in both ways. High latency would cause instability of controlled systems.

the fact that you are using a not-real-time OS introduce a lot of unpredictable latency, the use of a visrtual machine over that os then add a bit more.
Fast communication can be obtained increasing the baudrate, that will decrease the latency between the sample and the elaboration.
Also sending RAW data instead of string will be faster (no convertion AND less byte send), and finally decreasing the overhead caused by the protocol.

For example Firmata by default use a low baudrate AND will add a lot of overhead to send WHAT kind of operation is doing. Writing your own communication protocol is better.

For example: analogRead use 10bit, so you may send a raw int, 2 byte, 16bit, so 6 bit are lost.. or you can "compress" with a bit of bitwise operation 4 read (40 bit) into 5 byte (40bit, no bit loss) instead of 8(int size * 4)!

AnalogRead is a really slow operation by default on arduino (~200us), but can be faster if you set up a lower prescaler (attention, lower prescaler means less ADC precision. at prescaler 16 guaranteed precision is 8bit, if my memory is good)

  Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

On the PC side, if you need micro/nano second precision you need a real time os, newest linux kernel add a new special schedule but i think is still hard to find documentation. If less precision is ok, just use a timer.

On the arduino side, using a hardware timer is the best way, see LeOS for a nice scheduler on arduino

Please note HardwareSerial on the arduino side use interrupt to send data, so using it inside an ISR (like you are doing now or with LeOS) is really usafe and deadlock prone.
Also ISR will "slow down" each others, as they cannnot be executed parallel; and analogRead is a realtivly slow operation..
I would use timer to set up a flag, and in the loop if i see the flag, start the analogread, Serial.write and finally Serial.flush (to be sure to not fill Serial buffer, causing a lot of trouble on the arduino reprogrammation reset)


Safe changes in the Arduino Libraries and use them I changed 2 Arduino Libraries because i have a 9 bit data protocol, now i want use the amended Libraries on my Arduino mega2560.

At first i have set a 9 bit data mode that can i do when i set the UCSZ12 bit on 1(original code under the following link: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103 ):

void HardwareSerial::begin(unsigned long baud, byte config)
  ...
  sbi(*_ucsrb, RXCIE0);
  sbi(*_ucsrb, UCSZ12);  // chance: set 9-bit data mode on 1
  cbi(*_ucsrb, UDRIE0);
  ...

At second i want throw an interrupt when the 9th bit is an 1 that can i do when i change the code like the follow (original code under the following link : https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial_private.h#L101 ):

void HardwareSerial::_rx_complete_irq(void)
  if (bit_is_clear(*_ucsra, UPE0)) {
    bool is_address = UCSR0B & _BV(RXB80);
    unsigned char c = *_udr;
    if (is_address) {
      do_something_with_address(c);
      return;
    }
  rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
...

What must i do with the two file´s?

How can i use the changed Libraries?

I found the path to the files i want change in the github link so i can change the files(C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino).

I enable the uart for 9 bit, i add sbi(*_ucsrb, UCSZ12);  in HardwareSerial::begin

I decided that i only send a Flag to my PC when the 9th bit is set. For that i change the _rx_buffer to a 2 byte matrix (short _rx_buffer). Now i send the databyte in the low-byte and flags for 9 bit, framing error and overrun error in the high-byte. That i can do that i change the void HardwareSerial::_rx_complete_irq(void) code like the follow:

void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0))
  {
    bool is_address = UCSR0B & _BV(RXB80);
    bool is_framError = UCSR0A & _BV(FE0);
    bool is_overError = UCSR0A & _BV(DOR0);
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    if (i != _rx_buffer_tail)
    {
     _rx_buffer[_rx_buffer_head] = c;
     _rx_buffer[_rx_buffer_head] |= is_address << 8;
     _rx_buffer[_rx_buffer_head] |= is_framError << 9;
     _rx_buffer[_rx_buffer_head] |= is_overError << 10;
     _rx_buffer_head = i;
    }
  }
  else {    *_udr;  };
}

I hope this will work and i can evaluate the data right at the PC.

Frindly wishes sniffi


Two sensors on one input I got this question from my teacher the other day and I can't figure it out:

  If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

In short, the project includes an Arduino Uno with two ultrasonic sensors.

There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.

The active solution requires a device called a multiplexer.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.

The passive solution is called open drain or open collector (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.


How to connect HC-05 to an arduino Galileo? I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using Serial. functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo here.

So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?

This might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.

Cheers!


How do you call to a previous function? I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions?

You need to get your head around the Finite State Machine (FSM).

It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State").  One state would be reading pressure. Another state would be "testing", or whatever.

I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine


Using #define and multiple classes I am using the FastLED library in my program and the basic usage is that the following lines go at the top of the main sketch:

#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

You can see the documentation at https://github.com/FastLED/FastLED/wiki/Basic-usage

However, I am using the FastLED library in several different objects in my program and I would like to be able to reference NUM_LEDS in different header files for each object so that the number of LEDS can be controlled just by changing the value in the main sketch.

I am also intending that my own objects can be made into libraries for others to use, so they will then define the settings in their main sketch, that my libraries will then use.

As the OP suggested, I'm posting a summing up of the comments under his question since the answer was found.

In order to make a common define for those parameters in different source files, the easiest solution is to make a shared header. To do this, just create a new file called FastLedInclude.h and, inside of that, write

#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

Then in every source file you will just have to #include "FastLedInclude.h" to be able to use that library.

The FastLED library also requires the programmer to create a struct. Now, placing the definition of the struct (i.e. struct CRGB leds[NUM_LEDS];) into the header file leads to compilation errors, since the compiler writes the code to allocate it once for every object file.

The correct way to share this among different object files is to declare it extern in the header, then define it just once in one of the cpp or ino files:

// into FastLedInclude.h
extern struct CRGB leds[];

// into any cpp or ino file (but just once)
struct CRGB leds[NUM_LEDS];

This can also be done in the main ino sketch file, but personally I prefer to define it into another one (it depends, however, on how you choose to divide the program).

If you want to create a library, some other problems arise. The easiest solution is to ask the user to manually modify the header file which will be in the library folder. This solution is a bit uncomfortable, but it is the safest one.

Another solution is to force the user to create a header file into the sketch folder. Then the library should know the sketch folder path to back-include it. But.. This is a very discouraged option, since it will require the library to know the sketch location, thus violating the consistency principle at the base of a library-based approach.

The third solution is to modify the approach, from a compile-time static definition to a dynamic one. In order to do this, instead of defining NUM_LEDS and DATA_PIN at compile time you save them as variables in the library class.

For instance, in your library class definition you have

class yourclass
{
    public:
        yourclass(uint8_t data_pin, uint8_t num_leds);
        ~yourclass();
    private:
        uint8_t _data_pin;
        uint8_t _num_leds;
        struct CRGB *leds = NULL;
};

And the implementation can be

yourclass::yourclass(uint8_t data_pin, uint8_t num_leds)
{
    _data_pin = data_pin;
    _num_leds = num_leds;

    // Dynamic allocation of the array
    leds = (struct CRGB *) malloc(num_leds * sizeof(struct CRGB));
}

yourclass::~yourclass()
{
    // you should free the leds array when done
    free(leds);
}

Then the user can write

yourclass *obj = new yourclass(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass *obj = new yourclass(DATA_PIN, NUM_LEDS);

or, in the case of a statically allocated object,

yourclass obj(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass obj(DATA_PIN, NUM_LEDS);


Use chars in quotes in const char* as name of function I have been trying for a long time how to use a word declared as const string* word = "xxx" as name of void function declared somewhere below in my code.
Here is example with ssid:
const char* ssid = "name_of_ssid";

void (*name of ssid*) () {

⠀//some code

}

I want to use word declared in const char* in quotation marks as name of function.
It can not be written just void ssid().
Yes, I can set a name of void function manually, when const char* ssid = "CoffeeWifi" I can type void CaffeeWifi() but I want to do that by this way because my code is specific for this option and explaining this code here would be very difficult. When I change array of const char* word from "xxx" to "yyy" I want to  change the name of void from void xxx() to void yyy() as well.
How to do that? What function should I use?
Thank you!

Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.
An example:
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}


Can we generate 20kHz tone with normal buzzer in arduino? Can normal buzzer be used for generating high frequency audio and if this is possible then can normal microphone module be able to detect the same frequency range(15 kHz - 20 kHz).
Here is the specifications of this buzzer:-
Rated Voltage : 6V DC
Operating Voltage : 4 to 8V DC
Rated Current* : ≤30mA
Sound Output at 10cm* : ≥85dB
Resonant Frequency : 2300 ±300Hz
Tone : Continuous
Operating Temperature : -25°C to +80°C
Storage Temperature : -30°C to +85°C
Weight : 2g
*Value applying at rated voltage (DC)

An arduino is very well capable of producing a 20KHz signal. You can use a PWM signal on one of the PWM pins, generate the signal by alternating a pin high and low with a few microseconds in between or you can use a buzzer with an input signal that can play a continuous tone at a specified frequency. I really can't see if the module you show can generate a tone based on the input.
Detecting a tone, however is somewhat difficult. You need an analog microphone amplifier, an ADC (analog-to-digital-converter) and some processing to detect a frequency in the signal data.
The usual microphone modules that are sold for arduino's are mostly just noise detectors and generate a signal when loud noise is present.


Serial communication between multiple devices (or Arduinos) What I know from my search on the internet, for both SPI and I2C protocols, communication between multiple devices needs a master, which initiates the communication, and slaves, which respond to the master's request. Basically slaves can't initiate a transfer.

Is there any way to make different devices communicate on their will? I'm not sure about UART, but I think the story is the same here. But I know that it is possible to use a USB hub to connect multiple USB devices to one port on the computer. How can that be done? Can I use the same principle with Arduino?

To clarify what I want to do, consider that I have different modules (might be Arduinos) with different characteristics. I want to connect them on a bus line to a master Arduino. The module connections should be indifferent so that the user doesn't have to worry about which port should be used to connect the module. For this reason, using an Arduino Mega with more serial interfaces doesn't solve the problem, because we don't know which device is connected to which port.

Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.

However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.

That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).

The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.

It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.

Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.

As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.


Arduino Nano + (2* tlc5940) + 34 LEDs = Power Questions This is an adapted layout for two tlc5940 hooked up to an Arduino nano. The original project can be found here. I am a little unsure about the capacitors and resistors as that project had it hooked up to a 5v wall plug.

My Design will be running a pattern of PWM, blinking and chasing lights. The two red lights are off of the TLC5940s circuits because reds need a different resistance. If i am wrong, please let me know as that would simplify things.

Also as is the way of the stack community, any other red flags you can point out would be greatly appreciated as i am new to this game.

As Ignacio has mentioned the TLC5940 is a constant current driver. The 2kΩ resistor sets the current for the LEDs regardless of the forward voltage (or colour) or the supply voltage.

Also as Gerben says, move the 0.1µF (100nF) capacitor close to the TLC5940 as you can. There should be one for each TLC5940 since they are decoupling capacitors.

You might like to increase the capacitance of the electrolytic too. The purpose of that capacitor is to provide a low impedance energy source to supply the circuit (batteries are actually quite high impedance by comparison). Since you have lots of LEDs being controlled by PWM the current draw will be fluctuating wildly all the time, and lots of energy over brief periods will be wanted.

Another thing to watch, mentioned again by Ignacio, is the supply voltage for the TLC5940 is 5.5V absolute maximum. I wouldn't go much above 5V. Depending on what your batteries actually are you may be better running from 3 of them (4.5V alkaline AA - Ni-MH would be ~3.6V, so 4 of them, giving 4.8V, would be better in that situation).

I would also question your use of the TLC5940. They are not the easiest chips to drive requiring quite a strange protocol. Personally I prefer the TLC59116 which is the I2C variant of the same chip. Much easier to control from an Arduino, and requiring just 2 pins. Not so easy for bread-boarding though as they're SMD only.


BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1 Arduino Uno R3

Windows 10

Bascom AVR

The ON is alright.

The LED flickers now and then.

The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.

Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this.
The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.

So I hope you can use easy terms.
Thank you.

I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader.  It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol.  The arduinoisp.ino sketch also implements stk500v1.  So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2.  STK500v2 has been used in some of the larger arduino "Mega" boards.
So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud.  If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO.  If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.


16 by 8 Keyboard matrix I am working on a project, trying to construct an 80 button keypad. My problem is how to multiplex it so that i only feed the arduino with two sets of BCD or binary(whichever is easier) which are supposed to drive a 75 led display board simultaneously with a pair of 7 segments. The led display board is remote, which means i should drive the boards serially. The other 5 buttons remaining out of 80 are for other functions such as clear last number etc.
Please help!

Easiest would be to use 2 arduino's, which are connected in some way.
One of them should tell the other one what to do. I suggest you make the one reading the buttons the "master" and the other one it's "slave" device.

You could use 8 inputs, for each column and 10 outputs for each row.
Then you check all 8 inputs per column (pretty rapidly) and then you'll be able to read every button.

You could choose to either send changes or just every value to the slave device.

The slave device would have to do something similiar, but with 2 outputs, to address the right LED's/segments.

Alternatively you could use shift-registers.

There actually are a lot of tutorials on this to be found on the web.
You should check out "Arduino multiplexing" or "Arduino led cube" tutorials.


What device do I add in order to detect if my project is moved? I seem to be going round in circles trying to find the answer to this question, so thought I'd ask the good folk here.

I have an Arduino pro mini 3.3v based project, using lowpower libraries. It wakes up every h hours and takes a reading.  I would now like it to still wake up every h hours but in the meantime know whether the item (the board, or its container) has actually physically been moved - like binary, did it move or not at all?

I don't need constant monitoring of position. Once triggered I'd turn off the interrupt until the next wake up event.

In my mind I see the solution as being an interrupt attached to low power device which when moved slightly triggers the event to be recorded.

pseudo code would be:

if ((hour == h_hour) && movementDetectedSinceLastWakeup){
  doStuff();
} else {
  goBackToSleep(2hrs);
}

My question is, what kind of sensor should I consider for this job?

3.3v
lowpower
can trigger interrupt

EDIT "move" as in it vibrated past some set level.

There's two basic ways of detecting vibration - one which is quantifiable and one which isn't (much).

The simplest way is a sprint (possibly weighted) inside a metal tube. Vibration causes the spring to move and touch the tube - the resultant circuit is just the same as using a button. Sensitivity can't be controlled (other than maybe "how many times in a given period does the spring touch the tube"), but it's very very simple to use. They are often used in simple movement alarms (for things like bikes, etc).

The second method is to use an accelerometer. These are harder to work with but they do give you the actual amount of vibration at any given time. They are far more sensitive than a simple spring+tube, but since they are an active component they need to be constantly queried (often through I2C or an analog input). That makes them harder to use in a low-power scenario.

Some accelerometers are more intelligent and can be programmed to trigger an interrupt when vibration above a certain level is detected, though again that increases the complexity of working with them.

So in short: the lowest power option is the simple spring+tube sensor - it uses zero quiescent current. The best option is a programmable accelerometer that can trigger an interrupt to wake the main MCU. Which you choose depends on how sensitive you need the device to be...


Error to make a request using Arduino Uno and ESP8266 I'm using Arduino Uno and ESP8266 in a project.

I'm using AT Commands to connect to wi-fi and make a request. I'm using the monitor serial to test the code before compile it in arduino.

It is connecting to wi-fi and I can make a request to a server in my network but when i try to make a request to my web-service in cloud it doesn't work well.

The return is an HTML with an 404 page instead of what I am expecting:

Hello Versa

Here is my code:

AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=18
GET /webservice/

Can someone help me telling me what I am doing wrong?

After see the answer of Maximilian Gerhardt, I solved it writing the following sequence in the monitor serialize:

AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=70
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close
[Just press enter and send a new line]

A HTTP requests is comprised of more than just GET /webservice/. Take a look at what curl (console-line HTTP client) does.

C:\>curl -v "http://ternary.com.br/webservice/"
*   Trying 187.84.237.200...
* Connected to ternary.com.br (187.84.237.200) port 80 (#0)
> GET /webservice/ HTTP/1.1
> Host: ternary.com.br
> User-Agent: curl/7.46.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 11 May 2018 15:04:16 GMT
< Server: Apache
< X-Powered-By: PHP/5.6.30
< Vary: Accept-Encoding
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Expires: Wed, 11 Jan 1984 05:00:00 GMT
< X-UA-Compatible: IE=Edge,chrome=1
< Pragma: no-cache
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<

Hello Versa
* Connection #0 to host ternary.com.br left intact

You will have to at least transfer the minimal correct HTTP Headers of the form

GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close

To get an answer. Also mind the ending \r\n\r\n. Refer to this website for more headers.

When I only send GET /webservice/ I also get 404 page.

C:\>cat test
GET /webservice/

C:\>cat test | ncat ternary.com.br 80
[...]
        <title data-i18n="[html]404_page.title">404 ÔÇô P├ígina n├úo encontrada</title>


How can I seriously calibrate ADC voltage readings with Arduino Nano? I have been using Arduino Nano Analog input to measure voltages, in the range between 22-30 Volts.

I want to measure it down to a tenth of a volt.

Following the instructions found here:

Read Analog Voltage (www.arduino.cc)

Which basically states that all I need is this code:

int sensorValue = analogRead(A0);
float voltage= sensorValue * (5.0 / 1023.0);

5.0/1023 = 0.004888 volts per increment in analog readings.  Turning that around, voltage input divided by this value should give me the sensor value.
Clearly they are presuming an input of 0-5 Volts.

My voltage divider is 1 Mohm (R1) between the voltage input and A2, then 200K (R2) from A2 to ground

30 Volts measures as 4.2 Volts.  22 Volts measures as 3.1 Volts.

I think the range between 22 volts and 30 Volts doesn't present enough variation to the ADC - every single-digit change in the analogRead really make a big difference.

The result is that it is giving me some crazy readings.  It is definitely nonlinear, so I am having real trouble trying to get it to be accurate at both ends of my measurement range.  Each slight ADC increment makes too much of a difference in the measured voltage because I am not using the full 0-5V input range.

So I have been taking 10 readings in a row, at 500 ms intervals, then averaging.

And yet it is not working well enough.

(The biggest problem was the reference voltage and resolution were assumed to be 5/1024 which is completely incorrect.  Unless, as someone pointed out, I fed the Nanos directly at the 5V pin - which is still on the table - then it would be 5/1023)

I changed my resistor network to be 147K/23.5K

(Parts list:  1x 100K, 3x 47K)

R1 = 47K / 47K = 23.5K

R2 = 100K + 47K = 147K

Also added a 100uF 50V electrolytic across the input from the battery bank I am monitoring.

I am feeding 5V to Vin.  And have figured out that the reference is measurable on the 5V pin, after the regulator, as 4.6V.

Knowing that

Resolution/Vref = ADC/Vin

I turned that around to be

Vin = ADC * (Vref/Resolution)

Or, Vin = A2 * (4.6/1023)

Using a laboratory power supply I was able to confirm that with those settings 22 Volts came in at 3 Volts, and 29.98 came in right at 4 Volts.

So

Vbat = A2 * (4.6/1023) / (R2/(R1+R2))

Vbat = A2 * (4.6/1023.0)/(147000/170500)

It is now operating reasonably well.

(Yellow means the inverter is on)

--UPDATE--
  Changed resistors to 100K/20K for the divider and brought power to the 5V pin, bypassing the regulator for a reference.  It measures at 5.02 and is stable.

Results:

Charge controller meter says I am at 24.5 Volts.

Program says 24.64  (in the serial monitor).

--ADDENDUM:  I want to pursue the Op-Amp setup.  But if 741 won't work will need a suggestion.

Similarly, I went to 147K/47K for the 11-15 Volt circuit, and moved a higher-quality P/S over to the 5V pin, where it measures 5.03V; the results are better there, too. Just very slightly high.

So anyway, I'll put this to rest until I can figure out an op-amp circuit.

Thank you all for your help

Rather than mapping to a range of 0 to 4.4 V, map to the range 0 to 1.1 V and use analogReference(INTERNAL) to select the internal band-gap 1.1 V reference source.  This reference voltage might vary a small amount as Vcc varies, but the variation is likely to be just a few millivolts.

To get your input voltage into the range  0 to 1.1 V, use a voltage divider and a voltage subtractor.  The voltage divider ratio should map the 8-volt range of 22 to 30 V to a 1.1 V range, ie, should have a ratio of 8:1.1, and should map 30 V to 4.125 V and 22 V to 3.025 V.

If you use a Unity Gain Differential Amplifier as described at electronics-tutorials.ws, the divider can use large resistors, ie, need not provide the under-10 KΩ resistance needed for ADC input; instead, the UGDA's low output impedance will meet that requirement when used as ADC input.  For example, you could have 1 MΩ in series with 160 KΩ for the main divider.

Feed that divided voltage into V1 in the diagram below.  Use a pot or another voltage divider to create a 3.025 V reference to feed into V2, perhaps based on the board's 3.3 V regulator output.

Note, use R1 = R2 = R3 = R4, with all of them some value like 10 KΩ or 20 KΩ.


How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data? I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.

This is my code..

    #include <IRremote.h>
    #include <EEPROM.h>
    int EEPROMaddress = 0;
    int EEPROMaddress1 = 1;
    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
    int RECV_PIN = 11;
    int led = 10;//1FE50AF
    int led1 = 9;//1FED827
    boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
    boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
    boolean state;
    boolean state1;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      irrecv.enableIRIn();
    }
    void loop() {
      if (irrecv.decode(&results))
      {
        Serial.println(results.value, HEX);
        switch(results.value)
        {
           case 0x1FE50AF:
           if (previousState == LOW)
           {state = HIGH;
            digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led,state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);}
           else
           {state=LOW;
           digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led, state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);
           }
           break;
            case 0x1FED827:
           if (previousState1 == LOW)
           {state1=HIGH;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1, state1);
           delay(50);}
           else
           {state1=LOW;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1,state1);
           delay(50);}
           break;
}
        irrecv.resume();
      }
}

Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.

Write a bit to EEPROM:

byte EEPROMbyte = EEPROM.read(EEPROMaddress);
bitWrite(EEPROMbyte, pinBit, pinState);
EEPROM.update(EEPROMaddress, EEPROMbyte);

Read a bit from EEPROM:

boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.

I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.


Open the Uart0 Serial Port on Intel Edison I'll preface this buy saying I am very new to working with Arduino boards or hardware in general.
I am attempting to follow a tutorial on instructables

http://www.instructables.com/id/PCBot/step4/Printer-test/

I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:

  Open the UART0 serial port
  by default the GPIO's of the edison are disables.

  You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.

  To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:

  import mraa

  x=mraa.Uart(0)

I opened a python shell and entered the import mraa lines and tried to run the printertest.py

I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with opkg install python-serial but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph.

*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0' which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano

I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of /dev/ttyAMA0 to /dev/ttyMFD1 as shown by http://iotdk.intel.com/docs/master/mraa/edison.html . This was the final step after I had installed pyserial.


How to make Serial.read() return an integer instead of an ascii value? I want Serial.read() to return an integer instead of an ASCII value. For example, in the below code if I input 2, I want the output as 2 instead of 50
void setup(){
    Serial.begin();
}

void loop(){
    if(Serial.available()){
    int t = Serial.read();
    Serial.println(t);
}

If it's a single digit:
if (t >= '0' && t <= '9') {
    int numeric_value = t - '0';
} else {
    // Handle the input error.
}


can I check if why my motor isn't working? I am currently using the arduino Uno connected with L298N(green pcb) connected to a dc motor rated 12V. I provided dedicated 12v power supply to the dc motor and the arduino board's power is supplied by usb connected to my pc. I connected Pin 9 of arduino uno to 'ENA' on L298N , Pin 7 & 8 (UNO) to 'INA' & 'INB' of L298N. Connected '-' polarity of Motor power supply to GND of L298N, while also connecting the 'GND' of L298N to the GND of Arduino UNO. Last but not least, connecting the 'OUT B'to the dc motor. This is the picture of how L298N(green) look like https://sea.banggood.com/Green-Board-L298N-DC-Motor-Driver-Board-Stepper-Motor-p-974549.html?cur_warehouse=CN

Can i check why my motor isn't running? Thanks in advance.

char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
  pinMode(enB, OUTPUT);
   pinMode(InC, OUTPUT);
  pinMode(InD, OUTPUT);

}

void loop()
{Serial.println("Entered loop, should start moving now !");
  digitalWrite(InC, HIGH);
  digitalWrite(InD, LOW);
   digitalWrite(enB, HIGH);
   analogWrite(enB, 255);
 }

Well, your wiring is OK, but I think the

'digitalWrite(enB, HIGH);

in the loop() code is causing your problem.  You don't want to try to use the same pin for both digital and analog functions.

I wired up a Uno here with your setup and a L298N, and got a motor to run fine with the following sketch that doesn't use the loop() at all - it does everything in setup().

char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
    pinMode(enB, OUTPUT);
    pinMode(InC, OUTPUT);
    pinMode(InD, OUTPUT);

    Serial.println("motor should start moving now !");
    digitalWrite(InC, HIGH);
    digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);

    for (size_t i = 0; i < 10; i++)
    {
        analogWrite(enB, 20*i);
        Serial.print("motor speed = "); Serial.println(20 * i);
        delay(2000);
    }

    Serial.println("quitting!");
    while (true)
    {

    }

}

void loop()
{
    //Serial.println("Entered loop, should start moving now !");
    //digitalWrite(InC, HIGH);
    //digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);
    //analogWrite(enB, 255);
}

If you can't get your motor working with the above program, then you most likely have a connection or power supply or component problem that you'll need to troubleshoot.

Hope this helps,

Frank


Servos and Random Number I am new to coding and this website so I apologize if I make any mistakes. I am trying to get servos to move when a random number is generated. Like if I roll a 2 I want servos 1, 2 and 3 to open and then if I roll a 3 after I want servos 4, 5 and 6 to open. I am able to hold the previous values in the code now but can't get the servos to go with it. Any help is great! Thanks!

#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo     position
int x = 0;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious = 0;
int oldNumber;

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

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  Serial.print("Random Number ");
 Serial.println(randomNumber);
 if( xPrevious == 0) {
   randomNumber = randomNumber + 1;
 }

  // Only want it to do this on the first roll.
     xPrevious = randomNumber + xPrevious;
     Serial.print("xPrevious ");
     Serial.println(xPrevious);
    oldNumber = xPrevious;

 for (x = randomNumber; x <= xPrevious; x += 1) {
  myservo.attach(x);
  Serial.println(x);

  for (pos = 0; pos <= 180; pos += 1) { // goes     from 0 degrees to 180     degrees
 //in steps of 1 degree
    myservo.write(pos);              // tell servo to go   to position in variable 'pos'
    delay(15);                       // waits 15ms for the     servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes  from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go    to position in variable 'pos'
    delay(15);                       // waits 15ms for the  servo to reach the position
  }

 }
 }
 }

You planning to use multiple servo, but only declare one.
I still don't get about the pattern, but maybe this will give some image:

Servo myservo[5]; // assuming you have 5-servo
                  // servo[0]--> pin 0
                  // servo[1]--> pin 1
                  // servo[2]--> pin 2
                  // servo[3]--> pin 3
                  // servo[4]--> pin 4
pos = 0;

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  pos+=randomNumber;
  Serial.print("Random Number ");
  Serial.println(randomNumber);
  Serial.print("Current pos ");
  Serial.println(pos);

 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].attach(x+pos);
  Serial.print("attach servo-");
  Serial.println(x+pos); }

//open (move from 0-180 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(180);
 }
 delay(2000);

//close (move from 180-0 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(0);
 }
 delay(2000);

//detach servo
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].detach();
 }
 delay(2000);
}
}


`.readFileCounts()` not working on DFPlayer mini module I just played around using a MP3-TF-16P module, aka DFPlayer mini. The library and the examples I used as a basis can be found here.

My current setup contains a button (NC, normally closed), which is connected to Pin D2 and has an interrupted attached to it. The button input is debounced by using a time difference inside the ISR. The code (based on getStarted example) can be found below.

Using the button to play the next song works as expected. However, when trying to get the total number of tracks located on the SD card by calling Serial.println(player.readFileCounts()) as shown in the FullFunction example the board does neither print anything nor respond to any further commands. Even using the FullFunction example does not print anything.

Could someone please double-check this behaviour? Is this a module-related ore a library-related problem, since I am using a MP3-FT-16P module which might be a cheap clone of the original DFPlayer mini module? Does this work with other MP3-FT-16P modules out there meaning that mine is faulty?

#include "stdint.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

#define interruptPin 2
#define softSerialRx 10
#define softSerialTx 11
#define debounceDelayMillis 1000

volatile uint32_t lastInterruptTime = 0;
volatile bool interruptOccured = false;

SoftwareSerial softSerial(softSerialRx, softSerialTx);
DFRobotDFPlayerMini player;

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

  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), interruptHandler, FALLING);

  Serial.println(F("Initing player ..."));
  // `player.begin(stream)` returns true when module is initialized
  if (!player.begin(softSerial)) {
    Serial.println(F("... failed"));
    while(true) {
      // never leave this loop since initialization went wrong
    }
  }
  Serial.println(F("... ready."));

  // volume: 0 ... 30
  player.volume(30);

  // when using `player.readFileCounts()` player module does not respond to further commands
  // Serial.println(player.readFileCounts());
}

void loop() {
  // read status messages from DFPlayerMini on its software serial port when available
  if (player.available()) {
    printPlayerStatus(player.readType(), player.read());
  }

  if (interruptOccured) {
    Serial.println("Button pressed");
    player.next();
    interruptOccured = false;
  }
}

void interruptHandler() {
 uint32_t interruptTime = millis();
 if (interruptTime - lastInterruptTime > debounceDelayMillis) {
   interruptOccured = true;
 }
 lastInterruptTime = interruptTime;
}

void printPlayerStatus(uint8_t type, uint16_t value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number: "));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError: "));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

These DFPlayer modules are more difficult to drive than the examples suggest. Whenever you send a command to the DFPlayer (such as player.setVolume(30)) the module will return some sort of acknowledgement or a status command.  You need to be calling the player.available() method and then player.readType() and player.read() continually in loop() to keep the SoftwareSerial buffer free before you try sending commands. So calling player.setVolume(30) and then player.readFileCounts() in setup() may be overfilling the buffer before you start clearing it and the buffer will contain unread messages that are not the expected file count reply thus confusing the library. The other thing to consider is that it takes the module a second or two to initialise the SD card after .begin() and you really need to wait for the DFPlayerCardOnline status message to come in before you can ask for file counts.

I've written a more comprehensive library to drive these but it's not mature enough to share yet.


what is fastest allowable serial baudrate? what is the fastest serial read the Mega can do?
begin.Serial1(1024000) is accepted for compiling, but reading jibberish

any suggestions on a faster device?

The Arduino Mega 2560 runs at 16 MHz. There are online calculators making this easy, as the calculation is not a straight and simple formula.

http://wormfood.net/avrbaudcalc.php

which shows using 16 MHz

Baud Rate   UBRR(dec)   UBRR(hex)   % of error
300 3332    0x0D04  0.0
600 1666    0x0682  0.0
1200    832 0x0340  0.0
2400    416 0x01A0  0.0
4800    207 0x00CF  0.2
9600    103 0x0067  0.2
14400   68  0x0044  0.6
19200   51  0x0033  0.2
28800   34  0x0022  0.8
38400   25  0x0019  0.2
57600   16  0x0010  2.1 - Barely OK
76800   12  0x000C  0.2 - GOOD
115200  8   0x0008  3.7 - BAD
230400  3   0x0003  7.8 - BAD
250000  3   0x0003  0.0

Where it is noticeable that the Mega's Arduino boot loader uses

mega.menu.cpu.atmega2560.upload.speed=115200

which is above the acceptable 1% error rate.

While it is possible to support different baud rates than stated above, it is not advisable, as the above values are the standard values. Values in between are very atypical and likely not trustworthy on the corresponding other side of the connection.

As I see your above example is 1024000, it is also worth noting that HardwareSerial.cpp implements a method to convert the requested baud rate to configuration of the USART, and I would not necessarily trust it for non-standard baud rates, especially on older version of the Arduino IDE. You may want to try the latest 1.5.8+ and verify the rate.


Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield I need to control a brushless motor that came connected to this ESC using the Arduino CNC Shield V3.00 and Grbl 0.9j.

I connected the ESC's black wire to a GND from the shield and the ESC's white wire to the shield's Z+ limit (end stop).

I then tested by connecting everything but leaving the ESC unpowered, sending several M3 S*commands, where 0 <= * <= 1000, then powering the ESC, but nothing happened.

After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.

The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.

I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

Import grbl's library in Arduino IDE.
Find out where the library got installed and edit grbl/spindle_control.c, lines 89 and 94.
Change 0x02 to 0x05. Save and close the file.
Compile and download the library to Arduino Uno.
Connect everything but leave the ESC unpowered.
Send M3 S0 (that's a zero).
Power the ESC.
You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
Send S600. It should start spinning. If it doesn't, first send lower values from 0 to 600.
Send S500 to stop.


What is the proper way to implement PID? I'm having some trouble conceptualizing how to go about implementing PID into my drone. There are a few ways I'm thinking about implementing the pipeline:

Having one PID Object for each of the six motors.
Having one PID Object for each axis.

How I would implement PIDs on a per-motor basis?

How I would implement PIDs on a per-axis basis?

I'm guessing that the second one will be the best course of action, as it can all be put into its own loop, where the PID data will be available on-demand, as opposed to calculating it on the spot. It is object-oriented, and runs in the background.

The first one has its appeals, too. It eliminates some of the calculations needed in order to find the actual value. It is procedural, and very straightforward and performs on the spot.

What do you guys think?

Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.

For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.

To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.

I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.

I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.

Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).


Error using SD card module: no matching function for call to This code is just a test code to write a file to an SD card using an SD card module. When I run the code, I get this error message and I'm not sure what to do to fix the code: no matching function for call to'SDLib::SDClass::exists(SDLib::File&)'.

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

int cs = 10;

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {

  }
  Serial.println("Initializing SD card...");
  Serial.println();

  pinMode(cs, OUTPUT);
  pinMode(SS, OUTPUT);
  if (!SD.begin(cs)) {
    Serial.println("SD did not initiliaze");
    while (1) ;
  }
  Serial.println("SD initialized.");

  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);

     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
  else{
    myTest = SD.open(myTestName, FILE_WRITE);
    myTest.println("Another Line of Data");
    myTest.flush();

  }

  Serial.println("Done Writing");

}

void loop()
{

}

The function is defined as

// Methods to determine if the requested file path exists.
boolean exists(char *filepath);

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90

You call it with a File object, not the filename. You probably mixed up the variable names:

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  //[...]
  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);
     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
//..

Just exchange myTest for myTestName in the SD.exists() call.