Arduino documentation on PCIFR and PINC I was reading this thread:

Read RC receiver channels using Interrupt instead of PulseIn

and I have been trying to understand the code provided within.

While I was able to udnerstand most of it, I am still unable to find proper documentation on Arduino PCIFR and PINC?

Could someone please point me in the right direction?

Thanks in advance.

Welcome to Arduino.SE. The documentation that you seek on PCIFR and PINC would not be documented under Arduino, this is as these are directly related to the ATMega328 (AVR Atmel micrcontroller) which is on the Arduino, they are registers which are inside the microcontroller and PCIFR and PINC are mnemonics.

For the ATMega328 you will find the documentation to these registers in the datasheet (a good read with coffee), or in tutorials written by others explaining this information in an easy to grasp way.

The PCIFR register is the Pin Change interrupt flag register(description on pg 73 of linked datasheet), this holds the flag bit to tell the microcontroller that there was an interrupt and runs the ISR() routine that one has set out. Read this post by Nick Gammon on Pin Change Interrupts, and then read all of the post to get a better idea of interrupts in general.

The register PINC is for the inputs to the microcontroller, when one uses staus = digitalRead(A0); they are in effect using a wrapped up version of bitwise math and bit manipulation when simplified to status = PINC & (1 << PC0); thus PINx (x is for the register name ABCD) represents the state of the pin, either HIGH(1, 5V, true) or LOW(0, 0V, False). Borrowing from the below linked tutorial:

Another nice description of the input ports in this tutorial.

From the image you see that moving a bit to a position and then bitwise & that with PINx you will have a value returned if there is a 1 in that position.

 PINC      0b00001001
(1 << PC0) 0b00000001
         & __________
status  =  0b00000001

The above shows how you only get the state of the first input and how the 4th input is ignored as it was not needed. Also worth noting PIN is the register description and is not the same as a physical pin that sticks out the IC's body.


I²C between 2 Arduinos sends additional receive event I hooked up two Arduino Nanos with I²C, using 3 wires between GND <-> GND, A4 <-> A4, A5 <-> A5Ω and 1kΩ pull-up resistors on A4 & A5.

When I use the following code to communicate between them I get a weird empty receive event.

master.cpp

#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_SLAVE_ADDRESS 8

void setup () {
    Wire.begin();
    Serial.begin(SERIAL_BAUD);
}

void getFromState (unsigned char state) {
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Serial.print("s");
    Serial.print(Wire.write(state));
    Serial.print("e");
    Serial.print(Wire.endTransmission());
    delay(5000);
    Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
    int c = (unsigned char) Wire.read();
    Wire.flush();
    Serial.print("r");
    Serial.println(c);
    Wire.endTransmission();
}

void loop () {
    Serial.println("loop");
    getFromState(0);
    delay(10000);
    getFromState(1);
    delay(10000);
}

slave.cpp

#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_ADDRESS 8

unsigned char state = 0;

void requestEvent () {
    Serial.print("Request ");
    Serial.println(state);
    Wire.write(state);
}

void receiveEvent (int amount) {
    Serial.print("a");
    Serial.print(amount);
    Serial.print("r");
    state = (unsigned char) Wire.read();
    Serial.println(state);
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveEvent);
}

void loop() {
    delay(10);
}

Serial Output Master After 1.5 Loops

loop
s1e0r0
s1e0r1
loop
s1e0r0
s1e0

Serial Output Slave After 1.5 Loops

a1r0
Request 0
a0r255
a1r1
Request 0
a0r255
a1r0
Request 0
a0r255
a1r1

Question

Why is there an empty receive event a0r255 after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?

EDIT: I opensourced this project here, take a look if you want to!

Your code has several issues:

For the master:

Your I2C transactions should be quick and not delayed with Serial.print()s like in getFromState()
You requested 2 bytes from the slave but you are reading only one from the buffer. Wire.flush() flushes the outgoing buffer, not the receive buffer. Use while (Wire.read() != -1); instead.
Its also advised that you use Wire.available() to iterate through the receive buffer when read()ing; its how you check if anything was received at all and how many bytes were received.
After using requestFrom(), you shouldn't call endTransmission(). Its self-contained.

For the slave:

You should never call Serial.print() or delay() in requestEvent() or receiveEvent(); both functions are called from within ISRs and ISRs are meant to execute quickly and return.
You are requesting 2 bytes from the slave in your master code, whereas your slave's requestEvent() writes only one byte.
In receiveEvent(), again its best to use either Wire.available() to iterate through the RX buffer or you use the variable amount. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.


How to fade an LED in response to a sensor? As the sensor "sees" an object nearby, it makes the LED go to full brightness and it remains like that for as long as the sensor keeps on sensing the object. Then, as soon as the sensor stops sensing it, the LED goes OFF instantly... and so on, endlessly. This part of the code works perfectly as it is right now.

MY PROBLEM:

I need all of this ON and OFF switching to happen with smooth PWM fades instead of with abrupt "instant ON" and "instant OFF" changes. I need to have a 1.5 seconds PWM fade-in of the LED from 0% to 100% as soon as the sensor gets activated; and then a 3.5 seconds fade-out as soon as the sensor stops sensing something nearby. As long as the sensor is activated, the LED needs to remain at full brightness. So, simply put: I need the LED to dim smoothly between the sensor's state-changes, instead of changing instantly in an abrupt manner.

Do analogRead(sensor) and check what range of values you are getting. Arduino has 10 bit adc which means you can get 0-1023 in readings. However the sensor might not go complete LOW (0) or complete HIGH (1023). So just measure what's the range you are getting. Assume the range is 125 - 980.

PWM on arduino - This one is 8 bit, which means you can write 0-255. 0 means LED is OFF and 255 means LED is fully ON. Now you need to map 125-980 to 0-255 (as far as I can understand from your comments about synchronizing it with the sensor).

Here is what your code will look like:

/* Map an analog value (125-980) to 8 bits (0 to 255) */

    void loop()
    {
      int val = analogRead(0); //sensor attached to A0
      val = map(val, 125, 980, 0, 255);
      analogWrite(9, val); //LED attached to D9
    }


'tmElements_t' does not name a type I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:

#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

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

  tmElements_t tm;//it says that problem is in here

void setup() {

  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

and this is my output:

Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

     static bool read(tmElements_t &tm);

                      ^

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

     static bool write(tmElements_t &tm);

                       ^

SetTime:10: error: 'tmElements_t' does not name a type

   tmElements_t tm;

   ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

SetTime:21: error: expected primary-expression before ')' token

     if (RTC.write(tm)) {

                     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

SetTime:54: error: expected unqualified-id before '.' token

   tm.Hour = Hour;

     ^

SetTime:55: error: expected unqualified-id before '.' token

   tm.Minute = Min;

     ^

SetTime:56: error: expected unqualified-id before '.' token

   tm.Second = Sec;

     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

SetTime:71: error: expected unqualified-id before '.' token

   tm.Day = Day;

     ^

SetTime:72: error: expected unqualified-id before '.' token

   tm.Month = monthIndex + 1;

     ^

SetTime:73: error: expected unqualified-id before '.' token

   tm.Year = CalendarYrToTm(Year);

     ^

exit status 1
'tmElements_t' does not name a type

Clearly the compiler does not know what tmElements_t means.

It is defined in TimeLib.h

In your program you reference Time.h instead, where it is not defined.

So:  Change

include <Time.h>

to

include <TimeLib.h>

and it should clear that error.


MKR Fox 1200 doesn't wake up from sleep I have a Sigfox Arduino meassuring some sensors, sending it to the cloud and then falling asleep.

void setup()
{
Serial.begin(9600);
  while (!Serial) {};
  if (!SigFox.begin()) {
    Serial.println("Shield error or not present!");
    return;
  }
  SigFox.debug();
  delay(100);
  SigFox.end();
}

void loop()
{
SigFox.begin();
  delay(100);
  SigFox.status();
  delay(1);
  SigFox.beginPacket();
  SigFox.print("123456789012");
  int ret = SigFox.endPacket(true);

  if (ret > 0) {
    Serial.println("No transmission");
  } else {
    Serial.println("Transmission ok");
  }
  Serial.println();
  SigFox.end();
LowPower.sleep(20000);
}

The Issue I have is that the sending to the backend doesn't work when leaving the sigfox.debug() away and that it doesn't wake up from the sleep. It stays in sleep forever.

Looks like same problem as described in https://forum.arduino.cc/index.php?topic=483636.0
Solution described in that thread:
Add

LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, alarmEvent0, CHANGE);

to setup() and create a dummy function

void alarmEvent0() {
}


How to declare a global variable in the .h file? I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file.

The question is, is it possible to declare a variable in the .h file and make it global?

.h file is included by the compilation preprocessor as text into the .c or .cpp file. It is included as if you would replace the #include preprocessor instruction with the content of the .h file. (The Arduino .ino file is converted to cpp file before preprocessing.)

After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable definition the variable is defined in this object file. If your .h file contained a variable definition, the it is also in this object file.

If two cpp files included the .h file with the definition of the variable, then the variable will be in two object files and the linker will exit with an error, because of two variables with the same name.
If only one cpp/ino files includes the variable definition, then it is OK. It is not a good practice, but sometimes a necessary compromise. (example of it)

To have one global variable made accessible by a .h file, the variable should be only declared in the .h file and be defined in one cpp file. Usually it is a pair of .h and .cpp file with same name.

An example of global variable is Serial. It is a global object of type HardwareSerial declared in HardwareSerial.h as

extern HardwareSerial Serial;

and defined in HardwareSerial0.cpp as

HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);

Do you see the difference? The declaration has the keyword extern and the definition has in this case parameters for the constructor of the object. The declaration with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).


What's wrong with my keypad and time program? I really need help here. I'm a total noob in Arduino and this is my first Arduino project. I've been trying to get the keypad to be able to input time for my alarm clock project but I only managed to get the welcome part of the program. But then the display stuck at the welcome part only. I want to set alarm time by using the keypad only, and if the alarm time is the same as the time display, the buzzer should ring.

Plus, the deadline is in two days. I'm certain that there's no problem with hardware since all of the components (16x2 LCD, RTC DS1307, buzzer, 4x4 keypad) work properly when I use some basic tutorial coding for the components.

Please check what could be wrong in my code? I've tried to replace some of the codes but it had no change; the display's still stuck at the welcome part.

[Edit]I've added the "milli" code at the timedate() part. But I'm not sure, how to improve the alarm() part of this code? I can't input any key to insert the alarm time at this part.

If there's any update on what I've edit to my code later, I will edit this question's body. Thank you in advance.

#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
char buffer[3];
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {6, 7, 8, 9};
byte colPins[COLS]= {10, 11, 12, 13};
Keypad keypad= Keypad(makeKeymap(keys),rowPins, colPins, ROWS, COLS);

unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
Wire.begin();
rtc.begin();
pinMode(buz, OUTPUT);
lcd.begin(16, 2);
welcome();

rtc.setDOW(TUESDAY); //Set Day-of-Week to SUNDAY
rtc.setTime(18, 20, 00); //Set the time to 12:00:00     (24hr format)
rtc.setDate(18, 12, 2018); //Day, Month, Year
}

void loop() {
t = rtc.getTime();
Hor = t.hour;
Min = t.min;
Sec = t.sec;
tim = rtc.getTimeStr();
dat = rtc.getDateStr();
char key = keypad.getKey();

if(key == 'A'){
alarm();
}

if (key == 'C'){
digitalWrite(buz, LOW);
EEPROM.write(2, ASCII+6);
EEPROM.write(3, ASCII);
}
changealarm();
checkalarm();
timedate();
}

void checkalarm(){
if( Hor == h && Min == m)
{
delay(3000);
lcd.setCursor(0,1);
lcd.print("Hold C");
digitalWrite(buz, HIGH);
delay(3000);
}
}

void changealarm(){
buffer[2] = 0;
buffer[0] = EEPROM.read(0);
buffer[1] = EEPROM.read(1);
h = atoi(buffer);
buffer[0] = EEPROM.read(2);
buffer[1] = EEPROM.read(3);
m = atoi(buffer);
buffer[0] = EEPROM.read(4);
buffer[1] = EEPROM.read(5);
s = atoi(buffer);
}

void timedate(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Date: ");
lcd.print(rtc.getDateStr());

lcd.setCursor(0,1);
lcd.print("Time: ");
lcd.print(rtc.getTimeStr());
delay(3000);
lcd.setCursor(0,1);
lcd.print("Alarm: ");
lcd.print(h);
lcd.print(":");
lcd.print(m);
lcd.print(":");
lcd.print(s);
}
}

void welcome(){
lcd.setCursor(0,0);
lcd.print("Welcome");

lcd.setCursor(0,1);
lcd.print("To");
delay(2000);

lcd.setCursor(0,1);
lcd.print("TIMe Project");
delay(2000);
}

void alarm()
{
int j=0;
char key = keypad.getKey();
lcd.clear();
lcd.print("Enter Alarm Time: ");
lcd.setCursor(0,1);
while(j<4)
{
lcd.print(h);
lcd.print(":");
lcd.print(key);
lcd.print(m);
lcd.print(":");
lcd.print(key);
lcd.print(s);
lcd.print(key);
key=0;
}
delay(500);
}

Your function timedate() is called every time through loop() and it has a total of 6000ms of delay. During a delay, NOTHING can happen, not even checking for a keypress.

So, you would have to hold the desired key down until the key = keypad.getKey() statement is executed, which is a minimum of every 6 seconds.

Use of delay() for an interactive program in which user input can happen any time is not desired. Instead, there is a popular example Arduino sketch called "BlinkWithoutDelay" which us used as an explanation of how to avoid using delay() by letting your loop() function run at very high speed and only taking the desired action if the desired time has elapsed since some initiating action.

The more generic concept is called a "State Machine" and there are numerous websites that attempt to teach it, such as this one.

Be prepared to make significant changes to the structure of your program, however, as moving from delay() usage to state machine usage means a re-thinking of your loop() function -- you have to consider it running tens of thousands of times per second, and most of those times it doesn't do anything but check if something needs to be done -- most often the answer is "no, nothing needs to be done this time."


PID not working correctly I'm currently working on a project where I need to use PID to get the correct speed for a motor when it is angled a certain amount.

The problem is that I'm only getting 0.00 and 255.00 as the speed. Nothing in between. The code is supposed to activate when the angle value is more than 1300 and less than -1300. The ax variable is from an MPU6050 sensor.

int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
  Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop() {
  accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
  //Here I set the used variable to around 0. ax is actually around -10900
  //This is always true, this won't be in the final code. This is just making it work.
  if(1) {
    int val;
    val = map(a, -1300, 1300, 0, 1023);
    Input = val;
    myPID.Compute();
    Serial.println(Output);
  }
}

Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.

void loop() {
    int a = ax + 10900;
    if (1) {
      int val;
      val = map(ax, -1300, 1300, 0, 1023);
      Input = val;
      myPID.Compute();
      Serial.println(Output);
    }
  }
}

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.

There is a condition that is always true "if (1)" and so on.

Cheers!


Converting a standard setup/loop sketch to a low power application? Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.

How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // desired: enter low power mode here
}
void loop() {
  int buttonState = digitalRead(buttonPin);
  // desired: awake from low power mode here
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  // desired: back to low power mode here
}

This sketch is almost identical to the powerDownWakeExternalInterrupt.ino sketch that comes with the LowPower Library. I'm using INPUT_PULLUP and a N.O. push button switch to trigger it to wake up and turn an LED on.

#include "LowPower.h"
const byte wakeUpPin = 2;

// Just a handler for the pin interrupt.
void wakeUp(){}

void setup(){

  // Configure wake up pin as input.
  // This will consumes few uA of current.
  pinMode(wakeUpPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Allow wake up pin to trigger interrupt on low.
  attachInterrupt(0, wakeUp, LOW);

  // Enter power down state with ADC and BOD module disabled.
  // Wake up when wake up pin is low.
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

  // Disable external pin interrupt on wake up pin.
  detachInterrupt(0);

  // Do something here.
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);

}


Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers I intend to power three ATTiny45 chips (each requiring around 3.5V) in parallel with 2 pill batteries (namely Maxwell's CR2032) in series (which would come to around 6V). They will each play a sound with a piezo buzzer when a button is pressed.
Now maybe my thinking is wrong but I think dividing the power between the three chips may result in only around 2V delivered to each chip? Does the other components play a role?
So my question is this:

How much voltage is delivered across elements in parallel?
What changes should I do to the wiring to make the most of the voltage?
What kind of resources should I get to make sense of what to do? Cause I thought I was more advanced but this stomped me.

In any case I've added the schematic of what's intended.
[This schematic used to contain resistors to pull the switch but this need was removed with the help of jsotola's input_pullup comment]

simulate this circuit – Schematic created using CircuitLab

If you connect the AtTiny chips in parallel, they will all receive the full voltage from your battery. If you exceed the current output of your battery the voltage will droop.
If the AtTiny chips need 3.5V and you give them 6V instead, it will likely destroy the chips.
The short answer: Don't try to drive microcontrollers directly from batteries. You should get a 3.5V switching power supply. Then you will be able to drive all 3 chips cleanly from your battery. (Switching power supplies are very efficient. They don't waste much power at all.)
Note that button cells produce very small total power (in milliwatt/hours) so they won't drive your processors for very long before they are exhausted. I suggest using 4 AA batteries and a switching regulator instead. The 4 AA batteries would give you a 6V VIN to your voltage regulator, but a lot more total power.


LED series Resistor- Noob question Can someone please explain to me, like I'm 5, why this circuit does not work?

Every resistance calculator I use says that there is not enough voltage to calculate a resistance. If I understand correctly, wouldn't the LEDs light but just at a lower brightness?

Using R = V/I, The source voltage is 5v, the LED voltage is 6 divided by the current of 20mA equals -50ohms. All of the charge is used up by the time it reaches the arduino right?

The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.
Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)
Read this: https://www.baldengineer.com/led-basics.html :

Forward Voltage
The Forward Voltage defines the amount of voltage
required in order to conduct electricity. Any voltages below this
amount will cause the LED to remain “Open” and non-conductive. This
also means any components in-series with the LED will not have current
flowing through them either! Once the voltage dropped across the LED
reaches the Forward Voltage, it will begin to conduct electricity. Not
only that, but the LED will only drop its Forward Voltage at any given
time.
For example, consider a LED with a Forward Voltage rated at 3.0V. Now
what happens if you attach the Anode to the Positive (+) Terminal of a
AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will
the LED do anything? No! The AA (LR-6) Battery only has a nominal
voltage of 1.5V. Until you add a second battery, the LED will not
light up.


PWM on Pin 4 - arduino Micro I am using Arduino Micro. Is there any way to use PWM on pin 4 instead of Pin3 ?

I tried to change pins_Arduino.h but didnt worked.

//#define digitalPinHasPWM(p)         ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

#define digitalPinHasPWM(p)         ((p) == 4 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

and

const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    ////////////////////////modified///////////////
    //TIMER0B,      /* 3 */
    //NOT_ON_TIMER,
    NOT_ON_TIMER,
    TIMER0B,        /* 4 */
    ////////////////////////////////////////////////////
    TIMER3A,        /* 5 */
    TIMER4D,        /* 6 */
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    TIMER1A,        /* 9 */
    TIMER1B,        /* 10 */
    TIMER0A,        /* 11 */

    NOT_ON_TIMER,
    TIMER4A,        /* 13 */

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
};

You cannot. There is no PWM on that pin. PWM is generated by hardware. The hardware simply does not exist.


How to read ASCII values from AT24C32 IC using Arduino? And what is serial.begin(?) in that EEPROM? #include<Wire.h>
#include<Eeprom24C32_64.h>
#define EEPROM_ADDRESS 0x000

void setup() {
  Serial.begin(9600);
  eeprom.initialize();
  const word address = 0x000;
  const byte count = 94;
  byte inputBytes[count] = { 0 };
  byte outputBytes[count] = { 0 };
  Serial.println("Read bytes from EEPROM memory...");
  eeprom.readBytes(address, count, outputBytes);
  Serial.println("Read bytes:");
  for (byte i = 0; i < count; i++) {
    Serial.write(outputBytes[i]);
    Serial.print(" ");
  }
  Serial.println("");
}

void loop() {
}

Next code... I have tried many sketches.

#include <EEPROM.h>

void setup () {
  Serial.begin (115200);
  Serial.println ();
  for (int addr = 0x0000; addr < 0x0010; addr++) {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
  }
}  // end of setup

void loop () {
}

And most of the sketches check the internal EEPROM of the Arduino, not the external, stored on address 0x000. I want to read data from external AT24C32.

You have to know what the I2C address of your EEPROM is. Right now you have

#define EEPROM_ADDRESS 0x000

The example from the library you cite has this:

/**************************************************************************//**
 * \def EEPROM_ADDRESS
 * \brief Address of EEPROM memory on TWI bus.
 ******************************************************************************/
#define EEPROM_ADDRESS 0x50

Then, you have to create an instance of the Eeprom24C32_64 object:

static Eeprom24C32_64 eeprom(EEPROM_ADDRESS);

That sets up the object for the EEPROM on the right I2C address, so you can later use the eeprom object to read and write.


How to calculate actual Baud Rate and its percent error? I am using an Arduino Uno, and I need to create a program that calculates the actual baud rate and the percent error for all standard baud rate in Arduino monitor program.

First, look at the code used by the Arduino core library to configure
the USART baud rate register: it's in
HardwareSerial::begin(). The general formula is
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;

but beware of the hard-coded exception. You can replicate that part of
the code in your own.
Then, look at the ATmega328P datasheet. More specifically, at section
24.4.1. Internal Clock Generation – The Baud Rate
Generator. Here you find the formula
BAUD = F_CPU / (8*(UBRR0 + 1))

assuming the U2X0 bit has been set (again, beware of the hard-coded
exception). Combine both formulas and you get the actual baud rate.


Wifi server to control led on and off from local webpage.. - ..if statement doesnt work... Im a newbie on this arduino thing and I would like to build a curtain remotecontrolled from a local webpage with 2 buttons... a up an a down...

I got the connection via my phone the the local page with the buttons. :D

My problem on this one is that the buttons' if statement (command == on); doesnt work or in other words the client.println(command); get the "on" command and write it on the page... but it dont do the function in the if statement (the button)...

Can anybody help me...? it should be simple..:D

    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>

    int LEDPIN = 3; // your LED PIN
    YunServer server;

    String readString;

    void setup() {
  // Start our connection
  Serial.begin(9600);
  pinMode(LEDPIN,OUTPUT);
  digitalWrite(LEDPIN,HIGH); // turn on Led while connecting
  Bridge.begin();

  // Show a fancy flash pattern once connected
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);

  // Disable for some connections:
  // Start listening for connections

  // server.listenOnLocalhost();
  server.begin();

}

/* ------------------------------------------------*/
/* --------------- End WIFI connection ------------*/
/* ------------------------------------------------*/

void loop() {
  YunClient client = server.accept();
  if (client) {
      process(client);
    client.stop();
  }
  delay(50);
}

void process(YunClient client) {
  String command = client.readStringUntil('\\');

  client.println("Status: 200");
  client.println("Content-type: text/html");
  client.println();
  client.println("

");
  client.println("ON

");
  client.println("OFF

");
  client.print("Command: ");
  client.println(command);
  client.println("");

/* ------------------------------------------------*/
/* ------------------- Buttons --------------------*/
/* ------------------------------------------------*/

  if (command == "on") {
    digitalWrite(LEDPIN,HIGH);
    digitalWrite(13,HIGH);
  }

  if (command == "off") {
    digitalWrite(LEDPIN,LOW);
     digitalWrite(13,LOW);
  }
}

Pretty sure your problem is coming from the fact that you chose to use the backslash as your terminator character. The backslash requires special handling when encoded as a URL. You can observe this by Googling for "\" and and the results page you'll see your query in the address bar assigned to the "q" variable:
q=%5C
my entire URL looked like this, you may have something a bit different:
https://www.google.com/?gws_rd=ssl#q=%5C

Ok - so if you want a quick fix, stop using the \ to terminate your commands, since backslashes are often used to help sort out special characters (like "TAB" as \t) it's a a really bad choice, but an honest mistake.

If you change your code to generate links terminated with dashes you can get around the issue

client.println("ON

");
client.println("OFF

");

and of course change your readStringUntil invocation too

client.readStringUntil('-');

Edit:
You might want to use the "" if the hostname part of your URL contains a space:
http://my-web-server.com/on

And one more alternative, seek the "%" instead since that's going to be used to encode the backslash. In that case you just need to change the readStringUntil()


Low Power Library 4 seconds ON, 10 minutes OFF Could someone please demonstrate how to use a counter with the Arduino 'low power' library to wait for 10 minutes then digitalWrite 4000, HIGH and loop. (I don't mean the simple 'blink' sketch).

I'm trying to save as much power as possible, so any advice is appreciated.

Thanks!

Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like TPL5110. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.

This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

Then, you simply you do all your stuff on the setup() function and leave loop() empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your setup().

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.


Pin 0 (62) you are trying to use is not supporting interrupts Using RCLib (github) I'm getting this error. The trick is that the RCLib example works on it's own but does not work in my program (github).

Serial Output "Error"

Pin 0 (62) you are trying to use is not supporting interrupts
Pin 1 (63) you are trying to use is not supporting interrupts
Pin 2 (64) you are trying to use is not supporting interrupts
Pin 3 (65) you are trying to use is not supporting interrupts
Pin 4 (66) you are trying to use is not supporting interrupts
Pin 5 (67) you are trying to use is not supporting interrupts

It is quite right. Those pins aren't interrupt pins. What you want to do is make it use PinChange interrupt pins instead.

This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.


Changing the mode when pressing/holding down a buttton And first of all sorry for my bad English.

I am trying to write code that allows the user to change between continuous or manual mode, but I am having some issues getting it to work. The goal is to be able to switch from manual SOS (user pressing the button to SOS) and automatic SOS (the led automatically blinking SOS morse).

Currently, when I press down the button it loops once the automatic SOS and returns back to its normal state with LED on.

How would I make it, for an example switch the mode to manual when holding down button and giving user some sort of indication when changing the mode (etc blinking the led for X amount of time?)

What I am looking to achieve is:

Turn LEDS on when pressing the button.
Start looping automatic SOS signal
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch to manual SOS signal (user pressing the button to signal)
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch back to an automatic loop.

The code so far:

// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin =  13; // the number of the LED pin
int mode;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  mode = digitalRead(buttonPin);

  // Manual SOS mode.
  buttonState = mode;

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED on:
  } else {
    digitalWrite(ledPin, LOW); // turn LED off:
  }

  // Automatic SOS mode.
  if (mode == HIGH) {
    // check if the pushbutton is pressed.
    // if it is, starts looping automatic SOS.
    int i = 0;
    for (i=0; i<3; i++) {
      digitalWrite(ledPin, HIGH);   // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(1200); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(1200); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }
    digitalWrite(ledPin, LOW);
    // waits 3 seconds before starting the loop again
    delay(3000);
  }
}

Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.

First we define the PINs: defines are pre-processor macros, even better than const in terms of performance and space consumption:

#define BTN_PIN 2
#define LED_PIN 13

Let's initialize the board as per our requirements:

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

Now we define the code which emits and SOS signal in morse code using the standard timing:

a long pulse lasts 3 times a short one
a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:

#define UNIT 300
#define SHORT (UNIT)
#define LONG (UNIT*3)
#define PAUSE (UNIT*3)
#define SPACE (UNIT*6)

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the delay(...) function, but this will prevent detecting button presses while signalling:

#define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

With the above in place we can define a function to send an SOS which should be both very compact and also readable:

void sendSOS() {
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
  PULSE(PAUSE); // inter letter pause
  PULSE(LONG);PULSE(LONG);PULSE(LONG);
  PULSE(PAUSE); // inter letter pause
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
}

Now, let's describe what the mode changing should be notified to the user:

#define QUICK 100
bool autoMode = true;

void switchMode() {
  autoMode= !autoMode;
  for (unsigned int i = 0; i < 25; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(QUICK);
    digitalWrite(LED_PIN, LOW);
    delay(QUICK);
  }
}

Now our main loop will have to check the button and act accordingly, right?

#define LONGPRESS 500
unsigned long elapsed;
bool clicked = false;
unsigned long duration;

void loop() {
  if (autoMode) {
    sendSOS();
  }
  elapsed = millis();
  while(clicked || millis() - elapsed <= SPACE) {
    // keep waiting to emit a SPACE or until the button is released

    if (digitalRead(BTN_PIN)) {
      // button has been clicked: trace it and start counting time
      clicked = true;
      duration = millis();
    } else if (clicked) {
      // button has been released: stop tracing and verify click duration
      clicked = false;
      if (millis() - duration <= LONGPRESS) {
        // switch mode on long press
        switchMode();
      } else if (!autoMode) {
        // short press has a meaning only when not in auto mode
        sendSOS();
      }
    }
  }

The solution above has great space for improvement:

there is no de-bouncing on the button
the board is unresponsive while signalling
keeping the button pressed forever will prevent any signalling to occur in any mode
the code is afflicted by millis() rollover if you keep the button pressed for long periods (around 49 days)

UPDATE: I've added the inter-letter pause as suggested in the comments.

UPDATE: apparently auto is a reserved word, so I changed it to autoMode.


GSM shield 2 - Fully erase memory buffer I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.

What I'd like to do

My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem[1].

  I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the sms.flush() function. This function is available from the GSM.h library, which is bundled with the Arduino IDE by default.

and here comes the first glitch: the flush()function reference page states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that flush() would only work for outgoing messages...
...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use flush() to delete received SMS.

So for me, flush() really works both for outgoing and received SMS. Am I right?

What I did

Here is how the program works:

The arduino receives a SMS and is asked to light a LED
It does as instructed
then sends a SMS back saying that the LED is ON.
The DeleteSMS function is triggered

Here is the code:

void DeleteSMS(){
    int MessageQtt = 0;
    Serial.print(F("["));
    do{
        sms.flush();
        MessageQtt++;
    } while (sms.available() > 0);
    Serial.print(MessageQtt);
    Serial.print(F(" message(s)"));
    Serial.println(F(" have been deleted]\n"));
}

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also any SMS received in the mean time.

But it doesn't work and I can't really find out why.

My devices

Arduino UNO
GSM Shield 2
local (France) provider SIM card

Thanks all in advance for your input...

(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

[^1]: From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the memory buffer, but I can't really retrieve my source on that one.

Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.

So, the bottom line: never try to use the shield without a good powering system.


The most effective way to format numbers on Arduino I made a big search about how to Format Numbers with the Arduino. I want to format unsigned Longs into a String in this format: "23,854,972".

The most of the snippets I found work only with the standard C / C++ Libraries. They dont work on the Arduino until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is fast.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is more effective in the sense of speed.

Incoming Number: 23854972
Arduino Program Output: 23,854,972

Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like

digit = '0' + val % 10;
val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:

/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

pre-filling the string with spaces (for padding)
calling the function above
using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.

Here is a simple test program:

unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i < COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}


Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers I have a little project at the university where I have to use the timers to generate a pwm signal and get it into a piezo buzzer when something else turns over a certain value by using the registers, the thing is that we have worked on some other microcontrollers so I don't really know the libraries for arduino uno with atmega328p and I would require some help on that. Also I have to use the registers instead of the function analogRead() that is reading from a temperature sensor.

Having the following code that works for my setup:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Digital pins to which you connect the LCD
const int inPin = 0;
const int buzzer=9;// A0 is the sensor
void setup()
{
  pinMode(buzzer,OUTPUT); // DDRA=0b00000001;
  lcd.begin(16,2);
}
void loop()
{
  int value = analogRead(inPin); // read the value from the sensor <= to be written on registers
  lcd.setCursor(0,1);
  float millivolts = (value / 1024.0) * 5;
  float celsius = (millivolts-0.5)*100;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(celsius);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print((celsius * 9)/5 + 32); //turning the celsius into fahrehait
  lcd.print("F");
  delay(1000);
  if(celsius>30.0){tone(buzzer,1000);delay(1000);noTone(buzzer);delay(1000);} //<= on registers
}

In fact all the mentioned function calls are using the Special Function Registers (SFR) and thus the hardware peripherals of the Arduino in the background to work. But I guess this is an exercise to learn how to configure and use these peripherals yourself. Doing this for the whole code is a rather big task for a single question on this site. So I will give you hints and will point you to the corresponding registers. Then the datasheet of the Atmega328P (the microcontroller on the Arduino Uno) is a must read for you. It contains detailed descriptions for almost every function and SFR of the microcontroller.

PWM: I think you want to use PWM for creating a tone from your buzzer. This is not the classical PWM use case (as you don't need to change the duty cycle but the frequency to get different tones). Nonetheless you reach it with the same hardware. For hardware PWM you need to configure a Timer. The Uno has 3 Timers, where Timer0 is already configured by the Arduino IDE for functions like delay(), millis() and such. So I suggest you use Timer1. It has 3 control registers called TCCR1A to TCCR1C. You want the timer to be in CTC Mode (Clear Timer on Compare Match)(Waveform Generation Mode Bits set to 4, CTC mode for OCR1A). The timer will count up with the set frequency (will describe this later) until it gets to the value, that you wrote into the OCR1A register (Compare Match). Then it will reset. If you have set the COM1Ax bits in the TCCR1A register to the correct values, you can set it up to toggle the OC1A pin on a Compare Match).

So in this mode, the timer will reset at a counter value that you set and will toggle the OC1A output pin for you. Thus it generates a square wave with variable frequency, that you can control by writing different values to the OCR1A register.

But we also need to configure the frequency with which the timer will count up. This is done by the clock selection bits CS10 to CS12 in the TCCR1B register. A value of 0 for all bits means the timer is stopped. Look at the corresponding table in the Timer1 register descriptions in the datasheet. You want to connect the timer to the internal system clock. With these bits you can set the prescaler. This determines how many clock pulses it needs to let the timer count 1 up. With no prescaler the timer will count at every clock pulse. With the bit values 0 1 1 you will get a prescaler of 64, so the timer will count up 1 every 64 clock pulses. This sets the frequency range, that you have with the counter. The internal system clock runs at 16MHz on the Uno (you can do the math with the prescaler to calculate for the wanted frequency).
analogRead aka ADC: For reading an analog voltage the ADC (Analog Digital Converter) is used. It has the SFRs ADMUX, ADCSRA, the convertion result registers ADCL and ADCH, and ADCSRB. First we want to set the reference voltage for our conversion. When we set the REFS1 and REFS0 bits in the ADMUX register to 01 we use Vcc as voltage reference, which is sufficient most of the time. The bits MUX3 to MUX0 in the same register select one of the ADC pins for AD Conversion (We have only 1 ADC in the Atmega328P, but we can connect it to multiple ADC pins one after another). Now on the ADCSRA register: The ADEN bit will enable the ADC, with ADSC we can start a conversion. With the bits ADPS2 to ADPS0 we can select a clock prescaler for the ADC. This determines how fast the ADC runs. For maximum resolution you should keep the frequency between 50 and 200kHz.

You can start a conversion by writing 1 to the ADSC. Then you can poll the ADIF bit in the same register. It will be set to 1, when the ADC has completed the conversion. Then you can read the conversion result from the ADCL and ADCH registers (for the Low byte and the High byte of the 10bit result). You should reset the ADIF bit after that by writing a 1 to it.
LCD: I don't know, if you also need to replace the LiquidCrystal library by your own code, since it does not use special peripherals (just digital pins). Digital pins are controlled via the DDRx, PORTx and PINx registers. Google "arduino port manipulation" for more information. And then you can resemble the functions from the library with it.


Arduino does not see data from nodemcu I’m trying to send data from a NodeMCU to an Arduino nano.

If I try to send data with one second delay - all working fine.

But if I try to send without delay or with a delay less than one second, then arduino sees data but nothing not does.

Arduino nano sketch:

#include <Servo.h>

Servo servo1;

int servo = 6;
int engine = 5;

void setup() {
Serial.begin(9600);
analogWrite(servo, 67);
servo1.attach(8);
}

void loop() {
if (Serial.available()) {
String model = Serial.readStringUntil(':');
i

f (model.equals("engine")){
String value = Serial.readStringUntil('c');
int power = value.toInt();
analogWrite(engine, power);
}
if (model.equals("servo")){
String value_servo = Serial.readStringUntil('c');
int power_servo = value_servo.toInt();
servo1.write(power_servo);
}
}
}

NodeMCU sketch:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "my_wifi_ssid";
const char* password = "my_wifi_password";

ESP8266WebServer server(80);

void get_vars(){
if (server.argName(0) == "engine"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("engine:"+server.arg(0)+"c");
}
if (server.argName(0) == "servo"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("servo:"+server.arg(0)+"c");
}
}

void setup(void){
main_stuff();
}

void loop(void){
server.handleClient();
}

void main_stuff(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

server.onNotFound(get_vars);

server.begin();
Serial.println("HTTP server started");

}

the newline characters from println (\r\n) stay in the serial input buffer and you read them with Serial.readStringUntil(':');. then the string is not "servo" but "\r\nservo"

if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them


Read sd card content(text files) and display it on lcdi2c i am working for a project based on lifi using arduino and i need to diplay content of sd card to lcd i tried a lot some online programs also i tried but there is a simple blank screen. one of the code i used is this:
CODE:
#include <SD.h>
#include <SPI.h>

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7);

File myFile;
const int CSpin = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(CSpin, OUTPUT);
  SD.begin(CSpin);

  lcd.begin(20,4);
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  lcd.setCursor(0,0);
  ReadLine();
  myFile.close();
}

void ReadLine(){
  myFile = SD.open("Sample.txt", FILE_READ);
  myFile.seek(0);
  char cr;
  for(unsigned int i = 0; i < (3 - 1);){
    cr = myFile.read();
    if(cr == '\n')
      {
        i++;
      }
  }

  while(true){
    cr = myFile.read();
    Serial.write(cr);

    if(cr == '\n'){
      break;
    }
    //here...
    else if(cr >= 0x20 && cr <= 0x7E){
      lcd.print(cr);
    }

  }
}

displays blank screen
Please help me out!! Any other working program also would work.!! Thanks in advance.

Well The Do You Really Have an i2c module connected to the display you can find this out by checking how many pins the display has if it is not four pins then you need the LiquidCrystal Library If Not Then The Arguments Passed To The LiquidCrystal I2c Function Should Be The Address Witch Should Be 0x27 If You Did Not Modify The i2c Module(Next Time Give The Circuit Schmatics )


Use a PIR Sensor to detect the movements of a paper I need to detect when a paper comes out from a laser printer and count the number of printed papers. For that I hope to use a PIR sensor to detect the movement of the paper from the printer. Is it possible to detect the movement of a paper using a PIR sensor? Please be kind enough to help me.

If the paper is hot when it comes out of the printer, possibly.  Could be unreliable though.

Better would be to place a photo-interrupter (or IR LED and IR Photodiode) in the path of the paper to detect a break in an infra-red beam.


Is it possible to send 2 or more o/p signal at the same time? I wanted run two motors using Cytron MDD10A Dual Channel motor driver. So my concern is based on execution of code that is done line by line, in that case when I'm driving two motors will this delay in output signal at the PWM pins make a difference in nature of performance i.e. for example a car wheel, in case there is such delay it'll cause one wheel to rotate prior to another which is not desired. If yes, how do I rectify the same.
I also wanted to know when I use the delay function does it cause the delay in execution of the previous line or reads the upcoming line upon some 'x' seconds of delay?
Thank you for your help.
edit: code sample:
void FWD() {       // to move forward
    digitalWrite(m1, HIGH);  // motor 1 ON
    digitalWrite(m2, HIGH);  // motor 2 ON
    analogWrite(tm1, 225);   // tm1 assigned to a PWM pin
    analogWrite(tm2, 225);   // tm2 assigned to another PWM pin
}

in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

Technically, it is possible to start two PWM outputs at the exact same
time on an Uno or Nano. If they are both controlled by the same timer,
you just have to update the corresponding control register once with
the relevant bits set to enable both channels. For example, you could
start outputs 5 and 6 simultaneously, as both are on Timer 0:
OCR0A   = value;  // set the duty cycle on OC0A = digital 6
OCR0B   = value;  // set the duty cycle on OC0B = digital 5
TCCR0A |= _BV(COM0A1) | _BV(COM0B1);  // enable both outputs

If the outputs are on different timers, it is a bit more tricky. Timers
0 and 1 can be synchronized by clearing their shared prescaler with the
Timer/Counter Synchronization mode active. I do not think there is a
simple way to synchronize Timer 2 with any of the others.
All this is highly hardware-dependent, and not supported at all by the
Arduino core library. Thus, if you want to apply any of this, you will
have to study the datasheet, and poke directly into the I/O
registers of the microcontroller.
But then, as Delta_G clearly points out in his answer, all this is
irrelevant to motor control. Motors are mechanical devices that have
significant inertia. They take time to speed up and slow down. Just to
give you a sense of scale, PWM outputs 3, 9, 10 and 11 deliver a square
wave with a period of 2.04 ms. Yes, those are milliseconds, and
this is too short for the motors to significantly change their speed
within one period. Contrast this with the handful of microseconds,
that the call to analogWrite() will take.


Compilation error using arduino-mk on arch Linux (undefined reference to __dso_handle) I'm compiling a simple sketch that reads values from an analog input
and activates a buzzer on a digital input.
working on an Arduino uno.
the sketch compiles and runs fine on windows and arch linux using the Arduino
IDE.

I recently tried to start working with Arduino-mk, I tried to compile the said sketch and got the following compiler error (analogVal is the variable holding the analogRead):

/usr/bin/avr-gcc -mmcu=atmega328p -Wl,--gc-sections -Os -o /home/niv/Gits/bin/uno/maglove/maglove.elf

~/Gits/bin/uno/maglove/maglove.ino.o ~/Gits/bin/uno/maglove/libcore.a  -lc -lm
/home/niv/Gits/bin/uno/maglove/maglove.ino.o: In function `_GLOBAL__sub_I_nothing':
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xc): undefined reference to `__dso_handle'
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xe): undefined reference to `__dso_handle'
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0x18): undefined reference to `__cxa_atexit'
/usr/bin/avr-ld: /home/niv/Gits/bin/uno/maglove/maglove.elf: hidden symbol `__dso_handle' isn't defined
/usr/bin/avr-ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
/home/niv/Gits/Arduino-Makefile/Arduino.mk:1416: recipe for target '/home/niv/Gits/bin/uno/maglove/maglove.elf' failed
make: *** [/home/niv/Gits/bin/uno/maglove/maglove.elf] Error 1
make: Target 'all' not remade because of errors.

I am not very experienced with Arduino yet, and google has failed me in finding this error or any keyword from it in the context of Arduino uno.

thanks.

I can't say I fully understand what is going on, but it seems that if you add:

void * __dso_handle;

You may be able to eliminate one of the problems. You might try the same trick with __cxa_atexit as well.

I found the idea by searching on:

  arduino __dso_handle

This is the webpage that I found that suggested the void * hack.


What are the benefits or advantages of Arduino CLI? I saw that Arduino got a CLI (Command Line Interface), and my first question was "why?"  Even after reading the article, I don't see or understand its advantages.

What advantages or benefits does a CLI have for Arduino?

I haven't done much with Arduino in several years.  For example, there wasn't an Arduino SE when I was fooling around with Arduino, so I probably have an out of date context for Arduino development.

Simple: you can program the Arduino without needing a GUI.

One good example: You have an Arduino connected to a Raspberry Pi built into a robot. You SSH into the Pi, edit the Arduino's program, and upload the new code. All from wherever you happen to be.

A second example: You can integrate Arduino compilation into your own software. Such as a web interface for compiling your code.  I know of one such project where the creator has made a custom website for editing their robot code and using UECIDE's CLI (which pre-dates Arduino's) to compile and upload the code to the target board.

And yes, you have an outdated context of Arduino development, as evidenced by your use of the phrase "fooling around with". Arduino is not a toy. It's a development platform and educational tool. Maybe back when you were "fooling around" with it, it was little more than a toy, but things have moved on a long long way since then. The Arduino ecosystem boasts boards with chips from every manufacturer you can imagine to fill every niche you can conceive. The API and available libraries have certainly matured.


Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A I'm trying to receive an SMS and show it on the serial monitor.

My code is as following:

void setup()
{

  Serial.begin(2400);
  Serial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  Serial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  Serial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(Serial.available())
    {
      Serial.write(Serial.read());
    }
  }
}

void loop()
{
}

The circuit diagram is as shown below.

The output that I am getting is as following:

AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR

ERROR
AT+CMGR=1
AT+CMGF=1

I am not able to use AT+CPMS or AT+CMGL commands.

The Arduino UNO that you are using only supports one Serial connection (over the TX and RX pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.

Read this article to see more about Serial and how it works on different boards.


595 Shift Register Not Working Properly I followed the tutorial on controlling 8 LEDs using a SIPO SN74HC595N shift register on both Adafruit and Last Minute Engineer. I used a Sparkfun Pro Micro (Arduino Leonardo equivalent).

The problem is the LEDs are not lighting up in the way that I'm expecting it do it. Both guides said each LED will light up one after another. After all 8 are lit, all of them will turn off. Here is my result. Other LEDs will either dim up or down as the target LED turn on. I used the code provided from the guide and only changed the pinout number. The resistor values are the same for each color so it can't be the resistor. Anyone have any idea what's going on here?

/*
Test code for 74HC595N SIPO shift register. Used with Pro Micro
*/

int latchPin = 16;
int clockPin = 15;
int dataPin = 14;
int outputEnablePin = 10;

byte leds = 0;    // Variable to hold the pattern of which LEDs are currently turned on or off

void setup()
{
  // Set all the pins of 74HC595 as OUTPUT
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(outputEnablePin, OUTPUT);
  outputEnablePin = LOW;
}

/*
 * loop() - this function runs over and over again
 */
void loop()
{
  leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++) // Turn all the LEDs ON one by one.
  {
    bitSet(leds, i);    // Set the bit that controls that LED in the variable 'leds'
    updateShiftRegister();
    delay(500);
  }
}

/*
 * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
 */
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

Schematics:

The dimming problem was found to be the shift register IC not connected to Ground (dumb me).

However, there is still problem with LED's on and off pattern. Sometimes two LEDs turn on at the same time and all previous LEDS turning off before the last or second last LED is turned on. It turns out Pin 10 (SRCLR Bar) needs to be pulled to high to solve that pattern discrepancy.


Arduino Uno synthesizer - Line Level (audio) output to mixer/amplifier Is using PWM tones from Arduino amplified by a HiFi amplifier safe? Can I damage the amplifier or speakers because the PWM signal is not a "real" audio signal? Taken in consideration that I do not clip the signal and using a RC Low Pass Filter to filter out inaudible frequencies and using a LM386 amplifier chip to amplify and control the volume?
I am developing a synth/sampler project based on the Arduino Uno r3. This is my first electronics project ever and because of that reason I have some questions which I can't find a definite answer for on internet.
The synth has two function. It has a tone generator using the ToneAC library. With code I have mimicked LFO and VCO functions, using potentiometers I can adjust the frequency and LFO speed realtime. The other function is that I can trigger samples stored on a SD card using the TMRpcm library. The lowest frequency which can be played is 100hz and the highest 3100hz.
The device will be used in nightclubs on high end sound-systems and PA. I am afraid I will damage the equipment with my device because I do not send a pure audio (AC?) signal.
Currently the flow is like this:
PWM output (pin 9, 10) -> voltage divider to 2.5v -> RC Low Pass Filter 15Khz -> LM386 amp with volume control -> mono jack output -> mixing desk -> amplifier -> speakers
(the TMRpcm and ToneAC library share the same pin (9), I have fixed this by disabling the TMRpcm when the ToneAC is playing and vice versa. The mono jack is wired as follow. pin 9 goes to plus side of mono jack output, pin 10 to negative side. The TMRpcm pin 9 also needs to go to plus side of mono jack output, and mono jack negative needs to go to ground. Because I disable the ToneAC at that time I consider port 10 grounded because it not generating any sound so there is no signal/voltage running out of it, aka the IO pin is set to LOW)
I am hoping that using the voltage divider I am within range of the Audio Line levels of a default mixers Line-IN (like Pioneer, Behringer, etc). The RC Low Pass Filter is used to filter of inaudible frequencies and clean up the sound a bit, the LM386 audio amp is used to amplify the signal and (hopefully) make it a real audio signal.
Because I lack a lot of knowledge in this field and because I do not own a oscilloscope I can't say for sure if my output signal is harmful for the equipment and was hoping to get some guidance on my project on this forum.

In theory, the peak signal accepted from your amplifier should be 0.894V p2p if you want to rescpect the common -10dB signal strength/level. I don't know why you would want to have a 5V to 2.5V "voltage divider" in the first place, but in any case if you use that you already limit the current probably enough, it all depends on the resistor values used.

Using the LM386 amplifier is also simply not required at all, since the Arduino is already providing more than enough power. If you want to tune the volume at that stage, simply combine all functions (volume, low pass and current limit) by connecting the 5V PWM output thru a resistor (eg. 4k7) to a POT (eg. 1k) in parallel with the capacitor (eg.2n2) would give you approximately what you want. Then to remove de DC component, add a series capacitor (eg. 1uF) and you're all set. You may still hear a "click" when you connect it to the amplifier though, so keep the faders low when connecting.

Of course you can adapt the values quite liberally, but these values are both safe and should be close to what is needed (cutoff 15kHz, Vpp 0.88V max).


having problems with my arduino bluetooth car project(with L298n Motor Driver) so the scenerio is i am making a bluetooth controlled car(voice control)+obstacle avoidence function.I am using arduino uno with L298n motor driver and a HC-05 BT module in the sensors i am using the ultrasonic sensor and a IR sensor for the back and a servo motor is aslo used to rotate the ultrasonic sensor.so the problem is when i am sending command "turn left" the servo moves left and nothings happens and the other command i.e turn right,move backward,move forward are not working at all.
circuit diagram and code is given plz guyz guide me where is the lacking if i have done  something wrong with the code or else my motor driver or wiring is creating te issue
CODE :
'''
#include <NewPing.h>
#include<Servo.h>
#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;
String voice;
void setup() {
Serial.begin(9600);
myservo.attach(8);
myservo.write(90);
pinMode(IR, INPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
}
void loop() {
int distance = sonar.ping_cm();
if (Serial.available() > 0) {
voice = "";
delay(2);
voice = Serial.readString();
delay(2);
Serial.println(voice);
if (voice == "turn left") {
  left();
} else if (voice == "left") {
  left();
} else if (voice == "turn right") {

} else if (voice == "right") {

}

}
while (voice == "move forward") {
forward();
}
while (voice == "move backward") {
backward();
}
}
void forward() {
int distance = sonar.ping_cm();
if (distance < 10) {
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
voice = "";
} else {
digitalWrite(12, HIGH);
digitalWrite(10, HIGH);
}
}
void backward() {
int IR_Sensor = digitalRead(IR);
if (IR_Sensor == 0) {
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
voice = "";
} else {
digitalWrite(11, HIGH);
digitalWrite(9, HIGH);
}
}
void left() {
myservo.write(180);
delay(500);
myservo.write(90);
delay(500);
int distance = sonar.ping_cm();
if (distance < 10) {
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
voice = "";
} else {
digitalWrite(12, HIGH);
delay(700);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}
}
void right() {
myservo.write(0);
delay(500);
myservo.write(90);
delay(500); {
int distance = sonar.ping_cm();
if (distance < 10) {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  voice = "";
} else {
  digitalWrite(10, HIGH);
}
delay(700);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);

}
}
void Stop() {
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}'''

The code seems to have a few missing lines for logic. Here's a corrected version from my understanding.
#include <NewPing.h>

#include<Servo.h>

#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {
      right();
    } else if (voice == "right") {
      right();
    } else if(voice == "move forward"){
      forward();
    } else if(voice == "move backward"){
      backward();
    }

  }

}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite(9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}


Problems with Draw Loop using u8glib I am using an Arduino Mega and a 12864ZW LCD with the u8glib library and the following code to draw to the LCD:

U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);

void loop(){
   Draw();
}

void Draw(){
   Display.firstPage();

   do{
      Display.setPrintPos(10, 10);
      Display.print("This is a test");
   }while(Display.nextPage());
}

The problem is that the display is constantly redrawing itself. When I used LCD displays in the past, they usually only required to write to the LCD once unless you wipe the display. When I adjusted the code to:

U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
bool needsUpdate = true;

void loop(){
   Draw();
}

void Draw(){
   if (needsUpdate){
       Display.firstPage();
       do{
          Display.setPrintPos(10, 10);
          Display.print("This is a test");
       }while(Display.nextPage());
       needsUpdate = false;
   }
}

I do not get anything drawn on the LCD. Is there a parameter that needs to be set so I only have to redraw the LCD if something changes? Am I using an outdated library? Is there a better library I should be using?

EDIT

I think the main problem I have with using this library is does the Draw loop need to be executed continuously to display on the LCD or is there a way to only draw the screen once until it is needed to be drawn again?

You haven't shown us all the code – in particular, the call to Draw() from loop() is missing – so this answer is speculative, based on the assumption your loop() is as follows.

void loop(void) {
    Draw();
}

If so, your first bit of code will constantly redraw because loop() runs repeatedly without delay.  Try adding a delay(1000); after Draw() in that case.

Your second bit of code will begin by drawing your image once, and in that Draw() call it will set needsUpdate to false.  Then loop() runs again, and the firstPage() call erases the screen.  Since needsUpdate now is false and remains false, subsequent calls don't draw an image.

Rather than putting your picture loop into Draw(), perhaps use Draw() just to draw primitives, and keep your controls in loop():

void loop(void) {
  Display.firstPage();
  do {     // picture loop
    Draw();
  } while( Display.nextPage() );
  delay(1000); // delay before next picture
}

If you still get repeated fast redraws, for troubleshooting comment out the do and } while lines.


Installing Arduino IDE on Linux I downloaded arduino-1.8.4-linux32.tar.xz and ran install.sh as outlined (the very sketchy instructions) in https://www.arduino.cc/en/Guide/Linux

This seemed to work OK, so I removed 354M of what I thought was the installer, only to discover that I had deleted arduino.

The so-called install.sh on closer inspection seemed only to create links into the uncompressed download in my home directory.

The whole process seems very un-Linux like; I had assumed that it would be installed in /usr/share/ like most Linux programs.

I realise I could extract into /usr/share/ and set permissions for other users, but surely there must be others who have wanted to do the same. The macOS version seems to have a proper installer; does one exist for Linux?

The problem here is that there are multiple flavours of linux each with their own installation and package management systems - Aptitude, Yum, EMerge, etc.

It is not easy for Arduino to keep up with creating packages for each and every system, so instead they create a single tarball that can be used on any of the systems.

At one point Arduino (or someone, anyway) used to create Debian packages for the IDE and upload them to the main Debian repository - however this has not been done for many years now and the packages in the Debian repositories are very much out of date (1.0.5 IIRC).

If you, as a system manager, choose to deploy the IDE system wide then it is your task to decide how best to do that.

One option is to just copy the contents of the archive to /usr/share/arduino and then run ./install.sh from within that directory.


Data Report Which Technology I want to create a small position reporter for cars. I found some good GPS Modules with which i could collect data. But i'm unsure with what technology i should send the data.

A possibility would be to setup a service in the www which is feeded by the arduinos.

I want to track the data live. so i think GPRS should be the right choice ?
Or more better are there any shields which make this GPRS LOG and SEND as a package ?

Which GPRS hardware would you use ?
Would you use something else?

Any hints are very welcome

You can actually find all the information for what you want to do on the formal Arduino.cc website. They suggest a GSM shield:

But of course you can find many other GSM shields for purchase. Most of them works the same. Arduino.cc also offer a nice GSM Library, with which you can perform HTTP GET/POST queries to a remote webserver (visible over the web).

You can select whatever web server technology you prefer for receiving the data. Using NodeJS, PHP, MVC.NET or any other, you could expose a REST API to perform the update from the Arduino+GSM Shield side using HTTP.

The web server then could analyze the incoming data and display it in any way you like.


Minimal example of Task Scheduler Blink? Scheduler_example00_Blink is ~300 lines. For just an Arduino Uno, what is a minimal example?
It's hard to know what belongs and what doesn't. This example has six different approaches, and I'm just trying to extract one of them.

#include <TaskScheduler.h>

// Scheduler
Scheduler ts;

/*
   Approach 1: LED is driven by the boolean variable; false = OFF, true = ON
*/
#define PERIOD1 500
#define DURATION 10000
void blink1CB(); // <-------------------------------------------|
Task tBlink1 ( PERIOD1 * TASK_MILLISECOND, DURATION / PERIOD1, &blink1CB, &ts        , true );
//           (     500 * 1UL (ms)        , 100000 ms/ 500    , function , just put it,  ?   )

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  ts.execute();
}

inline void LEDOn() {
  digitalWrite( LED_BUILTIN, HIGH );
}

inline void LEDOff() {
  digitalWrite( LED_BUILTIN, LOW );
}

// === 1 =======================================
bool LED_state = false;
void blink1CB()
{
  if ( LED_state )
  {
    LEDOff();
    LED_state = false;
  }
  else
  {
    LEDOn();
    LED_state = true;
  }
}


Serial doesent work when calling function from timer You can try the code on your arduino UNO to better understand what is hapening in serial monitor!
I want to calculate jacobian matrix from rotation matrix!
float jakMATB[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
     };
float POKUS = 0;
float k = 0.000001;
float dt = 0.001;
float b = 90 * (PI / 180);
float vnB[3] = {0, 1, 0}, vpB[3] = {0, 1, 1};
float nB[3] = {0, 1, 0};
float nBplus[3] = {0 , 1, 0};
float nBminus[3] = {0, 1, 0};
void setup() {
Serial.begin(9600);
Serial.print("init ok");
cli();//stop interrupts
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1  = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = (16000000) / ((1 / dt) * 1024) - 1; // 15624 = (16*10^6) / ((1)*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}

when I call the function in loop everithing works fine and I get  1 2 1 in serial monitor
 void loop() {
 izracunJAKOB();
 for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  Serial.print(jakMATB[j][i]);
  Serial.print(" ");
}
Serial.println("");
}
}

when I call izracunJAKOB() with timer interupt Serial monitor
stops working and doesent event write "init ok"
ISR(TIMER1_COMPA_vect) {
  //izracunJAKOB();
 }
void izracunJAKOB() {
for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  nBplus[j] = nB[j] + k;
  nBminus[j] = nB[j] - k;
  float matricaBplus[3][3] = {
    {cos(b) + nBplus[0]*nBplus[0]*(1 - cos(b)), nBplus[1]*nBplus[0]*(1 - cos(b)) - nBplus[2]*sin(b), nBplus[0]*nBplus[2]*(1 - cos(b)) + nBplus[1]*sin(b)},
    {nBplus[1]*nBplus[0]*(1 - cos(b)) + nBplus[2]*sin(b), cos(b) + nBplus[1]*nBplus[1]*(1 - cos(b)), nBplus[1]*nBplus[2]*(1 - cos(b)) - nBplus[0]*sin(b)},
    {nBplus[0]*nBplus[2]*(1 - cos(b)) - nBplus[1]*sin(b), nBplus[1]*nBplus[2]*(1 - cos(b)) + nBplus[0]*sin(b), nBplus[2]*nBplus[2]*(1 - cos(b)) + cos(b)}
  };
  float matricaBminus[3][3] = {
    {cos(b) + nBminus[0]*nBminus[0]*(1 - cos(b)), nBminus[1]*nBminus[0]*(1 - cos(b)) - nBminus[2]*sin(b), nBminus[0]*nBminus[2]*(1 - cos(b)) + nBminus[1]*sin(b)},
    {nBminus[1]*nBminus[0]*(1 - cos(b)) + nBminus[2]*sin(b), cos(b) + nBminus[1]*nBminus[1]*(1 - cos(b)), nBminus[1]*nBminus[2]*(1 - cos(b)) - nBminus[0]*sin(b)},
    {nBminus[0]*nBminus[2]*(1 - cos(b)) - nBminus[1]*sin(b), nBminus[1]*nBminus[2]*(1 - cos(b)) + nBminus[0]*sin(b), nBminus[2]*nBminus[2]*(1 - cos(b)) + cos(b)}
  };
  jakMATB[i][j] = (matricaBplus[i][j] - matricaBminus[i][j]) / (2 * k);
  nBplus[0] = 0;
  nBplus[1] = 1;
  nBplus[2] = 0;
  nBminus[0] = 0;
  nBminus[1] = 1;
  nBminus[2] = 0;
}
}
}

//////////////////////////////
when I comennt out
   nBplus[j] = nB[j] + k;
   nBminus[j] = nB[j] - k;

and
   nBplus[0] = 0;
   nBplus[1] = 1;
   nBplus[2] = 0;
   nBminus[0] = 0;
   nBminus[1] = 1;
   nBminus[2] = 0;

Serial works just fine
when I coment out only  matricaBminus and  matricaBplus serial works fine
Please help! It surely is a stupid solution!

Timer was to fast! When I decreased frequency everithing worked fine.


Possible to "inline" PROGMEM strings into a structure array initialization? I have the following structure:

struct inst_t {
    const char *s1;
    const char *s2;
};

I'd like to initialize a constant array of this structure like this where all the strings are PROGMEM'ed:

const char START[] PROGMEM = "START";
const char ATZ[] PROGMEM = "ATZ";
const char ATE0[] PROGMEM = "ATE0";
const char OK[] PROGMEM = "OK";

static inst_t insts[] = {
    { START,      NULL },
    { ATZ,        OK },
    { ATE0,       OK }
};

You can see there is a lot of duplication here though. Is there anyway way I can inline the PROGMEM strings directly into this array initialization without separately declaring each string as being in PROGMEM?

If the strings are similar size you can, like this:

const int NUMBER_OF_ELEMENTS = 10;

typedef struct {
   char description [12];
} descriptionType;

const descriptionType descriptions [NUMBER_OF_ELEMENTS] PROGMEM = {
 { "Furnace on" },
 { "Furnace off" },
 { "Set clock" },
 { "Pump on" },
 { "Pump off" },
 { "Password:" },
 { "Accepted" },
 { "Rejected" },
 { "Fault" },
 { "Service rqd" },
 };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    // make a copy of the current one
    descriptionType oneItem;
    memcpy_P (&oneItem, &descriptions [i], sizeof oneItem);

    Serial.println (oneItem.description);
    }   // end of for loop

  }  // end of setup

void loop () { }

This is a bit wasteful of program memory, because you need to allow for the largest string (your example had them all similar sizes) but what you save is not needing a two-byte pointer for each string, so if they are all similar lengths, it will take about the same memory.

See my page about PROGMEM.


remove weird chars from char array ESP32 When I'm converting a string to a char array there are always some weird chars at the end.
I have to do it manualy because the convertTochar function crashes my ESP.

  String sssid = module.getCssid(); //String is stored in the eeporm
  char cssid[sssid.length()];
  Serial.println(sssid.length()); //prints correct length of 6
  //convert do ssid
  for( int i = 0; i<sizeof(cssid);i++){
    cssid[i] = sssid[i];
  }
  Serial.println(cssid); //prints myssid⸮?⸮2⸮?
enter code here

If I'm printing the value directly fromm eeprom there are no wired characters.
Also the max eeprom size for the string is 10 bytes...

Why are these characters at the end of string?

You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.

Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.

Instead of the for loop you can use the strcpy function which copies a function including the 0 string.

See description:

Description

The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.

Declaration

Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)

Parameters

dest − This is the pointer to the destination array where the content is to be copied.

src − This is the string to be copied.

Return Value

This returns a pointer to the destination string dest.

Example

The following example shows the usage of strcpy() function.

#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[100];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);

   return(0);
}


Global variable changes its value when loop starts again I have a problem with the global variable calibrationValue. It is initially set with the correct value and is also displayed correctly in the output. As soon as the loop function is restarted, the value of the variable is wrong, although it is not rewritten. Can someone help me please?
The following values are printed in the image:

new AI value
wrong calibrationValue (!)
sumOfValues (needed for calculation of calibrationValue) correct
numValues (needed for calculation of calibrationValue) correct
Text and calibrationValue (correct!)

    int op_mode_Pin = 7;                      // Digital input Pin which transmittes the op_mode_Ardui
    int op_mode_Ardui;                        // Operator Mode of Arduino
    int returnValue1 = 12;                    // First digital return value for transmitting box weight
    int returnValue2 = 13;                    // Second digital return value for transmitting box weight

    int sensorPin = A0;                       // Select the input pin for the potentiometer
    long weightValue = 0;                     // Variable to store the value from the sensor
    long calibrationValue = 0;                // Value which is filled in calibration progress
    int numValues = 50;                       // Number of taken values for calculating an average
    int thresBoxWeight = 300;                 // Weight for separating heavy and light boxes

    unsigned long sumOfValues;                // Sum of the taken values
    unsigned long aveOfValues;                // Average of the values

    char stringBuffer[30];                    // Buffer for combining string and variables

    void setup() {
      // Initiate serial communication to screen
      Serial.begin(9600);

      // Initiate some variables
      //weightValue = 0;
      //calibrationValue = 0;
      //numValues = 50;
      //thresBoxWeight = 300;

      // Set the Input Pins for op_mode_Ardui
      pinMode(op_mode_Pin, INPUT);            // sets the digital pin 7 as input

      // Set the Output Pins for Box declaration
      pinMode(returnValue1, OUTPUT);          // sets the digital pin 12 as output
      pinMode(returnValue2, OUTPUT);          // sets the digital pin 13 as output

    }

    void loop() {
      Serial.println(analogRead(sensorPin));
      Serial.println(calibrationValue);
      // Reset of Sum and Average variables for next cycle
      sumOfValues = 0;
      aveOfValues = 0;
      op_mode_Ardui = digitalRead(op_mode_Pin);

      if (op_mode_Ardui == HIGH){
        for (int i=0; i<numValues; i++){
          weightValue = analogRead(sensorPin);                                                  // read the value from the sensor
          sumOfValues = sumOfValues + weightValue;                                              // Build the sum of all values
        }
        Serial.println(sumOfValues);
        Serial.println(numValues);

        calibrationValue = sumOfValues / numValues;
        sprintf(stringBuffer, "Calibration accomplished with value: %d", calibrationValue);     // Combine text and variable to output
        Serial.println(stringBuffer);                                                           // print text and variable to screen
        delay(3000);
      }
    }

This:
sprintf(stringBuffer, "Calibration accomplished with value: %d", calibrationValue);

is a buffer overflow: the function sprintf() is writing a 40-byte
string into a 30-byte buffer. Whatever happens to lie in memory right
after the buffer will be overwritten by sprintf(). Apparently this
happened to be calibrationValue. You should use
snprintf() rather that sprintf(), as the former is designed to
prevent this kind of overflows.
Or better yet, stick with Serial.print[ln]():
Serial.print("Calibration accomplished with value: ");
Serial.println(calibrationValue);

Edit: You may notice that 13108 is the same as 0x3334, which on a
little endian architecture is stored in memory as 0x34 0x33. These are
the ASCII codes for "43", which is part of what sprintf() wrote past
the end of the buffer.


How do I set Grove GPS to use A-GPS? I am using a grove GPS http://www.seeedstudio.com/wiki/Grove_-_GPS

I attached the GPS to Serial1 of Arduino Mega 2560.

The baudrate of the GPS is set to 9600.

Library wise, I am using TinyGps to parse the GPS data.

The GPS receiver can only get a valid data if it can see a clear sky.

I read uBlox documentation and it states that I can use A-GPS.

So, my question is, how do I actually set the Grove GPS that is attached to my Mega, to use A-GPS?

A-GPS uses a network connection to download GPS almanac and ephemeris data to enable satellites to be located faster. Otherwise the GPS device has to wait for the data to be sent by a satellite, which may take up to 12.5 minutes. Alternatively, the GPS device can send noise GPS data to an assistance server which will process it and send back a fix.

A-GPS requires a network connection to an A-GPS server. You can't just 'turn it on'. There are some modules out there that combine GPS with a 3G modem which do A-GPS automatically.


Accessing configuration registers of OV7670 cam on i2c I am a new user of Aurdino and want to interface OV7670 camera with aurdino uno which uses i2c mode of communication.I want to check the configuration of the device control registers and set them as per requirement. In this case, OV7670 is my slave device.
     How can I access a particular register inside the slave device?(The parameters for commands like wire.begin() etc., include slave address but not the address of the registers inside a slave device.)

To communicate with the OV7670:

SIOC => SCL
(pulled up to 3.3V)
SIOD => SDA
(pulled up to 3.3V)
RESET => 3.3V
PWDN => GND
XCLK => Clock signal is necessary (at least 10 Mhz)
Vcc => 3.3V
GND => GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its timer0; check out this post on how to do it. After this, you can write a small sketch along the lines of:

Wire.begin();
Wire.beginTransmission(0x21);
Wire.write(0x12);  // software reset
Wire.write(0x80);
Wire.endTransmission();
delay(500); // wait for reset to complete

Wire.beginTransmission(0x21);
Wire.write(0x01);  // u now read from reg 0x01
Wire.endTransmission();
Wire.requestFrom(0x21, 1);
while (Wire.available() == 0);  //block till u get something
while (Wire.available())
  Serial.println(Wire.read(), HEX);

You can place everything in setup() after including the Wire library and setting up the XCLK clock signal. If all goes well, 80 should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.

I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.