Arduino MySQL Connector Issues with Select only first question i am doing so hope this is the right place.

I have an issue with an Arduino Uno and an Arduino ESP8266WiFi Shiald by WangTongze using this tutorial (https://www.instructables.com/id/ESP8266-ESP-12E-UART-Wireless-WIFI-Shield-TTL-Conv/) I have been able to connect to the my Wifi and host a small webserver.

Then with the Examples of the MySql Connector Library I have been able to do a simple Insert to a MySQL Database on a NAS Server. However, I want to be able to select a value from my DB and print it on the screen for some reason the Cursor always returns a null. I have been able to select from my PC using the same user. and created the user francis@% so that the host isn't an issue. Please note that this same code with a few tweaks worked to insert a record to the same table. Is there anything I am missing? Below is the code:

//#include <WiFi.h> // Use this for WiFi instead of Ethernet.h
#include <WiFiEsp.h> //use for ESP8266
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

// Emulate Serial1 on pins 2/3 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192,168,x,x); // IP of the MySQL server here
char user[] = "francis";
char password[] = "xxxxxx";

// WiFi card example
char ssid[] = "PintoLoco"; // your network SSID (name)
char pass[] = "xxxxxxxx"; // your network password

//WiFiClient client; // Use this for WiFi instead of EthernetClient
WiFiEspClient client; //Use this for ESP8266
MySQL_Connection conn((Client *)&client);
MySQL_Cursor cur = MySQL_Cursor(&conn);

char query[] = "SELECT Value FROM Peceras.Parameters ";

void setup() {

  Serial.println("Starting....");
  Serial.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial);
  Serial.println("Connecting to WiFi");

  // Begin WiFi section
  int status = WiFi.begin(ssid, pass);
  while(status != WL_CONNECTED){
      status = WiFi.begin(ssid, pass);
    }
  // print out info about the connection:

  Serial.println("Connected to network");
  IPAddress ip = WiFi.localIP();
  Serial.print("My IP address is: ");
  Serial.println(ip);

  // End WiFi section

  Serial.println("Connecting...");
  if (conn.connect(server_addr,3306,user,password)) {
  delay(1000);
  }
  else
  Serial.println("Connection failed.");
}
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
void loop() {
  row_values *row = NULL;
  long head_count = NULL;
column_names *cols = cur_mem->get_columns();
cur_mem->execute(query);
  // Execute the query
  do {
    row = cur_mem->get_next_row();
    if (row != NULL) {
      for (int f = 0; f < cols->num_fields; f++) {
        head_count = atoi(row->values[f]);
          Serial.print("Ingestelde Temperatuur:  ");
          Serial.println(head_count);
        if (f < cols->num_fields-1) {
          Serial.println(',');

        }
      }
      Serial.println();
    }
  } while (row != NULL);
  // Deleting the cursor also frees up memory used
  delete cur_mem;
  delay(2000);
}

I have no access to a compiler, so there might be errors.

#include <WiFiEsp.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192,168,x,x);
char user[] = "francis";
char password[] = "xxxxxx";

char ssid[] = "PintoLoco";
char pass[] = "xxxxxxxx";

WiFiEspClient client;
MySQL_Connection conn( (Client *) &client );
MySQL_Cursor *cur_mem = null;

// PPK: some database systems are case sensitive
// so Peceras.Parameters is not the same as peceras.parameters
// check if the tables and fields are named correctly.
char query[] = "SELECT Value FROM Peceras.Parameters";

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

  Serial.println( "Connecting to WiFi" );
  WiFi.init( &Serial1 );
  int status = WiFi.begin( ssid, pass );
  while( status != WL_CONNECTED )
  {
    status = WiFi.begin(ssid, pass);
  }

  Serial.println( "Connected to network" );
  IPAddress ip = WiFi.localIP();
  Serial.print( "My IP address is: " );
  Serial.println( ip );

  Serial.println( "Connecting DB ..." );
  if ( conn.connect( server_addr, 3306, user, password ) )
  {
    Serial.println( "DB connected." );
    cur_mem = new MySQL_Cursor( &conn );
    row_values *row = NULL;
    long head_count = NULL;
    column_names *cols = cur_mem->get_columns();

    cur_mem->execute(query);

    do
    {
      row = cur_mem->get_next_row();
      if ( row != NULL )
      {
        for ( int f = 0; f < cols->num_fields; f++ )
        {
          head_count = atoi( row->values[f] );
          Serial.print( "Ingestelde Temperatuur:  ");
          Serial.println( head_count );
          if ( f < cols->num_fields - 1 )
          {
            Serial.println(',');
          }
        }
        Serial.println();
      }
    } while (row != NULL);

    // Deleting the cursor also frees up memory used
    // PPK: I'm not sure if this is a good idea, I don't know
    delete cur_mem;
  }
  else
  {
    Serial.println( "DB Connection failed." );
  }
}

void loop()
{
  // PPK: I would recommend to do the select in the setup section
  // It looks like you want to run it just once
}

Edit

Please note, that this code only works if you connect the software serial pins D2, D3 to the respective RX and TX pins on the Shield. You have to bend the pins (P0-P3) of the shield to disconnect them from the Arduino. Then you have to connect D2 and D3 to P0 and P1. This is described in step 1 of the instructables you linked to in the question. See the picture at the end of Step 1. https://www.instructables.com/id/ESP8266-ESP-12E-UART-Wireless-WIFI-Shield-TTL-Conv/


What's the difference between DDRB and pinMode? It's my understanding that the following lines are equivalent. They seem to be interchangeable in my sketch:

DDRB = 1<<DDB0;

and

pinMode(0, OUTPUT);

Is the first form (DDRB...) setting a micro-controller address directly? Is that assembler?

And is the second form (pinMode) using an included library? Maybe the avr/io.h library?

On a Digispark ATTiny85.

DDRB

is a register. Exactly: Port B Data Direction Register. See datasheet for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

  DDB0

value was used.
Using this way of setting direction of a pin is much faster than  pinMode(0, OUTPUT);
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.


Lighting 5 leds...the last one lit is always dim I have a simple project with a close deadline.

I am trying to light up 5 LEDs as part of the project. The first 4 light up in sequence fine, and if I light up just the last one it lights up fine, but if all 5 are lit at once the very last LED is very dim. I swapped out cables, the pin on the Arduino, resistor, LED.

What would explain that? Input amperage? Too strong a resistor?

I have a 330 ohm resistor in between each LED and ground. I am using one of the neat resistors from SparkFun that packages up the 5 330 ohm resistors together, with a common ground wire. I bought two and tried swapping it out with no change.

http://imgur.com/fE9t5ZI

Here is my code:

/* Blink without Delay
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

const int startButtonPin = 6;
const int reedSwitchPin = 7;
const int ledPins[] = {8,9,10,11,13};
const int numLeds = 5;
const long interval = 1000;           // interval at which to blink (milliseconds)
const int revolutionsPerStage = 15;

int debounceDelay = 500; // for switches--interval to ignore short button presses/reed switch open/close
long lastDebounce = 0;
int buttonState = LOW;
int mapStage = 0;

unsigned long previousMillis = 0;        // will store last time LED was updated

void setup() {
  // set pin modes
  for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }
  pinMode(startButtonPin, INPUT);
  pinMode(reedSwitchPin,INPUT);

  digitalWrite(reedSwitchPin,HIGH); // activate the pull-up resistor
}

// Main program loop
void loop()
{
  buttonState = digitalRead(startButtonPin);
  //digitalWrite(8,HIGH);

  // wait for button press to begin program proper. we won't get back to this state except on first boot or if program finishes
  if (buttonState == HIGH) {
      digitalWrite(8,HIGH);
      chasingLEDs();
      //trackProgress();
  }
}

void trackProgress() {
  int blinkState = LOW;
  unsigned long currentMillis = millis();
  unsigned int numRevolutions = 0;

  do {
    digitalWrite(ledPins[mapStage], HIGH);

    // blink the current goal LED at constant interval specified earlier
    if(currentMillis - previousMillis >= interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
      blinkState = !blinkState;
      digitalWrite(ledPins[mapStage], blinkState);
    }
  } while (mapStage < numLeds);
}

// perform a simple welcome sequence to indicate we are ready to start pedalling
void chasingLEDs() {
   // turn LEDs on in sequence, then back off
   for (int i = 0; i < numLeds; i++){
     digitalWrite(ledPins[i], HIGH);
     delay(333);
   }

   for (int j = numLeds; j > 0; j--) {
     digitalWrite(ledPins[j], LOW);
     delay(333);
   }

   // flash the LEDs twice
   for (int k = 0; k < 2; k++) {
     for (int l = 0; l < numLeds; l++) {
         digitalWrite(ledPins[l], HIGH);
     }
     delay(500);
     for (int m = 0; m < numLeds; m++) {
         digitalWrite(ledPins[m], LOW);
     }
   }
}

I found the problem, it was a bug in my code. I had found code to read the array size online but it was off by 1.

Instead of:

for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }

When I changed it to thisPin < numLeds, it worked correctly. The last pin was simply set to be an input pin instead of an output pin.


Minimum current or power for Arduino Mega I wanted to use the cigarette lighter receptacle of a car as the power supply for the Arduino Mega. From 12 V, I will convert it to a 7 V supply, but my problem is, what must be the minimum current or electrical power to be fed into the Arduino Mega?

And are there any things I have to do to the Arduino Mega 2560 for it to function well in supplying it a 7 volts supply from a car?

The Arduino's voltage regulator is rated for a suggested input range of 7 to 12 volts. Automobile power will range from slightly below 12 volts to over 13 volts, so stepping it down to 7 volts is a good idea.

Looking at the data sheet it doesn't say how much current it draws. Since it uses a linear power supply it will likely draw the same amount of current regardless of the input voltage, and simply waste the power from a higher input voltage as heat.

The power from a car cigarette lighter should have plenty of current, so your proposed setup should work just fine. Is your 7 volt supply regulated?

Note that you could also use a "buck" style switching power supply to feed 5 volts directly into the 5V line. There are several buck style power supplies on the market for less than $10 US that will provide up to 3A of regulated 5 volts.


Slow refresh rate on I2C OLED screen I'm trying to create a small handheld console with 6 buttons and an I2C 0.96" OLED display:
https://imgur.com/a/AKiRMWN

The directional buttons use the analog pin and different resistors technique to save space while the two remaining buttons use a digital pin each.
However, despite using the same libraries as other projects, the sketch seems to run very slowly, resulting in a lowered screen refresh rate.

Here is the code:

#define wid 64  // Defines half of the width of the screen for graphic reference
#define hei 32

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display;  // Create display

int av;
const float sp = 3;
float pos[2]={0,0};  // Cursor position

void setup() {
   delay(100);  // Gives the screen time to setup
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Initialize display with the I2C address of 0x3C
   display.clearDisplay();
   display.setTextColor(WHITE);
   display.display();   // Clears the screen of any remaining images
  }

void loop() {
  av=analogRead(A0);  // Reads the directional input
  av=inputRefine(av); // Assigns it to a direction
  switch (av)         // Changes the cursor position accordingly
  {
    case 1:
    pos[1]-=sp;
    break;

    case 2:
    pos[0] += sp;
    break;

    case 3:
    pos[1] += sp;
    break;

    case 4:
    pos[0] -= sp;
    break;
  }
  display.clearDisplay();

  display.setCursor(5,5);
  display.print(millis());  // Prints the system time on the corner of the screen

  display.drawCircle(wid + pos[0], hei + pos[1], 5, WHITE);  // Draws a circle on the cursor position
  display.display();
  }

int inputRefine(int av)
{
  int a=0;
  if (av>500&&av<600) a=2;
  else if(av>1000) a=3;
  else if(av>920&&av<950) a=4;
  else if(av>680&&av<720) a=1;

  return a;
}

What is slowing the execution down?

EDIT: Even commenting out any unnecessary line doesn't remove the lag
EDIT 2: The problem might reside in the screen itself. Unfortunately, I don't have a backup one. I'll order one as soon as possible and test this theory.

Solved by updating the Adafruit sdd1306 library and the Adafruit GFX library

EDIT: Why am I being downvoted?


How do I control a conveyor to start and stop in same location using optical rotary encoder I am a complete novice at arduino. I just want to know if this is possible before I start investing in components. I need to start and stop a chain drive conveyor {can't slip} powered by a 12 volt motor in the exact same place each time I manually start the cycle. I want it to stop automatically. The controller would have to power a relay to power the motor due to high amp draw of motor. This is on a piece of equipment without access to any other power supply but a 12 volt battery. I am looking at an optical rotary encoder to count the revolutions of the shaft. I would count the revolutions the shaft makes between my start and stop point and I assume enter that in the program. Is this possible?
Thanks

Although your solution would work, it seems open to problems such as missed clicks, starting at a different place etc.
A better, more robust and error free solution might be to use a hall sensor.
Essentially what a hall sensor does is close a switch when a megnetic force is applied. So all you have to do is add a magnet to your conveyor/chain. This way, you can easily control where you want it to stop just by moving the magnet, and it doesn't matter what the starting position is because it will always stop as soon as the megnet reaches the sensor.


What's the 2nd ICSP header for in Arduino Uno R3? Looking at my Arduino Uno R3 board and its reference design schematic I noticed that there's a second ICSP 6-pin header. In the schematic, the connector I'm referring to is named ICSP1.

What's that for?
What useful things can an average Arduino user like me do with it?

The relevant part of the schematic is below (marked in red).

It's for the other MCU on the board.

The main MCU on the Uno is labelled "ZIC1". This is the one that is programmed when you press "Upload" in the IDE. But unlike other Arduinos that use a FTDI chip to connect to the serial port on the main MCU, the Uno uses another MCU instead, labelled "U3" on the left. This MCU runs a small bit of code that acts as a serial port via USB and passes through the bytes to its USART1. This then connects to the USART on the main MCU, where the bootloader on that chip accepts the bytes coming through and writes to flash and EEPROM on the main MCU.

You can use this additional MCU as you would any other, but the only I/O it has available are the USB connection, the SPI connection via its ICSP header, the UART1 connection to both the main MCU and pins 0 and 1, and two LEDs on PD4 and PD5.


Arduino Micro Interrupt I have built a custom Arduino Micro PCB, but I have made a mistake, I accidentally attached an interrupt pin for a Gyro sensor to pin 12 of the Micro, not realizing it wasn't an external interrupt pin.

I tried using the interrupt pin change command found on the Arduino website, but I am having some trouble getting it working. If there is a way to make pin 12 on the Arduino Micro an Interrupt pin, how would I go about doing that in the simplest way.

If there is a way to make pin 12 on the Arduino Micro an Interrupt pin

you should take a look at the device datasheet and see what other functionalities pin 12 has.

if it is a pcint pin, you are golden;
if it is a timer input pin or an input capture pin, they can be programmed to act like an interrupt pin as well.

all begins with reading the datasheet.


DAC to play audio samples I have a buffer which contains 16000 PCM samples of 8Khz 8-bit mono. I am trying to play it using 12 bit MCP4725 DAC. I have tried using micros() to control the write interval for the DAC. Here's my code:

uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
long previousMicros = 0; // Sorry for missing this out!!

void setup() {

Serial.begin(115200);
Wire.begin(D2, D1);
delay(100); // delay 100 ms
Serial.flush();
delay(1000);

}

void value_write(uint16_t temp){

  Wire.beginTransmission(0x62);
  Wire.write(64);
  Wire.write(temp >> 4);        // the 8 most significant bits...
  Wire.write((temp & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();

}

void loop() {

  unsigned long currentMicros = micros();

// 125 uS sampling for 8KHz signal
if(currentMicros - previousMicros > 125) {
  Serial.print("Index: ");
  Serial.println(indx);
  uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

  value_write(temp);
}

}

The write should logically be completed within 2 seconds but takes way more time. Any help regarding successfully writing the PCM values to the DAC at 8000Hz is greatly appreciated.

One sample takes 38 I2C clock cycles to write. That's:

1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second absolute maximum.

You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second absolute maximum.  That would just about be do-able.

I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.

There's also the matter of the map() function which is just nasty in this situation. You can just bit-shift.

So besides just removing the Serial commands (which will slow things down massively) you should also:

Change the I2C clock to at least 400kHz
Change map() to soundData[indx++] << 4
Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.


Why does analog sensor "hum" when plugged into common ground? I have the ground for an SD card module, LED, and piezo sensor all plugged into the same ground rail. When doing this I get a low "hum" in the piezo readings where instead of reading ground voltage (0) when there's no vibration, it cycles between 4 and 6.

However, when I switch the piezo's ground onto ground rail connected to different ground pin on my Arduino, the hum goes away. If I keep the piezo on original ground and move the SD card module's ground, the hum comes back.

I'm very new to electronics, so I'm wonder what's going on?

EDIT: Here's a diagram of the circuit.

@Milliways remarked:

You have a ground loop. Without seeing the actual physical layout it is impossible to determine the cause. This is a common problem in audio circuits. Fixing this is as much an art as a science. The usual solutions involve a single earthing point, earthing at one end only or in extreme cases common mode rejection techniques.
Yours is an idealised diagram. These kind of problems are often related to the physical layout e.g. parallel wire runs. I agree that there appears to be nothing amiss. As I stated this is a black art. I would suggest separating the low level analog circuit from the rest of the wiring - i.e. DO NOT share any earth cabling with any other circuit. This appears to be what you have done when it worked. You should also minimise any other source of interference by using twisted wires to the sensor.


Do some variables not hold their value when a while loop is exited? Sorry if i'm asking too many silly questions but i'm really stumped on this one. I understand if I set a variable inside a loop that that variable won't be within scope from the outside of the loop.

Usually I find that variables declared outside of a loop will be accessible inside the loop, modifiable within the loop, and hold their value when exiting the loop but in this case that doesn't seem to be happening.

There are books on the sd card.
I'm saving the name of each book to an array from within a while loop.
When the while loop is exited the array is still null.

How can I solve this? thanks

int amtBooks = 5; //this gets set previously but im not going to show all the code

// create an array the size of the amount of books
  char* book[amtBooks] = { NULL };

// assign the name of each book to the array
  int bookNum = 0;
  while (true) {

    File entry =  root.openNextFile();
      if (! entry) {
        break; // no more files
      }

    book[bookNum] = entry.name();

    Serial.println(book[bookNum]); // <--------PRINTS FINE HERE

    bookNum ++;

  }

  root.close(); // close the stream

Serial.println(book[0]); <---ONCE OUT OF THE WHILE LOOP NOTHING DISPLAYS?
Serial.println(book[1]);

variables declared outside of a loop will be accessible inside the
  loop, modifiable within the loop, and hold their value when exiting
  the loop

This is correct.

  in this case that doesn't seem to be happening.

It is happening. The reason it looks like it doesn't is that
book[bookNum] is a pointer: the address of some data in memory. You
can check that the pointer does hold its value by printing it:

Serial.println((uintptr_t) book[bookNum]);

However, the statement you used:

Serial.println(book[bookNum]);

has a different meaning. It doesn't print the value of the variable
(i.e. the pointer): it prints the characters that are stored at the
pointed-to address, up to and excluding the first NUL.

Your problem comes from the fact that when you declare

File entry =  root.openNextFile();

you have a variable that is local to the loop. Then, when calling the
method

entry.name()

you get a pointer to an array of characters that belongs to the entry
object. This pointer is only valid as long as the object is in scope. As
soon as it gets out of scope (at the end of each loop iteration), the
entry object is destroyed and all memory belonging to it is released.
At this point the pointer you saved is a “dangling” pointer: it points
to an area of memory that has already been deallocated.

The proper fix is to allocate yourself the memory you need to hold the
character arrays, as in:

for (int bookNum = 0; bookNum < amtBooks; bookNum++) {
    File entry = root.openNextFile();
    if (!entry) break;
    const char *name = entry.name();
    book[bookNum] = (char *) malloc(strlen(name) + 1);
    strcpy(book[bookNum], name);
    Serial.println(book[bookNum]);
}

If you know in advance the maximum length of a book name, you could
follow the advice of Jot and Juraj and statically allocate the maximum
space you may need. That would be safer in terms of memory management.


Don't pee there! Device I want to make a device with a sensor I can attach to the places my dog likes to mark. When sensor becomes wet I want a buzzer to make a loud noise to scare the animal and notify me I need to encourage the dog to go outside. Any suggestions on what sensor to use.

You probably will want a moisture sensor like this one (there are many variations of this).

This will return one signal when dry, and another when wet.

You will need a Buzzer to make a sound as well (Or a piezo speaker if you feel like getting more advanced) in order to make a sound.

Your sketch should have, in its loop, an if statement checking if the moisture sensor has returned the wet signal (The signal will depend on the sensor you get) and, in the block that executes if there is a signal, a statement driving the buzzer and a delay before turning it off.

Bear in mind that you want to keep the Arduino itself away from the moisture sensor, as your Arduino probably won't survive the dog's doings.


Arduino constant vs Microchip PIC constant 2.2 THE BASICS OF C PROGRAMMING LANGUAGE book is has like this,

CONSTANTS
A constant is a number or a character having fixed value that cannot be changed during program execution. Unlike variables, constants are stored in the flash program memory of the microcontroller for the purpose of saving valuable space of RAM. The compiler recognizes them by their name and prefix const.

And Arduino references has not said where is constant variables are stored either program memory or RAM.
My questions are, where is the saving location of Arduino constant variables?
Is it same to Microchip PIC?
Those two compilers are same or not in this case?

const means different things in different contexts as far as storage goes.

For a simple numeric value the compiler will generally replace the constant with the literal value. Any mathematics using purely constants or literals will be replaced at compile time with the result.

For instance, the code:

const int a = 3;
const int b = 4;

void setup() {
    int c = a + b;
    Serial.println(c);
}

void loop() {

}

results in the AVR assembly:

be: 4a e0           ldi r20, 0x0A   ; 10
c0: 50 e0           ldi r21, 0x00   ; 0

c2: 67 e0           ldi r22, 0x07   ; 7
c4: 70 e0           ldi r23, 0x00   ; 0

c6: 80 e2           ldi r24, 0x20   ; 32
c8: 91 e0           ldi r25, 0x01   ; 1
ca: 0c 94 4a 01     jmp 0x294   ; 0x294 <_ZN5Print7printlnEii>

Registers r22 and r23 store the second integer parameter to the Serial.println() - the actual function call generated is _ZN5Print7printlnEii(&Serial, 7, 10).

So you see that the literal value 7 has replaced both the sum of the constants and the variable it is placed in.

However it is very different when more complex values are called for - such as arrays (either numeric or character arrays, AKA "C Strings"). In this case yes the values are stored in Flash, however the startup code crt0.o copies that data into SRAM so that the software can access it easily.

Generally flash is hard for software to read from. In some architectures it requires special instructions to be executed. In others it requires setting values in SFRs (Special Function Registers) and reading from other SFRs to get the data. In other words it's far harder than just reading from a memory location (a limitation of Harvard Architecture). So it's copied at boot time into SRAM so that it then becomes easy to access, as it's just now accessing a memory location.

However that then defeats one of the objectives of using a constant value - reduction of SRAM usage by placing the data in Flash. So the Arduino has a specific macro PROGRMEM, which sets attributes on the variable to say "Never copy this data to SRAM".

More specifically it's actually provided by the file avr/pgmspace.h in the avr-gcc compiler:

#define __ATTR_PROGMEM__ __attribute__((__progmem__))
#define PROGMEM __ATTR_PROGMEM__

But now of course you can't access the data using simple memory accesses, so there are special functions to allow it to be done. Some are alternate versions of standard C library routines, for instance strcmp_P() shadows strcmp() with the second parameter being a PROGMEM variable. Others are special functions for reading bytes or words from locations in flash, such as pgm_read_byte_near().

The Arduino API also provides an extra little trick, called the __FlashStringHelper which is an empty class used to identify strings held in flash for the purpose of function overloading so that the F() macro can be used to call the right variant of a function to use the flash reading functions instead of assuming the string is in SRAM.

So as you can see it's not as straight forward as "consts are in Flash, non-consts are in RAM".

Highlighting the differences between how the AVR accesses Flash and how the various PIC sub-families access Flash:

The AVR has one single instruction that can read Flash - LPM:

  There is only one instruction for the read access to the program storage space. It is defined for the pointer pair Z and it is named LPM (Load from Program Memory). The instruction copies the byte at program flash address Z to the register R0. As the program memory is organized word-wise (one instruction on one address consists of 16 bits or two bytes or one word) the least significant bit selects the lower or upper byte (0=lower byte, 1= upper byte). Because of this the original address
  must be multiplied by 2 and access is limited to 15-bit or 32 kB program memory. Like this:

LDI ZH,HIGH(2*address)
LDI ZL,LOW(2*address)
LPM

PIC10, PIC12 and PIC16 chips have no way of reading the flash.

Instead a "lookup table" of "RETLW" calls is used. For instance the string "Hello" would be stored in flash as:

RETLW 72    ; H
RETLW 101   ; e
RETLW 108   ; l
RETLW 108   ; l
RETLW 111   ; o
RETLW 0     ; NULL

RETLW returns from a CALL with the W register set to the literal value in the instruction. The entire command, that is both the RETLW and the 8 bit literal value, fits into a single 14-bit opcode.

PIC18 uses SFRs to access the Flash memory. Set the three registers TBLPTRU, TBLPTRH and TBLPTRL to the three bytes of the address in flash you want to read, a TBLRD instruction is issued through the EECON1 register, then you can read the byte from TABLAT.
PIC24 / dsPIC33 uses PSV - Program Space Visibility. This gives you the ability to map a 32kB chunk of the flash memory into the upper 32kB portion of the data space. This allows direct reading of data from within that 32kB chunk as if it were in RAM.
PIC32 uses a Von Neumann architecture which means that Flash and SRAM both share the same 32-bit address space. There is no difference reading from Flash or SRAM, so no special instructions are needed.

The only chip from those above where const really means const is the PIC32 where there is no need to copy from Flash to SRAM during startup since all the Flash memory can be directly accessed with normal MIPS LW and LB etc instructions.


Can Arduino libraries be compiled for ARM MCU's? I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs.

I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.

IridiumSBD Library

Gecko Zero MCU

Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be mbed Gecko development boards so the task is, to port the Rockblock-IridiumSBD Arduino library.

The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.

The Rockblock-IridiumSBD Arduino library won't compile 'out of the packet' on mbed.

However, the Rockblock-IridiumSBD Arduino library appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.

The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.


Uno R3 connected via Ethernet shield becomes unreachable after a few minutes I'm setting up an Elegoo Uno R3 with a Seeed 5200 ethernet shield to monitor water flow and temperature. It needs to run unattended for weeks at time (being called several times a day by a remote script).

I'm normally able to send and receive UDP packets for a few minutes when I've just reset/power-cycled the Arduino. After that, it stops responding to UDP messages. By adding some serial output I can see that it hangs unpredictably at different parts of loop(). Sometimes it seems that physically shifting the device will get it to wake up; or it will wake up on its own after a minute or two. Most of the time it works until it quits, then doesn't work until I reset it.

It does respond to ping while it's otherwise unresponsive.

Is there anything wrong with my code? This is my first Arduino project. Otherwise could it be a hardware problem? If I buy another, I'll buy a genuine Arduino. Is Seeed a reliable source for the ethernet shield?

(By the way--I think it's safe to disregard the PACKETLEN thing, which is a leftover artifact. In the end it's unnecessary to read the incoming message anyway, so the packetBuffer array is superfluous but doesn't seem to change anything one way or another.)

Thanks in advance. Best wishes,
Dan

#include <SPI.h>
#include <EthernetV2_0.h>

#define PACKETLEN 48

//Flow and temp globals
byte sensorInterrupt = 0;  // 0 = digital pin 2
byte flowPin       = 2;
byte tempPin = 0;

float calibrationFactor = 45; // we're going to measure for 10s intervals
float minFlow = 270;          // minimum 6 L/min, measured for 10 s
volatile byte pulseCount;
unsigned long startTime, timeDelta;

int tempReading;
float tempVoltage;
float temperature;

//Communication globals
IPAddress ip(xxx, xxx, xxx, xxx);
byte mac[] = {
  0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx
};
EthernetUDP Udp;

unsigned int localPort = xxxx;
char packetBuffer[PACKETLEN+1];  //buffer to hold incoming packet,

int packetSize;
byte flowOk, tempOk;
IPAddress remoteIP;
unsigned int remotePort;

void pulseCounter()
{
  pulseCount++;
}

void setup()
{

  //Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);

  pinMode(flowPin, INPUT);
  digitalWrite(flowPin, HIGH);

  // attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

void loop()
{

    delay(2000);

    if(packetSize = Udp.parsePacket())
    {
        remoteIP = Udp.remoteIP();
        remotePort = Udp.remotePort();

        //Measure the flow for 10 seconds
        flowOk = 0;
        pulseCount = 0;
        startTime = millis();
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
        while((timeDelta = millis() - startTime) <= 10000) ;
        detachInterrupt(sensorInterrupt);
        if (pulseCount >= minFlow)
            flowOk = 1;

        //Check the temperature
        tempOk = 0;
        tempReading = analogRead(tempPin);
        tempVoltage = tempReading * 5.0 / 1024.0;
        temperature = (tempVoltage - 0.5) * 100;
        if (temperature < 35.0)
            tempOk = 1;

        Udp.beginPacket(remoteIP, remotePort);
        if (flowOk && tempOk)
            Udp.write("Ok");
        else
            Udp.write("Not ok");
        Udp.endPacket();
    }

}

I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet_Shield_W5200 library:

#include <EthernetUdpV2_0.h>

#define SDCARD_CS 4

void setup():
    //...//
    pinMode(SDCARD_CS, OUTPUT);
    digitalWrite(SDCARD_CS, HIGH);


sensor for illegal parking detection I want to create a system that will detect illegal parking. I will place the sensor s to specific locations and when a car parks there the system will send a message to local authorities. My question is if a PIR is the suitable sensor for this project.

thanks in advance.

Don't get discouraged, there are many ways to do this, but I would rate a PIR as being one of the worst options because even a bird or a squirrel could set it off. Plus, once the car has stopped you can't detect it's presence anymore with a PIR sensor, it has to be moving. I would recommend either using something like a webcam and OpenCV for this or if you're set on using an Arduino and physical sensors, multiple laser or multiple ultrasonic sensors placed 5-10 feet apart so that they both have to trip at once for positive detection of a vehicle instead of something else. You're going to have to spend some time experimenting and tuning. If you want something very reliable and you own the place, you could always do what the public street works does and cut a loop into the pavement and install a large steel cable and use inductance, but that may be overkill. ;)

Some other ideas:

Paint a pattern on the ground using high contrast paint and detect
when the pattern is completely covered.  Maybe there is something you
can do with IR reflective paint and use a camera with no IR filter,
this way you could make a pattern invisible to the eyes.
A carbon monoxide detector - Detects dinosaur powered vehicles, but
is nice to the environmentally conscious.

About a decade ago now I created my own parking detection using a Raspberry Pi and a webcam and some Perl code I wrote (non-opencv). I basically just detected the shadow contrast under the car and it worked very well. Originally I tried detecting red colors in the tail lights, but this was more troublesome due to other lighting in the environment. Especially at night. In my case, I didn't have direct access to set up physical sensors and lasers would have been too intrusive, so visual analysis made sense.


Arduino connecting relay has no power output I'm a newbie trying to control something through a relay. I've tried two relays with two different setups.

Setup 1

External 12V dc input to the relay (SRD-12VDC-SL-C) and signal pin from arduino to the IN pin, GND of ext. power supply to the GND of the Arduino, NO and COM to the load object (i.e. an LED).

Setup 2

Similar to setup 1, but using SRD-05VDC-SL-C, 5V from Arduino (Vin from Arduino also tested).

Test program

Modified version of the 'blink' example.

Symptom

The load object has been verified to be working before the testing.
Both setup can be verify the input is working, the power led and switch led of the two relay module are lighted as expected, and I can hear the click sound while switching.
No output can be obtained, both from the load object and using a multimeter.

Update

Sorry, I'm supposed to upload a Fritzing schematic, but I can't find a proper relay as I'm using.

The DC+ (red) of the relay is connected to the external ATX 12V.
The DC- (black) of the relay is connected to the external ATX ground.
The IN (blue) of the relay is connected to the Arduino pin 8.
The external ATX ground (white) is connected to the Arduino ground.
The NO (red) of the relay is connected to the load object Vcc.
The COM (black) of the relay is connected to the load object ground.

Sketch

A simple modified version of Blink example is used for testing.

const int relaySignalPin = 8;

void setup() {
  // put your setup code here, to run once:
  pinMode(relaySignalPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(relaySignalPin, HIGH);
  delay(1000);
  digitalWrite(relaySignalPin, LOW);
  delay(1000);
}

Question

I have no idea on why there's no voltage can be obtain between NO and COM while the switch is on, what's wrong with my setup?

It sounds, from your textual description (please post a schematic or at least a photo of your setup) that you aren't providing power to the relay.

A relay doesn't have a power output.  It never provides power - it is merely a magnetically operated switch.  It is used to switch an external source of power on and off.

Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.

You can share the same power supply as you are feeding to the logic / drive side of the relays.


How to fix error line number offset in Sublime Text when compiling for Arduino When compiling for Arduino via the Stino plugin line numbers are not represented correctly in the output. For example, I have an error on line 117 however the output is: sketch_name.ino.cpp:136:1: error:

The #line preprocessor directive is used to tell GCC both what the next line should be numbered as and what filename should be reported, and the plugin is not generating them properly. This is therefore a Stino bug.


Arduino 3rd party cores I am trying to use Arduino platform.txt to run some extra pre-processing on my Arduino codes.

As far as I can understand the best way to do that is to use prebuild hooks as mentioned below
https://github.com/arduino/arduino/wiki/arduino-ide-1.5-3rd-party-hardware-specification

I am using the hooks as follows

recipe.hooks.sketch.prebuild.1.pattern=echo {source_file} sketch pret;
recipe.hooks.sketch.prebuild.2.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

This is the output I get for the hooks

echo "{source_file}" sketch pret;
{source_file} sketch pret;
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   {includes} "{source_file}" -o "{object_file}"
avr-gcc: error: {includes}: No such file or directory
avr-gcc: error: {source_file}: No such file or directory
avr-gcc: fatal error: no input files
compilation terminated.

The {source_file} variable is used in a compilation reciep as follows

recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

and the recipe runs as follows

"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino" "-I/Users/vinayakjoshi/Library/Arduino15/packages/boltiot/hardware/avr/1.0.0/variants/boltduino" "-I/Users/vinayakjoshi/Documents/Arduino/libraries/boltiot-arduino-helper-update-dev/src" "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/src" "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp" -o "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp.o"

As you can see, in a standard recipe, the variable {source_file} and other such definitions are correctly replaced. But in the hooks, this is not happening.

I want to know whether it is possible to get the value of the {source_file} variable to be used with the hooks, so that I can do some extra pre-processing with it. And if it is, how can I do it.

P.S. IDK what tag has to be used. I couldn't find platform.txt or 3rd party cores. I used the Arduino-IDE tag, as this question definitely asks how the IDE works.

It looks like those properties are only expanded in:

recipe.cpp.o.pattern
recipe.S.o.pattern
recipe.c.o.pattern
recipe.preproc.includes
recipe.preproc.macros

They are not expanded in any of the hook recipes.

This actually makes sense for {source_file} with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See related issue report.

If you're actually trying to use {source_file} to get the preprocessed sketch file, that's accessible from any recipe as {build.path}/sketch/{build.project_name}.cpp.

As for {includes}, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.


How to use the Osepp proximity module with arduino uno I have recently purchased an Osepp proximity module at Radio Shack and am attempting to use it with my Arduino Uno. How should I connect it to the
Arduino, and what library do I use?

How should I connect it to the Arduino

Refer to the schematic in the page you link to. That shows you which pin is which.  It's I2C, so there's just 2 data pins, power, and ground.

  and what library do I use?

The Osepp board is a GP2Y0D805Z0F connected to a PCA9534 IO expander. There is a library here.


Simple Ground circuit layout I am making a circuit without using a PCB or perfboard and i am unsure if i am running the ground wire correctly.

I usually prototype on a breadboard with the ground all joining on the far right, is this the same concept? I wanted to know if this is the accepted  convention for running the ground back to the board.

Yes, based on basic electrical theory, you have the ground connected correctly.


L298N motor driver issue I am facing the same issue with my motor driver. Initially I ran the code and connected the L298N with Arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver.

I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver?

One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine.

Here is my complete program:

const int MOTOR_RIGHT = 1;
const int MOTOR_LEFT =  2;
const int MR_CONTROL_PIN_A = 8;
const int MR_CONTROL_PIN_B = 9;
const int ML_CONTROL_PIN_A = 10;
const int ML_CONTROL_PIN_B = 11;

void setup() {
  // These two pins will act as output pin

  pinMode(MR_CONTROL_PIN_A,OUTPUT);
  pinMode(MR_CONTROL_PIN_B,OUTPUT);
  pinMode(ML_CONTROL_PIN_A,OUTPUT);
  pinMode(ML_CONTROL_PIN_B,OUTPUT);
  Serial.begin(4800);

}

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

  forward(MOTOR_RIGHT);
  forward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);
  backward(MOTOR_RIGHT);
  backward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);

}
/////////////////////////////////////////////////////////////////////
//Forward

  void forward(int motorNo)
  {

  Serial.print("\r\n Forward : ");
  Serial.print(motorNo);

  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,LOW);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,HIGH);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No ");
    Serial.print(motorNo);
   }
  }

//////////////////////////////////////////////////////////////////////
  void backward(int motorNo)
  {
   Serial.print("\r\n Backward : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,LOW);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,HIGH);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

///////////////////////////////////////////////////////////////////////
  void stopMotor(int motorNo)
  {
   Serial.print("\r\n STOP : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

Is there something wrong with my L298N ? How can I test it?

The specified minimum voltage for the motors is 2.5 volts higher than the logic supply.

You need to use a separate supply for the motor that is higher than the logic power.


Communicate with ESP8266 RX/TX I just managed to get a unofficial Arduino WiFi shield to work. But the ESP is flashed on its own now - providing only information to the USB->TTL converter and therefore the output goes straight to the Serial Monitor of the Arduino IDE.

Since the ESP is flashed and should be running now - I should be able to disconnected the USB->TTL converter and attach the Arduino RX/TX to the ESP TX/RX right?

Then I should receive Serial Data and should be able to process these in my Arduino Sketch right?

So what do I need to do now? Should I start trying a Serial read from the arduino with the baud rate specified by the ESP Flash (11520)? Or do I have to consider something else as well?

Your analysis is indeed correct, you can communicate between Arduino and ESP using the serial protocol.

Electrically speaking you must ensure the RX and TX pins are crossed:

Arduino RX goes into ESP TX
Arduino TX goes into ESP RX

Also, the two devices MUST have a common ground, the GND pins of the Arduino and the ESP8266 must be tied together.

You don't need level shifters because, even if the ESP8266 runs at 3.3V, its IO ports are 5V tolerant.

Also, as you already pointed out, the two devices must set the same speed (aka BAUD rate) in order to comprehend each other.

In case you decide to transmit binary data please also consider the two devices use a different architecture: Arduino is 8bit, ESP8266 is 32bit, meaning they have different word size (the minimum allocation unit size).

I had to face the word size issue when I first tried to exchange a struct between an Arduino and a RaspberryPI (also 32bit)...


How do I directly access a memory mapped register of AVR with C Assume I want to write the following without using DDRD or PORTD:

#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRD = 0xFF;
    PORTD = 0xFF;
}

I found this link which includes a list of mapped registers to memory addresses:
https://github.com/DarkSector/AVR/blob/master/asm/include/m328Pdef.inc

So I replaced one of the keywords with a pointer:

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRD = 0xFF;
    unsigned char *portd = 0x0b;
    *portd = 0xFF;
}

But it's not working (my LED isn't turning on with the second code). Why is that?

It's worth exploring how PORTD is defined in the actual AVR header file.  The relevant file is iom328p.h, and it's defined as:

#define PORTD   _SFR_IO8(0x0B)

_SFR_IO8 is defined as

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)

and

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

This shows that 0x0b is not the address of the PORTD register, but its offset from the address __SFR_OFFSET, which is 0x20.  Indeed, if you look at the ATMEGA328 datasheet, the register summary shows that PORTD is at offset 0x2b.  So that is the address that you would want to access via a pointer.

Note that this also shows the type of the pointer, if we fully expand the original definition of PORTD we get:

#define PORTD   _SFR_IO8(0x0B)
#define PORTD _MMIO_BYTE((0x0B) + __SFR_OFFSET)
#define PORTD _MMIO_BYTE((0x0B) + 0x20)
#define PORTD (*(volatile uint8_t *)(0x2B))

This syntax takes the integer 0x2B, casts it to type pointer to volatile uint8_t, and dereferences that pointer so you can assign to or read from the location the pointer references.  The volatile qualifier is important because it prevents the compiler from optimizing out accesses to memory.  Without it, the compiler may store the value to a register instead, or not store it at all, which would mean your IO port would remain unchanged or appear to report an incorrect value.

To go back to the title of your question, you have asked how to "directly access a memory mapped register in C", well the answer is you do that exactly the way the header file defines for you:

(*(volatile uint8_t *)(0x2B) = 0xFF

aka

PORTD = 0xff

There is no more direct way than this.  The compiler sees a literal address and writes to it.  What you've written is very different (adjusting to use the correct address and type:

volatile uint8_t * portd = 0x2b;
 *portd = 0xFF;

This allocates a location in memory symbolized by portd, which holds the value 0x2B.  When you write *portd = foo, the MCU has to access the location where portd is stored, take the value found there as an address to find the location you actually want to write to.  This method requires that you allocate a place in memory to hold portd and requires an extra memory access to be able to read or write to the port register.  This method is therefore indirect.

In reality, if optimization is enabled, the compiler may optimize the pointer away and replace it with the same literal access as in the PORTD case, however this depends on the program structure, and in particular the qualification and scope of the pointer.  Limiting the scope of portd as much as possible and/or declaring it as volatile uint8_t * const portd = 0x2b (which indicates that the pointer's value is constant even if the value pointed to is volatile) will increase the likelihood of the pointer being optimized away.

The reason the AVR headers define the IO port registers this way is because in addition to the standard load/store instructions that can access the entire data memory address space and take three clock cycles to complete, the IO registers are special, and can also be accessed using IN/OUT instructions, which complete in two cycles.  The load/store instructions use the memory address for the IO registers (starting at offset 0x20), whereas the IN/OUT instructions use the IO address, which starts at 0x00, but corresponds to 0x20 in the memory address space.  From the datasheet:

So when you access an IO location, the optimizer should recognize that it can issue a more efficient instruction than the standard load/store, and it will replace the load/store to 0x2b with an in/out to 0x0b.


How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0" I am working on a project where I would like values received from an Xbox Kinect will activate components on my Arduino. Currently, I am trying to get a servo motor to turn on and rotate when the value is "1" and to remain in one position (currently written as 120degrees) when the value is "0". However, I can turn on the motor and initiate rotation just fine, but when I let go of the mouse (and it shows that the value "0" is being sent in Processing and on the Serial Monitor), the motor just keeps spinning. This is my current code:

char val; // Data received from the serial port
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
  if (Serial.available())
  { // If data is available to read,
    val = Serial.read(); // read it and store it in val
  }
  if (val == '1') { // If 1 was received
    Serial.print ("1");// turn the LED on
    for (pos = 0; pos <= 120; 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 = 120; 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
    }
  }
  if (val == '0') {
    Serial.print ("0");
    pos = 120;
    myservo.write(pos);
  }
}

Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.


HC06 correct baud rate but missing characters/ no AT commands I have an issue with the communication between my Serial Monitor and my BT HC06 Module. Iam able to send ascii characters from my phone with BT connection to my local serial monitor. When i send characters from my local serial monitor to my BT module i receive something like this: AT -> U or 3 -> 3

I have this issue since i changed the baud from 9600,0,0 to 9600,0,1

Code:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(9600);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Sorry, my question was not easy to understand. Your solution had not worked for me.
I found another libary where its possible to add the parity bit:
https://github.com/ledongthuc/CustomSoftwareSerial

This works fine for me.

Thanks for your help :)


Syntax for declaring more than one serial pins of Arduino mega? How can I declare multiple serial ports for Arduino Mega as it has been in the example below?

#include <SoftwareSerial.h>
SoftwareSerial mySerial(18,19); // RX, TX  //how this syntax can be modified for multiple Rx module?

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

void loop(){
   Serial.write(45);    // send a byte with the value 45

   int bytesSent = Serial.write(â€œhelloâ€); //send the string â€œhelloâ€ and return the length of the string.
}

If you mean the built in serial ports then just user the other objects that are pre-declared as per:

https://www.arduino.cc/en/Serial/Begin


Loop though array values at end of each for loop cycle I'm using the NeoPixel Ring from Adafruit and trying to pulse though and array of colors. However, I'm having trouble with having the loop go to the next color at the end of each pulse (end of loop). Here is what I currently have:

uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed){
  int fadeAmount = 10; //how much to increase each loop
  int n = 0; //get first color
  for(int b = 100; b >= 10; b = b - fadeAmount) { //start pulse for loop
    for (int i = 0; i < strip.numPixels(); i++) { //select all pixels
      strip.setPixelColor(i, color[n]); //set color from our array
      }
    strip.setBrightness(b); //set brightness based on b
    strip.show(); // send the changes to the strip
    delay(speed); //wait before running again
    //if at the end of the loop (brightness is 10) change color
    if (b == 10){
      if( n > 6){ //if we are at last color in our loop start over
        n = 0;
      }
      else{
        n++; //auto increment color value
      }
    }
  }
}

I'm sure the problem is with the if statements but not sure how to fix it.

I can't quite make out what your if test is supposed to be doing, but don't you want a loop within a loop? Like this?

uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed)
  {
  const int fadeAmount = 10; //how much to increase each loop
  for (int currentColor = 0; currentColor < 6; currentColor++)
    {
    for (int i = 0; i < strip.numPixels(); i++)
      { //select all pixels
      strip.setPixelColor(i, color[currentColor]); //set color from our array
      }
    for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
      { //start pulse for loop
      strip.setBrightness(brightness); //set brightness based on brightness
      strip.show(); // send the changes to the strip
      delay(speed); //wait before running again
      }  // end of brightness loop
    }  // end of colour loop
  }  // end of pulseUp


Incremental encoder code can somebody tell me what`s wrong with my code, i am using it to calculate rpm using incremental encoder

long counter=0;
 long  rpm = 0, z =0;
 long  ini_time = 0;
long  end_time=0;

void setup(){
  attachInterrupt(0, A_RISE, RISING);

  Serial.begin(115200);
}//setup

void loop(){

    Serial.println(rpm);
}

void A_RISE(){
  counter ++;
  if (counter == 1)
    ini_time = micros();
  else if (counter>470){ //470 is ticks per revolution
    z = counter;
    rpm_counter(z);

    counter =0;
  }
}

void rpm_counter(int x){

  end_time=micros()-ini_time;
  rpm=(60*10^6)/end_time;

}

Volatile.

Essentially any variable declared within global scope (anything you declare before you get to setup()) MUST have the volatile qualifier if you want to use it within an interrupt service routine otherwise it will not be correctly utilised/implemented/instantiated.

As your code stands, you need to add voltatile to all four of your global variables:

volatile int counter = 0;     // if you're stopping at 470, int is all you need
volatile long rpm = 0;
volatile long z = 0;          // this isn't necessary, see below!
volatile long ini_time = 0;
voltaile long end_time = 0;

Your ISR includes some wasteful instructions, which will increase the time it takes for the routine to complete. As @jfpoilpret suggested, you may be constantly interrupting loop(). Cutting the time down may solve this:

Firstly, z = counter; rpm_counter(z); . Pointless, if I'm honest. Why not just call rpm_counter with counter?

Secondly, rpm_counter() function... it doesn't use the arguement you sent! "x" is not used anywhere within the function, so why are you sending it?

Thirdly, even if my second point wasn't valid rpm_counter() doesn't really need to be a function in its own right. Unless you're going to be calling it from lots of different places, just inline the contents of the function to into A_RISE():

else if (counter>470)
{ //470 is ticks per revolution
    end_time = micros() - ini_time;
    rpm = (60*10^6) / end_time;
    counter = 0;
}

That could save a great deal of execute cycles.


Powering Arduino with reverse car lights? I'd like to build a reverse car sensor using Arduino

When we select reverse gear, the reverse lights powers, so we can take electricity from them.

My question is can i power my Arduino directly from the reverse lights wires, or should i use regulators or anything else?

It depends very much on the car and your Arduino. There are two factors to consider:

Leeching power off lights can have an adverse effect on the car's ability to sense a blown bulb.
Many Arduinos have a 2 second delay while the bootloader executes (some even have 8 seconds).

If your car doesn't sense blown bulbs (most modern ones now do, even cheap ones) and you can work without a bootloader (programming directly with a USBasp for example) to avoid the power-on delay, then it may be possible, yes.

As has been mentioned by others, using a switching regulator is the best method for powering the board as it avoids excess power loss through heat (which can especially be a problem in confined spaces). I would recommend not using one of the cheap eBay modules, but instead using a proper "cigarette lighter" to USB adaptor (available from all good gas stations priced $5) which is designed to work with automotive voltages. A car's 12V power has transients in excess of 50V sometimes (back EMF from the spark generation) and the electronics have to be able to cope with that - those cheap eBay modules aren't designed for that and could die taking your Arduino with it.


connecting SIM900A GSM/GPRS module Arduino Mega i have bought following SIM900A GSM/GPRS module. I need to connect it with Arduino Mega. Can anyone answer me which pin i need to connect to Arduino??

From your pic, it looks like the upper left corner has a jumper with TTL level TX, RX, GND.


Need to set a FAILSAFE in an if else loop This works but I would like to have a timed failsafe...

If the FLOAT_PIN goes LOW for more than 3 seconds, it will turn SOLENOID_PIN to LOW.

I can't figure out how to incorporate it into my loop. I tried delay() and started playing with millis() but all I keep finding is LED blinking samples...

I'm not very good with C++ - still learning.

const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

void setup() {
  Serial.begin(9600);
  // Since the other end of the FLOAT switch is connected to ground, we need
  // to pull-up the FLOAT switch pin internally.
  pinMode(FLOAT_PIN, INPUT_PULLUP);
  pinMode(SOLENOID_PIN, OUTPUT);
}

void loop() {
  int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

  if (floatswitch == HIGH) {
    // If the pin reads high, water is OFF.
    Serial.println("Switch closed");
    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
  } else {
    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
  }
}

This is one of those cases when thinking in terms of a finite state
machine makes the programming quite straightforward. Here I would
use three states:

In the OFF state, the switch is LOW and the solenoid is off
in the ON state, the switch is HIGH and the solenoid is on
in the DELAYING state, the switch is LOW, but the program is
keeping the switch HIGH for three seconds.

The possible transitions are:

OFF → ON when the switch goes HIGH
ON → DELAYING when the switch goes LOW
DELAYING → OFF after three second in this state
DELAYING → ON when the switch goes HIGH.

The last transition is meant to ensure that LOW states of the switch
that last less than three seconds do not turn the solenoid off.

And here is a tentative implementation. Keep your constants and your
setup(), and replace your loop() with this:

const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

void loop() {
    static enum {OFF, ON, DELAYING} state;
    static uint32_t start_delay;
    int floatswitch = digitalRead(FLOAT_PIN);

    switch (state) {
        case OFF:
            if (floatswitch == HIGH) {
                Serial.println("Switch closed");
                digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                state = ON;
            }
            break;
        case ON:
            if (floatswitch == LOW) {
                start_delay = millis();
                state = DELAYING;
            }
            break;
        case DELAYING:
            if (floatswitch == HIGH) {
                state = ON;
            }
            else if (millis() - start_delay >= DELAY_TIME) {
                digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                state = OFF;
            }
            break;
    }
}


Getting inverse values of acceleration and tilt for the MPU 6050 I'm using the I2C library to connect to a GY-521 board and, when executing the getAcceleration() methods I get gyro values and viceversa..

This is my setup (I'm using a proto shield but that shouldn't change anything as far as I understand):

It follows this schematic:

And this is the code I'm testing:

#include "Wire.h"

#include "MPU6050.h"

MPU6050 accel;

int16_t ax, ay, az;

void setup() {
    Wire.begin();
    Serial.begin(9600);
    Serial.println("Initializing I2C devices...");
    accel.initialize();
    Serial.println("Testing device connections...");
    Serial.println(accel.testConnection() ? "Connected" : "Connection failed");
}

void loop() {
    accel.getAcceleration(&ax, &ay, &az);
    Serial.print("acc x:    ");
    Serial.println(ax);  // This prints the gyro value of the Y axis!
    delay(1000);
}

I don't think it has to do with the wiring since inverting the 4 and 5 analog pins yields zero values.

Is this a problem with the library? Or with my chip?

There are a lot of libraries, I wouldn't use the accelerometer library in wire, download and add the I2Cdev library, you can get it on a variety of different sites like github.com


How to reset millis( )? I am currently doing a school project.  There you have to program a stopwatch with the Arduino.  I wrote a program where millis starts.  But when I press my start button, millis don‘t start from 0.
Has someone an idea? Please let me know.

Ps: I‘m German, so I‘m sorry for my bad English

You don't. Instead you just remember what millis() was when you pressed your start button, then subtract that from whatever millis() is showing at any other point in the future.


NFC 'dynamic' UID database Hi SE (and Majenko in particular, if I'm lucky) -
I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE [sic] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

You got me ;)

Since a UID is a fixed size you don't need to think in "lines", only in bytes.

The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).

You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.

myFile.seek(recordNumber * 8);

If .seek() returns false then you have reached the end of the file.

So to find a tag you can:

myFile.seek(0); // Start at the beginning of the file
int recno = 0;
char foundUID[8];
bool found = false;
while (myFile.read(foundUID, 8)) {
    if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
        found = true;
        break;
    }
    recno++;
}

At the end of that found will be true if there is a match, and recno will be set to the record number. Now the magic begins...

If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:

myFile.seek(recno * 8);
for (int i = 0; i < 8; i++) {
    myFile.write(0xFF);
}

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.

Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.

It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.

If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the \r\n line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.


ble_write slows down my sketch causing problems (Blend Micro & NRF8001) I'm working on a prototype which uses the RedBearLabs Blend Micro with the NSC's nrf8001 ble chip, but have ran into a problem that I'm not sure how to solve.

I have two tactile buttons connected to the input pins on the Blend Micro, which are used to increase or decrease counters (integers) in my sketch that is in turn displayed on a OLED screen. When I use these buttons to manipulate the counter in offline mode (meaning that the bluetooth is not connected) I can repeatedly press the buttons very quickly and the counter is increased with every push - but when I connect to my phone and try to push the buttons with high frequency (>1-2 per second) the program is not able to react to every button interaction, causing only every second or third click to be registered.

The only thing that I do differently when I am connected is that I'm sending 5 bytes using "ble_write" (part of the RBL nrf8001 library), which seem to cause this delay resulting in missed clicks. Even sending one byte using "ble_write(X)" seem to slow down the sketch so much that this phenomena occurs.

Do any of you had similar problems and possible ways to solve this? I've been considering batching clicks together until I reach a certain amount and then send them at all once - this however may risk that a button is being pressed at the same time as the ble_write is executed, causing missed click.

Offline click looks like this:

if(digitalRead(A4)) {
while (digitalRead(A4)) {        }
offlineIn++;
localIn++;
totCount++;
sleepTimer = 0;
  }

And the online like this:

if (digitalRead(A4)) {
  while (digitalRead(A4)) {        }
  totCount++;
  localIn++;
  sleepTimer = 0;
  ble_write('0');
  ble_write('0');
  ble_write('0');
  ble_write('1');
  ble_write('1');
}

Thanks!

I've solved it by overclocking my blend micro to 16mhz (done in the Arduino IDE). Not a perfect solution but works. :)


Individually addressing LEDs in a multiplexed matrix I have created my first LED project with a hand made 4X4 LED matrix. The cathodes are joined horizontally to make the rows and the anodes are joined vertically to make the columns the columns. It is controlled by a shift register with the cathodes (rows) connected to pins 0-3 and the anodes (columns) connected to pins 4-7 of the register controlled from an Arduino Nano.

It all works but I have hit upon a limitation that I have not seen in the various videos and tutorials about making LED matrices so I suspect I am missing something.

This code will light up the bottom left LED which I will call position (0,0).

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
digitalWrite(latchPin, HIGH);

This code will light up the LED at position (1,1), so one up and one to the right.

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
digitalWrite(latchPin, HIGH);

If I then combine the two as below:

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B00111100 );
digitalWrite(latchPin, HIGH);

it of course lights up 4 LEDs: (0,0),(0,1),(1,0) and (1,1).

This feels like a limitation of wiring the LEDs in this way because once you power a row in a given column, you cannot unpower it in subsequent columns or vice versa. i.e. lighting (X,Y) and (A,B) means that you cannot have (X,B) and (A,Y) unlit.

However, in the videos I have seen that accompany tutorials on how to make similarly constructed matrices, I can see them lighting up in ways I can't replicate.

How can I light up an LED at positions (0,0) and (1,1) without also lighting up (0,1) and (1,0)?

Is this possible with this configuration?

Thanks to KIIV in the comments I figured it out. Apparently the trick is to rapidly switch between columns or rows without ever having two on at the same time.

With the below code running in the main loop it appears that (0,0) and (1,1) are lit at the same time even though they are actually switching rapidly.

void loop()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
  digitalWrite(latchPin, HIGH);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
  digitalWrite(latchPin, HIGH);
}


SPI - Apparently Random pulses on CS/SS line I'm trying to figure out why my SPI device isn't responding as expected. So I hooked up my logic analyzer and am a bit confused by the results.

I'm seeing what appears to be random pulses on the chip select/slave select line (CS in the images below). The pulses happen in random locations with random counts. Always matching either a falling edge or rising edge in the CLK line.

The code I'm running is part of a library, but I've pulled it all out for a minimum functional example:

#include <SPI.h>

#define DC_PIN          9
#define CS_PIN          10
#define BUSY_PIN        7

int IfInit(void) {
    pinMode(CS_PIN, OUTPUT);
    SPI.begin();
    SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
    return 0;
}

void SpiTransfer(unsigned char data) {
    digitalWrite(CS_PIN, LOW);
    SPI.transfer(data);
    digitalWrite(CS_PIN, HIGH);
}

int Init() {

    if (IfInit() != 0) {
        return -1;
    }

    SendCommand(0x01); //POWER_SETTING
    SendData(0x03);                  // VDS_EN, VDG_EN
    SendData(0x00);                  // VCOM_HV, VGHL_LV[1], VGHL_LV[0]
    SendData(0x2b);                  // VDH
    SendData(0x2b);                  // VDL
    SendData(0xff);                  // VDHR
    SendCommand(0x06); //BOOSTER_SOFT_START
    SendData(0x17);
    SendData(0x17);
    SendData(0x17);                  //07 0f 17 1f 27 2F 37 2f
    SendCommand(0x04); //POWER_ON
    WaitUntilIdle();
    SendCommand(0x00); //PANEL_SETTING
    SendData(0xbf);    // KW-BF   KWR-AF  BWROTP 0f
    SendData(0x0b);
    SendCommand(0x30); //PLL_CONTROL
    SendData(0x3c);        // 3A 100HZ   29 150Hz 39 200HZ  31 171HZ

    return 0;
}

void SendCommand(unsigned char command) {
//    digitalWrite(DC_PIN, LOW);
    SpiTransfer(command);
}

void SendData(unsigned char data) {
//    digitalWrite(DC_PIN, HIGH);
    SpiTransfer(data);
}

void WaitUntilIdle(void) {
    while(digitalRead(BUSY_PIN) == 0) {      //0: busy, 1: idle
        delay(100);
    }
}

void setup() {

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

  Serial.begin(9600);
  Serial.println("Start");

  if (Init() != 0) {
    Serial.println("init failed");
    return;
  }

  Serial.print("init success");

}

void loop() {

}

I've tried on two different ATMEGA chips (same Arduino Uno board), same results. I've also tried with the device disconnected. Again same results. I've also tried changing the pin used for the CS, still didn't change anything.

Anyone have some insight as to what might be causing this, and/or what can be done to stop it?

See my page about SPI.

  Pin 10 of the Arduino is the SS line - so does this mean you have to use it for the peripheral SS line? Or should it be kept high? The answer (from the Atmega documentation) is that the SS line (pin 10) must be configured as an output (regardless of what value is on it). If configured as an output the Arduino ignores the value on that line, and thus the SPI hardware will not be put into slave mode.

  Since the value on pin 10 is ignored, providing it is set as an output, then it can also be used as the SS line for your first, or only, slave. You could then use other pins (eg. 5, 6, 7, 8, 9) to control other slaves.

For you to successfully make an SPI master then pin 10 on your Uno must be configured as an output, regardless of whether or not you actually use pin 10 for SS. Under the circumstances, you may as well use pin 10 for SS if you are going to make it an output anyway.

  This issue persists when using pin 10 as the SS.

I tried your code with my Uno (no device connected) and had no such problems. Sounds like an electrical issue to me.


Output works on UNO Pin 13, but not on 2? I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).

I can receive and record the remote codes, and I can transmit the codes to an IR LED.

Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.

So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.

I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?

The sketch, since I know someone will ask for it:

int IRledPin =  13;
int buttonPin = 4;

void setup()   {
  pinMode(IRledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH); // pullup
  Serial.begin(115200);
}

void loop()
{
  if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts
  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
    digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    // so 26 microseconds altogether

    microsecs -= 26;
  }
  sei();  // this turns interrupts back on
}

void SendCode() {
  // This is the code for my FIOS FF
Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);

}

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);

Personally I would be putting the cli() around everything in SendCode (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.

I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

And this pulse width on pin 13:

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.

Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

  I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

Use a timer to generate 38 kHz

You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:

const byte LED = 10;  // Timer 1 "B" output: OC1B
const byte buttonPin = 4;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()   {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  Serial.begin(115200);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
}

void loop()
{
 if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
    delay (200);
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(const unsigned int microsecs) {
  TCCR1A |= bit (COM1B1); // clear OC1B on compare
  delayMicroseconds (microsecs);
  TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
  digitalWrite (LED, LOW);
}

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  noInterrupts ();
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);
  interrupts ();
}

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.

Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

For more information see my page about timers.

I have a graphic which shows a lot of the useful registers:


Digispark don't work when I power it by 5v and GND inputs and chip starts heating I'm beginner so probably I did something stupid, but now my digispark don't work when I power it by 5v and GND inputs but chip starts heating immediately. When I power it by USB everything works well. Did i broke it? And how can I check it?

You connected the power backwards - so all the current is being shunted straight through the ESD protection diodes (and likely other routes too) generating lots of heat and risking permanent damage to the MCU.

Take better care next time...


Compatibility between shields Despite that I am new to Arduino, I am tasked to invent a serious alarm system and I chose Arduino.
I study electronics, but virtually I am a software programmer and C is my area of expertise.

I ordered the parts I think I will need and the time is immensely pushing me.
The delivery goes slow and it needs to happen before our planned vacation, because
we've been robbed several times so far.
I need to know if I will need another gadgets to deal with a problem I've discovered suddenly.

  >

I plan to stack up these 3 shields

Arducam-F Shield V2 Camera module shield /w OV2640
3.5" TFT LCD Display Touch Screen Module
SIM900 Quad-band GSM/GPRS Shield

From what I've learned the shields 1 and 3 are compatible, as the arducam uses
CS/SD, ICSP, VCC, GND, SDA and SCL
or according to standard pin out table:
I2C_SCL, I2C_SDA, SPI_SCLK, SPI_MISO,
SPI_MOSI, 9, 10, Reset, 5V, GND
and the GPRS shield uses D7 and D0/D1(or D2/D3), 3 I/O ports. For D7.

The arducam however seems to be not stackable and as far as I can not see it is impossible
to make it stackable (Maybe even if I drill holes and solder stackable shield headers)
So it must be the topmost shield.

What about the LCD shield? I also learned that such shields use a lot of pins, so it is possible that there will be no free pins. I also ordered lots of jumper wires of any kind, if that can help.
Maybe I don't need to wire each of the pins in order to make it work or do some extra coding to get it work? I also don't necessarily need the other shields to work while I operate with the screen, so maybe there is a way I can connect/disconnect shields separately with a program or something else I can buy. I have a feeling that this LCD shield will leave no pins for the other shields and I should connect the arducam on another way since it is not stackable.

Its not just a question of the stackability of the shields and the clash of pins you also need to consider what the shields do.

Stacking the GSM shield under the LCD is going to restrict is tx/rx power unless you have an external aerial.

The LCD will require a large amount of memory and processing power, a 3.5" inch display is really going to push an Uno to the edge, you aren't going to get much time for servicing the GSM and camera.

The camera is also going to require a large amount of RAM and processing time to handle still images.  If you are processing video then I really doubt you will be able use the other shields.

You don't say if you are experienced in Embedded development.  Its different to Linux or Windows dev where resources are almost limitless.  If you don't have experience then you might find the transition quite hard.

Your question was are they compatible, I don't have the evidence but I would say no because of the resources they consume.  Sorry I can't see this project going anywhere fast. :(


Using PWM signal to decrease power of laser over time I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?

I dont know your circuit but...
Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...

To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.

Somewhere to start anyway :)


How to heat the air with arduino? I have a plant growing box, fully controlled with arduino.

Youtube: ESP8266 IOT Flora

All things are under control, besides the air temperature.
I can cool it down running fans, but cannot find a way to heat it up.

Need to keep the temperature between 25-28 C all the time.

I was thinking of:

8x8 (64) Leds - maybe this can heat up the temperature, how much ?
Dedicated Module - is there any 5v heating module available ?

LEDs are not really efficient for heating up, you can better use a normal light bulb for that (they are less efficient, thus giving more heat).

The Arduino can only control some 100's of mA, that's not much for heating purposes.

Did you think about using a real heater (maybe small size), and use a relay to turn it on by your Arduino, and using a temperature sensor to switch it off above 28 and switch it on below 25 (or a lesser margin to keep up with the time it takes to change the environment temperature)?

If you do not want an external mains power, you could use probably a 12V heater and use a 12V->5V converter for your Arduino, or use a 5V heater pad, but according to what I have seen they are more for warming up cold hands, I doubt they can bring up the heat to 25-28 degrees Celcius. Besides, they are probably not very efficient.


Look for Master and Slave code with error for a Arduino Mege I am building a a-10c Sim. So I need lots of input and outputs. Each Arduino has 54 digital i/o and 16 analog inputs in each. As I need more I just add another arduino mega 2560.

I want to thank in advance Im am very new at his, and would welcome any help.

Regards,

Gary
Im am a dyslexic so pls excuse the spelling or bed sentences

I am not sure that I understand what you are planning to build. From the Internet I see that a "10c Sim" is a flight simulation program. Therefore I assume you plan to build some hardware, like flight stick and throttle, to provide the necessary input to the PC on which this sim program runs.

The number of digital i/o and analog inputs you mention is not true for "each Arduino" but only for an Arduino Mega.

To expand the number of i/o pins you could add another Arduino, but this makes the programming (much) more complicated. You could set them up as master and slave, where the master tells the slave which output to perform and the slave tells the master which input came in. Or you can split-up the total system into two subsystems where each Arduino has his own responsibilities to handle it's part of the system. In order not to lose many i/o pins to the connection between both Arduino's, the connection between the two Arduino's has to be serial.

But there are better possibilities to extend the number of i/o-pins. IC's (chips) exist wit a serial input and a number of (parallel) i/o pins. A special case of this are the IC's working with I2C as the serial connection. Look at Google for "i2c port expander".


Getting an Arduino Uno and MKR zero to communicate I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.

Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?

Here is a picture of my setup:

Let the MKR Zero play the wav files. It has DAC on A0 and AudioZero library to play wav files from SD card.

You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.