texts:
I'm building a scale which reads a value (from a load cell) and outputs it on a LED screen.

There is a function for the scale, read which will read the value from the scale.
However this is not instantaneous - it uses the yield function to wait until the scale is ready.

The LED screen has a function, display which will display an integer on the screen with no delay. However, this lasts barely a fraction of a second, so it must be repeatedly called.

These functions as is are called one after another inside loop(), but it causes only a quick flash of the LED screen followed by a half second of reading.

How would I allow the LED screen to keep displaying a value while the scale reads? I know there's BlinkWithoutDelay - but I'm not using specific times. There is no instance of the function delay anywhere in the program. I also am not going to edit the library which reads the load cell.


texts: I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.


texts: how to send large strings (> 100 characters) from arduino serial monitor

texts:
I am a newbie to arduino programming. I wish to send big strings which are in range of 100 to 1000 characters to my arduino uno. I saw that arduino cannot read more than 63 characters at a time.

The strings can be received in parts (~40 characters) which will be processed by my program and few minutes later they will get deleted. Then another ~40 characters will be received and the process continues till all the characters are received.

Can you please help me with this. If the question is not clear, you're free to ask in the comments. Thanks in advance :-)


texts: Native function name w/o parens -- expected behavior?

texts:
I wrote a sketch that used the millis() function in several places. I got odd behavior because I inadvertently used the plain millis in one line, without the parens. It evaluated to zero when running.

Why didn't the compiler flag this as an undeclared variable? I suspect it's because the name was already in the symbol table, but I still would have thought it'd be caught. Is this a quirk, or expected? If expected, what is the benefit?

C/C++ is not my main language so be gentle. (-:

Edit as requested to show some code. This is an incomplete sample, but shows the usage:

const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
...
unsigned long gateStopTime = 0;
...

  if (isGateCycling) {                 // if open/close cycle is running
    if (isGatePassive) {               // if we're not applying power
      if (millis() >= gateStopTime) {  // if current delay expired
        digitalWrite(GateCloseRelay, ACTIVE);
        gateStopTime = millis() + GATE_CLOSE_TIMER;
        isGatePassive = false;

... followed by similar logic for the reverse direction. If any use of millis() is replaced by millis, the code falls over but the compiler sees nothing wrong.


texts: How to interpret Serial data received by Bluetooth module

texts:
I'm experimenting with a hc-05 knockoff the JDY-30 and am confused about the Serial data I'm getting from it. I downloaded an app called BlueUino to send commands from my Android to my Arduino Uno via Bluetooth. I then print the data I get via Serial port using the code below:
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = '1'; //Serial.read(); // Reads the data from the serial port0
    stateData = Serial.read();
    sprintf(data, "Data is %u", stateData);
    Serial.println(data);
    Serial.println();
 }

Here are some of the results I get in the log which I can't make sense of. For example, sending the string "def" doesn't contain the sequence of data from sending the command "e". Also, how does one convert these values to characters ?
Send Command "b"
Data is 128
Data is 0
Data is 248

Send Command "abc":
Data is 120 // doesn't contain the sequence of Data of "b"
Data is 120
Data is 120
Data is 0
Data is 120
Data is 0
Data is 248


texts: string.charAt() is not returning the correct value

texts:
I know this is a super basic question, and I did try debugging, but somehow I think I am missing the way variable stores value in Arduino.

int enablePin = 2; // ebanble pin for slave

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

bool tx_master = false;
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // setup enable pin for slave (always low)
  pinMode(enablePin, OUTPUT);
  delay(10);
  digitalWrite(enablePin, LOW);
  // set digital pin 8 - 11 for output
  for (int i = 8; i < 12; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    // make sure this message for slave "A"
      Serial.println("PRINT LOCAL VARIABLE");
      String akshay = "2AKSHA";
      Serial.println(akshay.charAt(0));
      Serial.println(inputString);
      Serial.println(inputString.charAt(0));
    if (inputString.charAt(0) == '2') { // check if message for SLAVE 1
      Serial.println("MESSAGE FOR SLAVE 2");
      Serial.println(inputString);
      tx_master = true;
      for (int i = 1; i < 5 ; i++) {
        if (inputString.charAt(i) == '1')
          digitalWrite(7 + i, HIGH);
        else
          digitalWrite(7 + i, LOW);
      }
    } else {
      Serial.println("MESSAGE NOT FOR SLAVE");
      Serial.println(inputString);
      Serial.println(inputString.charAt(0));
    }
    if(tx_master == true) // IS MESSAGE FOR SLAVE 1 TRANSMIT SAME MESSAGE TO MASTER.
    // clear the string:
    {
      Serial.println(inputString);
      inputString = "";
      tx_master = false;
    }
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      Serial.println(inputString);
      stringComplete = true;
    }
  }
}

Now in this program i have these 2 lines String akshay = "2AKSHA";        Serial.println(akshay.charAt(0));  which give me output as "2AKSHA" and "2"
Now the next 2 lines Serial.println(inputString); Serial.println(inputString.charAt(0)); does same thing here inputString value is "2AKSHA" but here my output is "2AKSHA" and "S"

Now i am not sure why charAt(0) gives me "S" for global variable and not for local variable.

Other solution i tried -

I tried to use substring(0,1) it returned same "S"
Assigned inputString to local variable and tried to get charAt it returned "S"
Thought there could be space so did trim but still same "S"
Tried to get IndexOf but same result.


texts: Home made drum kit - How can I speed up the response time after my sensor gets triggered?

texts:
I am trying to make a psudo drum kit with my Arduino Due and a couple Force Sensitive Resistors (activated with my fingers, no drum sticks). So far in my testing I'm only using one FSR. I've attached an SD Card reader and put a WAV File on there (44100 Hz, 16-bit, stereo). In my 'Loop', I read in the resistance of the FSR to know if it's been triggered, then I play the WAV file accordingly. It works but its not that fast. If this project is going to work, the response time needs to be much faster.

Here's my code:

#include "SD.h" //Lib to read SD card
#include "SPI.h" //SPI lib for SD card
#include <Audio.h>

#define SD_ChipSelectPin 2

const int FSR_PIN = A0; // Pin connected to FSR/resistor divider

const float VCC = 4.875;
const float R_DIV = 10000.0;

void setup()
{
  Serial.println("Starting Drum Kit!");
  Serial.begin(9600);
  while (!Serial) {}

  pinMode(FSR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  Serial.print("Initializing SD Card...");
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("FAILED!");
    while(true);
  }
  Serial.println("done");

  // 44100kHz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);

  void loop()
{
  File snare_file;
  short snare_buffer[1024];
  int fsrADC = analogRead(FSR_PIN);
  if (fsrADC > 20) // If the analog reading is non-zero
  {
    Serial.println(String(fsrADC));

    snare_file = SD.open("606snare.wav");
    while (snare_file.available()) {
      snare_file.read(snare_buffer, 1024);
      Audio.prepare(snare_buffer, 1024, 1024);
      Audio.write(snare_buffer, 1024);
    }
    snare_file.close();
  }
}

If I hold down the sensor (constant triggering), the fastest that the file plays is about every half second. Here's the Serial output:

15:12:28.453 -> Initializing SD Card...done
15:12:28.487 -> 1023
15:12:28.930 -> 1023
15:12:29.510 -> 1023
15:12:30.050 -> 1023
15:12:30.628 -> 1023
15:12:31.136 -> 1023
15:12:31.744 -> 1023
15:12:32.328 -> 1023
15:12:32.834 -> 1023
15:12:33.411 -> 1023
15:12:33.955 -> 1023

I've tried playing around with loading the file and buffer in the setup section but I can't get it to work properly. There's not a whole lot of documentation on the Audio library either.

If you know of a better way to speed this up, or if I should be using a different library, please let me know.


texts: Arduino : send data via satellite (or other solutions ? without GSM)

texts:
I'm a researcher and I'm looking to build a very tiny embedded system. I must to send data from the desert and above the ocean, to do that I think that my single option is to use satellite transmission (and not GSM).
Thus, I found Iridium Satellite (RockBLOCK) but my main issue is that their Arduino module is too big for my project (4cm of length and too heavy).
Do you know if there is other module to send data via satellite with Arduino ?
If not, do you know other microcontroller which can do that ? (Using Arduino is not mandatory for me)
Thank you a lot,
Sincerely.


texts: What is the use of ISP and ICSP in Arduino?

texts: I am trying to connect gsm module with my arduino uno. confused about the use of isp and icsp


texts:
I'm looking at the little code snippet from this (many other projects also use similar code):

void loop(){
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 ax = map(ax, -17000, 17000, -1500, 1500);
 ...

If my reading is correct, it's assuming the value of ax to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?

Any thought appreciated.


texts:
I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.

int motorPin = A0;
int blinkPin = 13;

int watertime = 300000; // how long to water in miliseconds
int waittime = 3600000; // how long to wait between watering

void setup() {
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    delay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    delay(waittime);
}

Changed int to:

#define watertime 300000
#define waittime 3600000

But it does not work.


texts: Arduino code issue (using Bluetooth and Rfid technology)

texts:
I am building a device that communicates with my Android phone.
I know that my App works but my Arduino code seems to have a problem.
So I have made a smaller programm and everything works fine there.

SMALLER PROGRAM - THAT WORKS

#include <SoftwareSerial.h>

SoftwareSerial btSerial(8,9); // RX, TX

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

void loop() {
  //Send everything from PC-Console
  while( Serial.available() )
  {
     btSerial.write( Serial.read() );
  }

  //Show everything received with bluetooth to PC-Console
  if(btSerial.available())
  {
    while(btSerial.available())
          Serial.write((char)btSerial.read());

    Serial.println("");
  }
}

I thought everything is fine so I've changed a few things in my original code.
But still the Arduino receives nothing, sending is no problem.

ORIGINAL PROGRAM - PROBLEM

#include <SoftwareSerial.h>

SoftwareSerial btSerial(8, 9); //RX TX
SoftwareSerial rfidSerial(11, 12);

char tagCollection4][13] = { {"6A003D68AA95"},
                             {"6A003D8879A6"},
                             {"6A003D49617F"},
                             {"6A003A426775"} };

String tagCollection_str[4] = {"6A003D68AA95",
                               "6A003D8879A6",
                               "6A003D49617F",
                               "6A003A426775"};

bool tagsFound[4] = {false, false, false, false};

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

void loop() {

 //Send everything from PC-Console to Bluetooth device | that part works
  while( Serial.available()  )
  {
    btSerial.write( Serial.read() );
  }

  //Show everything received with Bluetooth device on my PC-Console
  if( btSerial.available() )
  {
     while(btSerial.available())
              Serial.write((char)btSerial.read());

    Serial.println("");
  }

  //Here starts the Rfid Part that I’ve done first it works mostly
  char tagString[13];
  int index = 0;
  boolean reading = false;

  if(rfidSerial.available() )
  {
    while( rfidSerial.available() )
    {
      int readByte = rfidSerial.read(); //read next available byte

      if(readByte == 2) reading = true; //begining of tag
      if(readByte == 3) reading = false; //end of tag

      if(reading && readByte != 2 && readByte != 10 && readByte != 13){
        //store the tag
        tagString[index] = readByte;
        index ++;
      }
    }

    delay(50);
  }

  checkTag(tagString);
  clearTag(tagString); //Clear the char of all value
*/
}

void checkTag( char tag[] )
{
  if(strlen(tag) == 0) {return;}

  int tagNum = compareTag( tag );

  if( tagNum == -1 )
  {
    Serial.println("");
    Serial.println("NO MATCH");
    Serial.println("");
  }
  else
  {
   if( !tagsFound[tagNum] )
   {
      tagsFound[tagNum] = true;
   }
   else
   {
     tagsFound[tagNum] = false;
   }
   //Just a little delay
   delay(2000);
  }

  //Show the scanned tag
  Serial.println("");
  for( int i=0; i<13; i++ )
  {
   Serial.write(tag[i]);
  }

  Serial.println("");

  for(int i=0; i<4; i++)
  {
      Serial.println( tagsFound[i] );
  }

  Serial.println("");
  Serial.println("");

}

int compareTag( String tag )
{

  if(tag[9] == tagCollection4[0][9])
      return 0;

  if(tag[9] == tagCollection4[1][9])
      return 1;

 if(tag[9] == tagCollection4[2][9])
      return 2;

  if(tag[9] == tagCollection4[3][9])
      return 3;

  return -1;
}

void clearTag(char one[]){
///////////////////////////////////
//clear the char array by filling with null - ASCII 0
//Will think same tag has been read otherwise
///////////////////////////////////
  for(int i = 0; i < strlen(one); i++){
    one[i] = 0;
  }
}

Please help me, it's for a school project.

Thanks for everything in advance.


texts:
While this was seemingly answered in another forum question, the answer given of using an alternative library of...  #define HARDWARE_TYPE MD_MAX72XX::FC16_HW  was tested and resulted in a worse situation of totally jumbled display with nothing meaningful displayed (no actual letters or numbers).  When using MD_MAX72xx.h library the text is displayed but is mirrored  e.g. letters are displayed backwards.
I'm using the latest downloads of MD_Parola and MD MAX72XX downloads yesterday.

I'm at a total loss as what to do to reverse the letters. Can anyone help please in simple terms, as I'm still very much a novice and on a steep learning curve with Arduino!

Thank you.

Sorry for the delay in replying.
I'm totally unsure where to add the line suggested in the MD_MAX72xx.h file?? (Said I was a novice!!).

The library file is just the basic MD_MAX72xx.h as downloaded. The other files being used are MD_Parola.h and SPI.h

This is a video of what is happening and what needs correcting .. [1]: https://youtu.be/LVuyTmeNFQ8 It will be removed from YT in a few days

I'm unable to paste the files details here as it exceeds the 30000  character limit


texts: If-statement matches but doesn't give a result

texts:
I just started two weeks ago with Arduino and I'm hooked!

I got off to a good start and went through some online tutorials quite easily. Then came the RGB LED, which I couldn't get to work all of a sudden (it required putting in a color through the serial monitor, which would then be given by the RGB).

And the strange thing is, I can't get anything to work anymore that requires input through the serial monitor, where I used to get it working immediately...

I presume it's something with the if-statement, because if I remove it and just say digitalwrite HIGH to a certain pin, it works fine....

Checks I did:

Full re-install of Arduino (didn't solve it).
Check the LEDs by hooking them up to 5V directly (they all work).
Reconnecting the Arduino (didn't solve it).
Use a multimeter to measure current (there isn't, although the if-statement matches...

Here's my code. Does anybody see it? Because I don't...

Regards,

nannev (using Mac and Arduino Uno)

int yellowPin=8;
int redPin=9;
int greenPin=10;
String myLED;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
}

void loop() {
  Serial.println("Your color?");
  while (Serial.available()==0) {
  }

  myLED=Serial.readString();
  Serial.print(myLED); //check if the input came through correctly, which it did
  delay(1000);
  if(myLED == "yellow"){ .    //nothing happens at yellow....
    digitalWrite(yellowPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "red"){             //nothing happens at red....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "green"){       //nothing happens at green....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
  }
}


texts: Trying to control DC motor speed with PID

texts:
i'm trying to control a DC motor with PID. I have already made a code where i control the motor with an ultrasonic sensor (for distance) but now i need to run the motor at a given RPM (the Output). I did a lot of resarch and found that i will have to use the PID Library. But with my existing code i'm not sure if it's going to work. I know that i will have to modify PWM values by the Input on the analogWrite(). Can you enlight me on this PID? Here is my code:

int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);
  Serial.println(distancefonction(dt,distance));

  if (distancefonction(dt,distance)<15 && distancefonction(dt,distance)>7){
    slowdown();}
}

int distancefonction(int dt, int distance) //function to show distance

void slowdown(){
  for(int i=255;i>=0;--i){
      analogWrite(enableBridgePin,i);
      delay(10);}
   Serial.println("SLOWDOWN");
}


texts: Arduino EEPROM retains old data after flashing with a new program

texts:
I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the eeprom_clear program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.

I did some digging and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?


texts: arduino mega number of simultaneous pulse inputs

texts:
I'm looking at this specification page:

http://arduino.cc/en/Main/ArduinoBoardMega2560

It says there are 54 digital input pins. How many of those can be used at the same time to measure pulse input frequency? I've seen examples of a couple pins being used at the same time, but can it handle measuring frequency on say 12 pins at the same time?

Also I am looking at this bluetooth shield:

http://redbearlab.com/bleshield/

Would there be a limit on the number of simultaneous frequency measuring pulse pins when then this is added?

Currently I use an IOIO board and can monitor 9 pulseInput pins (at least it seems like it is simultaneous, but probably not, it has a PIC24FJ256GB206 microcontroller that has 9 input capture modules when used as single precision.) It works well with my around 15-30 Hz signals updated every 250 milliseconds. I'm wanting to move it to arduino for supported connectivity to many other devices. What are the capabilities of the arduino mega?


texts: How do I make my LCD screen scroll text while allowing for button input?

texts:
Here's what I want my code to do: This is part of a tea infusing project that would automate the steeping of tea, part of this is initially having a selection of either Black/Herbal tea or White/Green tea, this will then set off several other factors down the timeline.
I want my LCD screen to display and scroll "Please select a tea" while still being able to take in pushbutton input.
I've been doing this all day, and I've tried several things. I firstly tried using a normal delay function so my text could scroll properly, but the problem with that is that it halts all the code and doesn't allow for any other input, so I quickly found millis() was likely what I needed to use. However, when I try to apply it to this specific example, it just scrolls all my text extremely quickly through the LCD.
Perhaps I'm being stupid and ignoring something obvious, but please let me know.

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);

const int black_herbal_osb = 2;

int black_select;

//Timing
unsigned long prev_millis;
unsigned long current_millis;
const unsigned long LCD_delay = 500;

void setup() {

  //Tea selection buttons
  pinMode(black_herbal_osb, INPUT);

  //LCD screen setup
  lcd.init();
  lcd.backlight();

}

void loop() {

  lcd.autoscroll();
  lcd.setCursor(16, 0);
  lcd.print("Please");

  current_millis = millis();

  black_select = digitalRead(black_herbal_osb);

  if (black_select != HIGH) {

    if (current_millis - prev_millis >= LCD_delay) {
      lcd.print(" select ");
      prev_millis = current_millis;
    }
    if (current_millis - prev_millis >= LCD_delay * 2) {
      lcd.print("a ");
      prev_millis = current_millis;
    }
    if (current_millis - prev_millis >= LCD_delay * 3) {
      lcd.print("tea ");
      prev_millis = current_millis;
    }
  }

  else if (black_select == HIGH) {
    lcd.clear();
    lcd.autoscroll();
    lcd.setCursor(16, 0);
    lcd.print("Black/Herbal ");
    delay(500);
    lcd.print("tea ");
    delay(500);
    lcd.print("selected");
    delay(2000);
    lcd.noAutoscroll();
    lcd.clear();
  }

}


texts:
I have a small project with arduino UNO R3 + RTC clock DS3231, that control through a relay a electrovalve (12V).

I would like to use the entire circuit on battery.

The electrovalve (a small motor) has a consumption of 500mA and will be active 4 times a day for 15 second.

I have a 7Ah battery, and I had calculated that my system will work only around 34 hours with it... is there any way to optimize circuit consumption ?

Thanks for any suggestion !


texts: AVR timer overflow interrupt not working

texts:
My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:

void timer0_init( void )
{
    cli();
    TCCR0B |= 3;    //clock select is divided by 64.
    TCCR0A |= 2;    //sets mode to CTC
    OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
    TIMSK |= 2;     //Enable overflow interrupt
    sei();          //enable global interrupts
}

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.

ISR(TIMER0_OVF_vect)
{
    cli();
    //ticks ++;
    PORTB |= ( 1 << PORTB0 );
    sei();
}

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with PORTB |= ( 1 << PORTB0 ); which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement PORTB |= ( 1 << PORTB0 ); in my infinite loop and confirmed the LED came on)

For further explanation, here is my main.c:

/*================================= main.c =================================*/

#define F_CPU   8000000UL

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

#include "timer.h"
#include "hardwareInit.h"

int main(){

    //Initialize hardware HERE
    DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

    SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

    timer0_init();          //set up timer0 for 1 ms overflow

    while(1)
    {
        /* if( getTicks() > 0 )
        {
            PORTB |= ( 1 << PORTB0 );
            _delay_ms(1000);
            PORTB &= ~( 1 << PORTB0 );
            _delay_ms(1000);
        } */

    }
    return 0;
}

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.

Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.


texts: Is there a way for me to read the pin mode for one of the digital pins on Arduino?   In other words, can I determine whether a pin's been set to an input or output?


texts: Ardutester Millenium I2c Lcd Not Showing Anything!

texts:
Hiii Friends....,
I am Trying to Build Components tester Using Arduino Specifically Atmega328p Chip .
I Downloaded The Ardutester Millenium Code From Here ..  https://create.arduino.cc/projecthub/plouc68000/ardutester-millenium-the-ultimate-uno-mega-versions-c81db4
Edited Makefile.h By Enabling i2c lcd Interface And Adding My I2c Lcd Adress ...   But it wont work
I tried On Uno And Mega Also Serial Monitor Output seems ok But It Doesnt Display anything on 16*2 lcd
Thanks ...... :)

Code is available at that page sir...
Thanks for your reply


texts: >=500Mhz microcontroller that works with arduino sketches?

texts:
I'm looking for a decently beefier arduino, but from what I can tell by using google the best I can get is up to 80mhz clock speed. I need something closer to or higher than 500 with more ram, I found the Intel Edison but it runs linux, what I'm looking for is something that is bare metal like the arduino.
I need the higher clock rate for faster calculations and more ram for storing vertex information for a 3D renderer.
Thanks for your help everybody.


texts:
I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.

Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link
https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino

So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.

I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.


texts: Powering the Arduino with a battery and reading the battery voltage

texts:
I am trying to display the battery level as it is being used to power the arduino.

I have tried powering the arduino through the USB and the battery voltage is read accurately, when compared to the multimeter reading.
But when the battery is powering the arduino and being read, it keeps displaying 5.00V, when it should not be.

Just wondering what might be happening and how I can go about resolving this issue.

I have been trying to research some answers, and came across something about an 1.1V reference voltage, but not entirely sure what they mean.

Would appreciate any answers!
Thanks!

Here is my code for reference.

#include <SoftwareSerial.h>
SoftwareSerial BTserial(10,11);

int battPin = A1;

void setup() {
  pinMode(battPin, INPUT);
  BTserial.begin(9600);
  Serial.begin(9600);
}
void loop()
{
  int voltReading = analogRead(battPin);
  float volts = (voltReading/204.6);
  BTserial.print(volts);
  BTserial.print(";");
  Serial.println(volts);
}

I am using a 3.7V Lipo battery. It is connected to A1 and also Vin.


texts: How can I filter out noise from ADC lines without delay or signal change?

texts: I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. How can I filter noise out of the signals?


texts: Nano clone not working over USB, no data, no power, but can power via Vin (CH340 chip? schottky diode?)

texts:
My quite new Nano clone (ATmega328P + CH340G) suddenly stopped working. Plugging it in with USB did not light up the LED(s) nor did it get detected by my machine. I looked it up, and found some how-to's (such as this one: Repair Arduino Nano (no power on USB)), which suggested at least some diagnostics.

So I plugged the Nano in to a 5V breadboard power source using the Vin and GND pins, and the power LED lights up, but connecting via USB cable to my machine does not detect it.

So then I used some of the methods mentioned in the link, and used just a normal jumper cable (without soldering) to check if that could magically make it detectable by my machine. No luck. I tried bypassing the voltage regulator by "jumping" over it, and the power LED gets brighter, and "pin 13" LED flashes for just an instant. The same occurs if I "jump" the voltage regulator all the way to either end of what I am guessing is the "Schottky diode".

In all cases, still nothing in terms of being detected by my computer. The cable is fine because I tested with another nano clone, and it gets detected right away.

So, how do I properly diagnose what is going on here? Specifically how do I fix my poor board? How do I find which component is in need of replacing?

Update:

I found some online guides on how to have another Arduino board talk to this one over SoftwareSerial and found that I could get some data flowing through. However, the text was garbled, such that, for example if I was expecting it to say:

  "Please enter some input"

It might read instead:

  "Ulease XYZter some [][]put"

Often with the same characters being garbled in the same way. I tested the Schottky diode the way it was suggested in the video (with some guessing as to the multimeter setting I had to use was, since I have a different model than the one in the video), and it seems the diode is fine. So at this point I am guessing it is the ch340g chip that is toasty, either that, or the ATmega chip itself, which I don't know, but that sounds less likely.

So, could it be that it is the CH340G chip, since I get no power over USB, and the TX/RX over serial is being interfered with? Is there anything else I can do to figure out if it is the CH340G that's damaged before I go about trying to replace it?


texts: Decoding IR codes with IR sensor rather than IR receiver module

texts:
I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).

Is there a library that supports IR sensors?

A picture of the two possibilities can be seen here

EDIT: This isn't a duplicate of my previous post, it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen here


texts:
I have this code.

String incoming;   // for incoming serial data

void setup() {
    Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incoming = Serial.read();
            String mysrr = String(incoming);
            // say what you got:
            Serial.print("I received: ");
            Serial.println(mysrr);
    }
}

A few of you will recognise this as an Arduino example.

However, when I run it ( I sent it the message "hi"), I get this in the serial:

I received: 104
I received: 105

Why is this happening?


texts: Attiny85 Timer 1 comparator B doesn't work properly (while A does)

texts:
I'm writing a simple program that is using Timer 1 comparator B to generate a square wave on DEBUG_PIN.

So my code at first turns on timer 1 with prescaler 8192 so that one tick is approximately 1ms. Then , when timer reaches up to 100 I turn off all timers, than enable timer1 compB and drive DEBUG_PIN high. When timer1B interrupt occurs, then it drives DEBUG_PIN low and disables TIMER1B interrupts.

The problem is that whenever I run the code, DEBUG_PIN state is always high. Here is the strange thing: when I change comparator from B to A on the same timer, everything works fine!
Here is the code:

#include "avr/interrupt.h"

#define DEBUG_PIN 4

volatile bool flag = false;
volatile int counter = 0;

ISR (TIMER1_COMPB_vect){
  digitalWrite( DEBUG_PIN, LOW );
  bitClear(TIMSK, OCIE1B);
}

void setup() {
  cli();

  pinMode( DEBUG_PIN, OUTPUT );

  digitalWrite( DEBUG_PIN, HIGH );
  //stop TIMER1
  TCCR1 = 0;
  //prescaler is 8192 sot that 1 tick is 1ms, enable timer1
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
  sei();
}

void loop() {

    if( TCNT1 >=100 ){
      cli();
      counter = 0;
      //disable compB
      bitClear(TIMSK, OCIE1B);

      digitalWrite( DEBUG_PIN, HIGH );

      /* enable compB */
      //set comparatorB value
      OCR1B = 70;
      //enable compA interrupts
      bitSet(TIMSK, OCIE1B);

      TCCR1 = 0 ;

      TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

      TCNT1 = 0;

      //reset OCF1A interrupt flag, just in case
      bitSet(TIFR,OCF1B);
      sei();
    }
}

Does anybody has any idea where this comes from?!?!


texts:
So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.

Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?

//------------------------------------------------------------------------------------------------
// Displays information when a push button is pressed. Also turns on and off a corresponding led.
// 5/3/2016
//------------------------------------------------------------------------------------------------

// declare variables

char* titles[] = {
  "RELATION",
  "FIRST NAME",
  "LAST NAME",
  "LOCATION",
  "PHONE NUMBER"
};
char* user_info[] = {
  "SELF",
  "JOHN",
  "SMITH",
  "FLORIDA",
  "999-888-6666"
};
char* econ_one[] = {
  "BROTHER",
  "MICHAEL",
  "SMITH",
  "FLORIDA",
  "999-888-5555"
};
char* econ_two[] = {
  "WIFE",
  "EMILY",
  "SMITH",
  "FLORIDA",
  "999-888-4444"
};
char* econ_three[] = {
  "SISTER",
  "SOPHIA",
  "ADAMS",
  "NEW YORK",
  "888-777-3333"
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
// setup - set pins

void setup() {
  Serial.begin(9600);
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("Emergency Contact");
}

// main
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      int x;
      for (x = 0; x <= 4; x++) {
        Serial.println(" ");
        Serial.print(titles[x]);
        Serial.print(" ");
        Serial.print(user_info[x]);
      }
      Serial.println(" ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      int y;
      for (y = 0; y <= 4; y++) {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econ_one[y]);
      }
      Serial.println(" ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;
    } else if (state == 2) {
      int z;
      for (z = 0; z <= 4; z++) {
        Serial.println(" ");
        Serial.print(titles[z]);
        Serial.print(" ");
        Serial.print(econ_two[z]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      int q;
      for (q = 0; q <= 4; q++) {
        Serial.println(" ");
        Serial.print(titles[q]);
        Serial.print(" ");
        Serial.print(econ_three[q]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

// function to turn LEDs on/off

void setLights(int one, int two, int three, int four) {
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

output image

https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU_X0bl04KXFAQyja


texts: Not able to convert String to Integer when receiving data from pubnub?

texts:
I did managed to upload mpu9250 sensor data on PubNub and nodeMcu but not able to use the received data to control servo

Look at the Port reading and see that servo angle is still showing '0'

Code:-

IMU.readSensor();
char buf[500] = {};
int imu = IMU.getAccelX_mss() * 10;

sprintf(buf, "\"%d\"", imu);

Serial.print(buf);

PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);
if (!pclient) return;
PublishCracker cheez;
cheez.read_and_parse(pclient);

/** You're mostly interested in `outcome()`, and,
    if it's "failed", then `description()`.
*/

Serial.print("Outcome: "); Serial.print(cheez.outcome());
Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
Serial.print("description: "); Serial.println(cheez.description());
Serial.print("timestamp: "); Serial.println(cheez.timestamp());
Serial.print("state: "); Serial.print(cheez.state());
Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
Serial.print("IMU Reading: "); Serial.println(IMU.getAccelX_mss());

pclient->stop();

/* Wait for news. */
PubSubClient *sclient = PubNub.subscribe(subchannel);
if (!sclient) return; // error
String msg;
SubscribeCracker ritz(sclient);
while (!ritz.finished()) {
    ritz.get(msg);
    if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);
    }

}
sclient->stop();

delay(1000);

How do I convert a string to integer so that it can be used in servo?


texts: How to make a clap switch fan using an Arduino

texts:
I am a beginner in working with Arduino. I am having trouble with making a clap switch fan using Arduino.
The clap switch works with an LED, but when I connect a 5V fan using a relay, the fan doesn't move.
Please try to find a solution for this.
I used this code and instead of an LED I used a fan:
void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
}

void loop() {
  int analog_val;
  static bool led_state = false;

  analog_val = analogRead(A2);

  if (analog_val > 10) {
    if (led_state) {
      led_state = false;
      digitalWrite(2, LOW);
      Serial.println(analog_val);
    }
    else {
      led_state = true;
      digitalWrite(2, HIGH);
      Serial.println(analog_val);
    }
    delay(50);
  }
}


texts:
I have a simple flashing led program that I want to upload on my pro micro (see image) but it doesnt work (see image: no port available, Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.)

I have successfully uploaded this program on my arduino uno.

Ive followed this guide for the drivers and more.
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows

Thanks for help


texts: Reset arduino nano after disabling tx/rx

texts:
I know, i am a bit dummy sometimes and i don't know why i actually did this but here it is. I have an arduino nano and i want it to use an external power via the the Vin port using a 12V external power supply. I thought this would be as simple as replacing the usb power supply by my external 12V power supply on the Vin pin.
But nothing works so i did some digging on the problem and after many tries like soldering the pins 25 and 26 of the FTDI or connect the TX/RX pins to the GND. Concerning that last point, because the TX/RX was still flashing after beeing connected to the GND i have put in my program this two lines to force TX/RX to be disabled and this is my mistake :

digitalWrite(0,LOW);
digitalWrite(1,LOW);

And now what a surprise i can't load a program in my arduino nano anymore even using another arduino to burn the bootloader. And i get this message :

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x38
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x31

I would like to come back to my factory arduino nano and/or enable once again the TX/RX connections ...


texts: Is it safe to use the same power source for Arduino and its Motor shield?

texts:
Is it safe to use a unique 12V 5A DC power source to feed both Arduino and its connected Motor shield, provided that

the motor (connected to the shield) will eat 3A maximum
the Arduino Vin will get the power

Arduino and the shield exchange information, and use both the same power supply, is there some risk of "interference" of some kind?

edit

This is the motor controller shield I intend to use. In the manual, the connections show that

the Arduino and the shield have different power supplies
the Arduino power pins are not used by the shield


texts: Brand new to Arduino, and can't even make an LED blink

texts:
So I'm going through Getting Started With Arduino. I skipped to making a LED blink when you press a button.

First I wrote the code, then I copied it directly from the .pdf I have, neither has worked.

The code is here:

// Example 02: Turn on LED while the button is pressed
const int LED = 13;   // the pin for the LED
const int BUTTON = 7; // the input pin where the
                      // pushbutton is connected
int val = 0;          // val will be used to store the state
                      // of the input pin
void setup() {
  pinMode(LED, OUTPUT);   // tell Arduino LED is an output
  pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
  val = digitalRead(BUTTON); // read input value and store it
  // check whether the input is HIGH (button pressed)
  if (val == HIGH) {
    digitalWrite(LED, HIGH); // turn LED ON
  } else {
    digitalWrite(LED, LOW);
  }
}


texts:
I have an application that is being controlled by an Arduino. At one point in the process, it needs to determine the level of vacuum in a chamber and adjust it to within a range of values.

I can control the vacuum pumps easily enough, but it is hard to find a vacuum sensor for the Arduino. I need a sensor that can be reasonably accurate down to roughly 28 inches mercury and would connect by a tube. I can't put the sensor directly into the chamber.

Does anyone know of an Arduino sensor that would work? If not, could someone suggest a sensor component that may work with an Arduino. I would prefer to not have to engineer a solution from the sensor component up but I can if I need to.


texts: Can Android phone can be used instead of( or with) Arduino as controller?

texts:
I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

phone as controller (without arduino) - this option would be the
best
if phone cannot give commands maybe with arduino, while
using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?


texts: Adding esp32_komoot_ble library to Arduino IDE

texts:
I am an absolute beginner with Arduino IDE and I want to build an interesting device I stumbled upon on github
https://github.com/jstiefel/esp32_komoot_ble
Problem is I really can not add it to Arduino IDE. I did the wiring for the lcd and all, but please bear in mind i'm an electrician, with a very basic understanding of arduino/ absolute beginner.
What i'm asking is which is  the "main file" in the src folder so i can rename it 'ino' to work with the arduino IDE  and upload it to the esp32 board?
I downloaded the esp32 library and all the dependencies that says in the readme.md file. I download the esp32_komoot_ble.zip file. Now how do I get the  .cpp and .h files on the arduino IDE and finally my esp32 device. I have been watching tutorial for 1 week now  but could not figure it out yet!
Thank you for everything guys!


texts: Print output on 16x2 LCD and Serial Monitor

texts:
I'm trying to print an int on both an LCD and the Serial Monitor, but its only being displayed on the LCD. The Serial Monitor is printing question marks.

Here is my Arduino code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int x = 10;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop()
{
  x++;
  lcd.setCursor(0, 0);
  lcd.print(x);
  Serial.print(x); // print Serial
}


texts: Unexpected negative values from abs() function inline with analogRead

texts:
When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.

int sensor = 0;
sensor = abs(analogRead(A0) - 512);

Values:

77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31

When running the (apparently) mathematically equivalent code below I get exclusively positive values.

int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);

I don't think this is an integer overflow as in this post because when I switch to long sensor = 0 I get the same negative results.

What's going on here?


texts: Problems connecting nodemcu esp8266 on my laptop

texts:
I have a new laptop and didn't run any development boards on it except some Arduino boards.
But now, I have only nodemcu esp8266 and maple mini boards and trying to connect them but I get error connection message.
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
I tried to find solutions but apparently I'm stuck here and I can't do anything.
I tried to re-flash the nodemcu with the flasher but I can't get the addresses. This is what I got:

The flashing started but can't get the AP MAC and STA MAC. I don't know what is the problem now, I used to flash it before but on my old Dell laptop. I started to think that there are some problems with usb ports of my msi gaming laptop, they are 3.0, I think that could be a problem.
The board is recognized in device manager and in Arduino IDE COM ports.
My question is how to solve this problem ?


texts:
I am working on a protection circuit with 2 raindrop sensors which would be hooked onto the arduinos 2 interrupt pins and as soon as they detect water they shut some relays off, turn a red led on and exit() the main program.

These sensors I have order are working fine as regular input pins with the following code:

// lowest and highest sensor readings:
const int sensorMin = 0;     // sensor minimum
const int sensorMax = 1024;  // sensor maximum

void setup() {
  // initialize serial communication @ 9600 baud:
  Serial.begin(9600);
}
void loop() {
  // read the sensor on analog A0:
    int sensorReading = analogRead(A0);
  // map the sensor range (four options):
  // ex: 'long int map(long int, long int, long int, long int, long int)'
    int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // range value:
  switch (range) {
 case 0:    // Sensor getting wet
    Serial.println("Flood");
    break;
 case 1:    // Sensor getting wet
    Serial.println("Rain Warning");
    break;
 case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
    Serial.println("Not Raining");
    break;
  }
  delay(1);  // delay between reads
}

I will use the digital output not the analog but this doesn't change much. For the digital the pin is up at 5V at start and will be put to LOW once water is detected by the sensor.

I using the mega right now for breadbording but micro will be the final board.

Both the mega+micro should have 2,3 as interrupt pins:

Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based   0, 1, 2, 3, 7

I have modified the following code and tried all conditions:

LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.

It doesn't respond to any (the same time as I said the pin works fine as regular input).

Here in the setup I know that I am not using

attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);

but

attachInterrupt(interruptPin, myISR, FALLING);

that is because the IDE doesn't recognize this function. Is there any problem with the code? If I understand interrupts correctly I don't even need to check for that if ( ISRRan ) to break off the while loop, once the interrupt comes in the ardu SHOULD be running my interrupt function and immediately run the protection code then abort.

byte interruptPin = 0;  // your interrupt pin
volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
byte C = 0;  // this is just the counter var for the while loop

void setup() {
 attachInterrupt(interruptPin, myISR, FALLING);
}

void myISR() {
 ISRRan = 1;
 // do other things in the ISR
}

void loop() {
 while ( C < 10 ) {
   if ( ISRRan ) {
     break;
   }
   //doing something inside the while loop
 C++;
 }
 // do other things outside of the while loop
 ISRRan = 0;  // Reset for whatever reason
}


texts: How would i add PID control to this servo motor control program. potentiometer

texts:
I have installed an AutoPID library (by ryan downing version 1.0.3) to my arduino IDE, but im not sure which parts i will have remove to get the PID to control the servo angle.

Thanks for the reply, but i know i have not used the library in the sketch but i am unsure how to combine it, i have an example code for how to use the AutoPID, i will add it below.

void setup() {
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  Serial.begin(9600);
}
void loop() {
  float a;
  float b;
  float desired_angle;
  float actual_angle;
  float error;
  float motor;
  float setpoint;

  a=analogRead(A1);
  desired_angle=map(a,0,1023,0,180);

  b=analogRead(A2);
  actual_angle=map(b,125,920,0,180);

   if ( (desired_angle>0) && (desired_angle<70) )
  {
    setpoint=50;
  }
  if ( (desired_angle>70) && (desired_angle<110) )
  {
    setpoint=90;

  }
  if ( (desired_angle>110) && (desired_angle<180) )
  {
    setpoint=130;

  }

  error=(setpoint-actual_angle);
  motor=desired_angle/270*255;

  if (error>0)
  {
    digitalWrite(5,LOW);
    analogWrite(6,motor);
  }
  if (error<0)
  {
    digitalWrite(6,LOW);
    analogWrite(5,-1*motor);
  }

  Serial.print(actual_angle);
  Serial.print(",");
  Serial.println(setpoint);

}

and here is the example code

#include <AutoPID.h>

// PID settings and gains
#define OUTPUT_MIN 0
#define OUTPUT_MAX 255
#define KP 0.12
#define KI 0.8
#define KD 0.003

// Variables
double analogReadValue, setPoint, outputVal;

// Input/output variables passed by reference, so they are updated automatically
AutoPID myPID(&analogReadValue, &setPoint, &outputVal, OUTPUT_MIN, OUTPUT_MAX, KP, KI, KD);

// Setup timeStep
void setup() {
  myPID.setTimeStep(500);
}

void loop() {
  setPoint = analogRead(A3);          // Set our desired point (read the POT)
  analogReadValue = analogRead(A1);   // Read our output voltage
  myPID.run();                        // Run the PID
  analogWrite(6, outputVal); // Write the PID result to the output
}


texts: Arduino Mega timer for reliable time recording

texts:
I'm making a slow control system using Arduino Mega. The Arduino board needs to measure temperature, magnetic field, switch on/off LEDs, and exchange messages with an external system via UART. All of the measurement data needs to be recorded in a microSD card with accurate and precise(1ms or smaller) timestamps.

At a glance the tasks seem to require a RTC. However, I'm not able to put a battery on my peripheral board due to a space limitation. Then it would make more sense that I don't use a RTC but just count time using a Arduino timer. However, I wonder if timing count with a Arduino timer is reliable.

With the combination of a RTC and Arduino timer input capture mode, one can achieve a timing resolution of 1/32k seconds. Without the RTC, Arduino timer can prescale system clock and count time. Without using AVR library, would the timestamping be accurate enough?


texts: Not able to send SMS to Mobile using GSM900A and Arduino Uno

texts:
I tried the code shown below (found here)

void setup()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+919449835011\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Test SMS -Jay\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}
void loop()
{
}

I interfaced my GSM SIM900A module to the Arduino UNO (connections - GSM Tx to Arduino Rx, GSM Rx to Arduino Tx, GSM provided with supply (12V) using external adapter, GSM gnd to Arduino gnd).

I dumped the code into Arduino and then opened the Arduino IDE serial terminal. In the serial terminal, I get AT+CMGF=1AT+CMGS="+919449835011"Test SMS -Jay\r being displayed and I am not receiving any sms to my phone. I am not sure if its a problem with the code or connections.


texts:
I defined myself a struct:
typedef struct {
  unsigned char current;
  unsigned char start;
  unsigned char target;
  unsigned long startTime;
  unsigned int duration;
} led;

I was able to initialize an instance of that like this:
led h_red = {0,0,255,0,300};

However, when I try to have them in an array:
led leds[LEDS];
leds[0] = {0,0,0,0,0};
leds[1] = {0,0,0,0,0};
leds[2] = {0,0,255,0,300};

I get this error
signal:28:1: error: 'leds' does not name a type
 leds[0] = {0,0,0,0,0};
 ^~~~
signal:29:1: error: 'leds' does not name a type
 leds[1] = {0,0,0,0,0};
 ^~~~
signal:30:1: error: 'leds' does not name a type
 leds[2] = {0,0,255,0,300};
 ^~~~

And I have no idea what I'm doing wrong here. You can see the full change here on GitHub


texts: OOP vs procedural programming on arduino

texts: It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?


texts: Atmega328p - PCB ISP pins for bootloader and sketch upload

texts:
I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.

I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.


texts:
running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds-
closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?

here is whats running:

int i=0;
int req=18;

void setup(){
Serial.begin(115200);
 DDRD = DDRD | B10000010;
 interrupts();
pinMode(req,OUTPUT);
}

void loop(){
i=1;
digitalWrite(req, HIGH);
delayMicroseconds(3); //gives 7.5 microsecond pulse?
digitalWrite(req, LOW);

while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
 delayMicroseconds(1);
 i=(i+1);}
 }


texts: Altering SoftwareSerial to transmit more than 1 byte at a time

texts:
I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.

One of the really good suggestions I have heard is to use Manchester encoding on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I assume.

Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.

size_t SoftwareSerial::write(byte* b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

//Doubtful of this loop ------------------
for(int i = 0; i < 128; i++)
{
  if (inv)
    b[i] = ~(b[i]);
}

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);
for(int j = 0; j < 128; j++)
{
  // Write each of the 8 bits
  for (long i = 8; i > 0; --i)
  {
    if (b[j] & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b[j] >>= 1;
  }
}
// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

Here is the original function.

size_t SoftwareSerial::write(uint8_t b)
{
if (_tx_delay == 0) {
  setWriteError();
  return 0;
}

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

if (inv)
  b = ~b;

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

The serial buffer can only hold 64 bytes at a time, but I am using the following code, courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.


texts: SoftwareSerial Write to return Read in Serial Monitor?

texts:
Hoping someone can help me out in my conundrum here...

I currently am testing the SoftwareSerial library out to understand how I may use it in my project.

I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.

I have written the following:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

void setup() {

  Serial.begin(1200);
  mySerial.begin(1200);
}

void loop() {

  mySerial.write('F');
  delay(100); // attempting to allow time between write and read commands

  while (mySerial.available()>0) {
  Serial.println(mySerial.read());
  }
}

The whole point is just to see 'F' return in the Serial Monitor.

The output, unfortunately, is absolutely nothing! If I omit the while(mySerial.available>0) I just get -1 's down the lines of the Serial Monitor.

Thank you in advance!


texts: Arduino's digitalWrite, precautions for direct port manipulation?

texts:
I stumbled upon this piece in digitalWrite.
I'm unsure why clearing interrupts and setting/resetting SREG is neccesary here.

Can anyone shed a light on this?

uint8_t oldSREG = SREG;
cli();

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

SREG = oldSREG;

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes *out = *out & ~bit?

And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

When speed matters, I often use the direct port manipulation, I'd like to get an idea if it's neccesary for me to include these "precautions".


texts: How can I open simultaneously 2 client socket connections with GSM shield?

texts:
How can I open simultaneously two socket connections with a GSM shield?

It seems that when I try to open the second connection, it is not opened, and additionally the first connection is closed.

Code:

#include <GSM.h>

#define PINNUMBER      ""
#define GPRS_APN       "sm2ms.movilforum.es"
#define GPRS_LOGIN     ""
#define GPRS_PASSWORD  ""

#define SERVER "www.abv.bg"    // some server
#define PORT   80              // some port

static GSM gsm;
static GPRS gprs;
static GSMClient clientControl;    // first connection
static GSMClient clientData;       // second connection

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

    Serial.println("GSM not initialized");

    while (true)
    {
        if (gsm.begin(PINNUMBER) == GSM_READY)
        {
            Serial.println("GSM initialized");

            while (true)
            {
                GSM3_NetworkStatus_t eErrorCode;

                delay(1000);

                eErrorCode = gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);
                if (eErrorCode == GPRS_READY)
                {
                    Serial.println("GPRS initialized");

                    return;
                }
                Serial.print("Not connected to GPRS, error code = ");
                Serial.println(eErrorCode, 1);
            }
        }

        Serial.println("Not connected to GSM");
        delay(1000);
    }
}

void loop()
{
    delay(1000);

    Serial.println((clientControl.connect(SERVER, PORT))
                   ? ("Connected") : ("Couldn't connect"));

    delay(1000);

    Serial.println((clientData.connect(SERVER, PORT))
                   ? ("Second connection succeeded")
                   : ("Second connection failed"));

    Serial.println("Do something here");

    // close the stuff here!!!
    for (;;);
}

The serial dumps:

GSM not initialized
GSM initialized
GPRS initialized
Connected
Second connection failed
Do something here

With other clients I don't have problem supporting two simultaneous connections. Here the first connection succeeds, the second fails.

Regards,
Boyan


texts:
I have a continuous servo motor connected to my Arduino UNO. I want it to react to the Hexadecimal code received by an Infrared remote. I want the motor to rotate once in one direction and then rotate once in the reverse direction and then stop until triggered by the remote again. At the moment, the remote will cause the the motor to rotate once in one way but then it rotates continuously in the reverse direction. Any help would be much appreciated!

#include "IRremote.h"
#include <Servo.h>

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

Servo servoMain;
IRrecv irrecv(receiver);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  servoMain.attach(10);
}

void loop()
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}

void translateIR() // takes action based on IR code received

// describing Remote IR codes
{

  switch (results.value)

  {

    case 551520375: servoMain.write(180); delay(1000); servoMain.write(0);     delay(1000); break;
    default: break;

  }

  delay(500); // Do not get immediate repeat

} //END translateIR


texts:
Im a newbie. I have a problem with displaying text in LCD (16x2). It shows incorrect message in the lcd. Here is the code and the picture that gives the wrong output : Kindly help Thank you.

#include "SIM900.h"
#include <SoftwareSerial.h>

#include "sms.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//gsm
SMSGSM sms;

int numdata;
boolean started  = false;
char smsbuffer[160]; //message
String newsms;
char n[20];
unsigned char i;
//lcd
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
int outputValue = 0;   // value output to the %
int outputValue1 = 0;   // value output to cursor

void setup()
{
  //Serial connection.
  //gsm
    lcd.begin(16, 2);

  Serial.begin(9600);

//  lcd.setCursor(0, 1);
//  lcd.clear();
//  lcd.print("   Wireless Public       via GSM"); //55 chars
//  lcd.setCursor(0, 2);
//  lcd.print("    Notice Board "); //55 chars
   Serial.println("GSM Shield testing.");
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    started = true;
  }
  else Serial.println("\nstatus=IDLE");

  //lcd
  // set up the LCD's number of columns and rows:

};

void loop()
{

  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 100);
  outputValue1 = map(sensorValue, 0, 1023, 0, 200);

  //scroll = lcd.scrollDisplayLeft();
  if (started) {
    //Read if there are messages on SIM card and print them.
    if (gsm.readSMS(smsbuffer, 160, n, 20))
    {
      //lcd
      lcd.clear();
      lcd.setCursor(0, 2);
      lcd.print("SMS Received!");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0,1);
      Serial.println(n);
      Serial.println(smsbuffer);
      lcd.print(smsbuffer);
      delay(1000);
//      lcd.clear();
    }
    delay(1000);
  }
}


texts:
i hit the forums again with my homemade fan idea, this time i got the right servo. everything works fine until i try turn up to the 2nd speed of the servo, the buttons just go mad and the response in the serial monitor is ridiculous. I press the button once, x goes to 1 the motor starts spinnin' at its lowest speed, all fine, i hit the button one more time and "x" goes mad, in the serial monitor it shows that it goes to infinte, it just adds and adds and adds and never stops. Any suggestions? I appreciate all the help you guys gave me so far and I'd really like to finish this project

Here's the code:

const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
const int motorPin = 9;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  pinMode(motorPin, OUTPUT);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int Speed1 = 50;
    int Speed2 = 100;
    int Speed3 = 200;
    int Speed4 = 0;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

     if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
             x = x + 1;
            Serial.println("on1");
            Serial.print("Speed:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x = x - 1;
            Serial.println("on2");
            Serial.print("Speed:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
      }

lastButton1State = button1State;
lastButton2State = button2State;

  if( x == 0 )
    {
      analogWrite(motorPin, Speed4);
    }

  else if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      analogWrite(motorPin, Speed1);
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
      analogWrite(motorPin, Speed2);
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
      analogWrite(motorPin, Speed3);
    }
}


texts: I'm doing a project that involves sending MPU-6050 gyroscope data via serial communication to the laptop. Is ATtiny85 micro-controller suitable for this job? Is it powerful enough to do it? I was thinking of using an Arduino nano instead. please give me your opinion.


texts: Wemos: 16x2 display doesn't show anything

texts:
I connected a 16x2 LCD display to a Arduino Uno. Then I tested a "Hello, Word" code and it works perfect.
Now I want to do the same with a Wemos D1 Mini but it doesn't work.

Here the Wemos is not connected to USB:

This os the "Hello, World" code. I needed to change the name of the pins (maybe this is the problem):

#include <LiquidCrystal.h>

const int rs = 8, en = 7, d4 = D5, d5 = D4, d6 = D3, d7 = D2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  lcd.begin(16, 2);
  lcd.print("hello, world!");
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
}

This is the result (potentiometer works perfect):


texts: Problem in Uploading through Visual Studio

texts:
This is my simple program:

int led = 13;
void setup()
{
    pinMode(led, OUTPUT);
  /* add setup code here */

}

void loop()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  /* add main program code here */

}

I tried to upload it using Visual Studio 2013 using a plugin Visual Micro for Arduino. But it resulted in this error:

Compiling 'bb' for 'Intel® Galileo Gen2'
Binary sketch size: 83,455 bytes (used 1% of a 10,000,000 byte maximum) (0.17 secs)
Compiling debug version of 'bb' for 'Intel® Galileo Gen2'
Binary sketch size: 85,056 bytes (used 1% of a 10,000,000 byte maximum) (2.81 secs)
Uploading to I/O board using 'COM3'
starting download script
Args to shell: C:\arduino-1.5.3-Intel.1.0.4/hardware/tools/x86/bin C:\Users\Shiran Abbasi\AppData\Local\V.Micro\Arduino\Builds\bb\izmir_fg/bb.elf COM3
COM PORT Abbasi\AppData\Local\V.Micro\Arduino\Builds\bb\izmir_fg/bb.elf
Converted COM Port Abbasi\AppData\Local\V.Micro\Arduino\Builds\bb\izmir_fg/bb.elf to tty port
Sending Command String to move to download if not already in download mode
Deleting existing sketch on target
Moving downloaded file to /sketch/sketch.elf on target

#!/bin/sh

echo "starting download script"
echo "Args to shell:" $*

# ARG 1: Path to lsz executable.
# ARG 2: Elf File to download
# ARG 3: COM port to use.

#path contains \ need to change all to /
path_to_exe=$1
fixed_path=${path_to_exe//\\/\/}

#COM ports are not always setup to be addressed via COM for redirect.
#/dev/ttySx are present. Howwever, COMy -> /dev/ttySx where x = y - 1

com_port_arg=$3
com_port_id=${com_port_arg/COM/}
echo "COM PORT" $com_port_id
tty_port_id=/dev/ttyS$((com_port_id-1))
C:\arduino-1.5.3-Intel.1.0.4/hardware/arduino/x86/tools/izmir/clupload_win.sh: line 20: Abbasi\AppData\Local\V.Micro\Arduino\Builds\bb\izmir_fg/bb.elf: syntax error: invalid arithmetic operator (error token is "\AppData\Local\V.Micro\Arduino\Builds\bb\izmir_fg/bb.elf")
echo "Converted COM Port" $com_port_arg "to tty port" $tty_port_id

echo "Sending Command String to move to download if not already in download mode"
echo "~sketch download" > $tty_port_id
C:\arduino-1.5.3-Intel.1.0.4/hardware/arduino/x86/tools/izmir/clupload_win.sh: line 24: $tty_port_id: ambiguous redirect

#Move the existing sketch on target.
echo "Deleting existing sketch on target"
$fixed_path/lsz.exe --escape -c "mv -f /sketch/sketch.elf /sketch/sketch.elf.old"  $tty_port_id 1>&0
C:\arduino-1.5.3-Intel.1.0.4/hardware/arduino/x86/tools/izmir/clupload_win.sh: line 28: $tty_port_id: ambiguous redirect

# Execute the target download command

#Download the file.
host_file_name=$2
$fixed_path/lsz.exe --escape --binary --overwrite $host_file_name  $tty_port_id 1>&0
C:\arduino-1.5.3-Intel.1.0.4/hardware/arduino/x86/tools/izmir/clupload_win.sh: line 34: $tty_port_id: ambiguous redirect

#mv the downloaded file to /sketch/sketch.elf
target_download_name="${host_file_name##*/}"
echo "Moving downloaded file to /sketch/sketch.elf on target"
#$fixed_path/lsz.exe --escape -c "cp sketch /sketch/sketch.elf"  $tty_port_id 1>&0
$fixed_path/lsz.exe --escape -c "mv $target_download_name /sketch/sketch.elf; chmod +x /sketch/sketch.elf"  $tty_port_id 1>&0
C:\arduino-1.5.3-Intel.1.0.4/hardware/arduino/x86/tools/izmir/clupload_win.sh: line 40: $tty_port_id: ambiguous redirect

Any help would be appreciated.


texts:
I want to make an 8*8 led matrix. I found this code on the web:

    int latchPin = 12;  //Pin connected to ST_CP of 1st 74595
    int clockPin = 13;  //Pin connected to SH_CP of 1st 74595
    int dataPin = 11;   //Pin connected to DS of 1st 74595

    int latchPin2 = 6;  //Pin connected to ST_CP of 2nd 74595
    int clockPin2 = 7;  //Pin connected to SH_CP of 2nd 74595
    int dataPin2 = 5;   //Pin connected to DS of 2nd 74595

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

      pinMode(latchPin2, OUTPUT);
      pinMode(clockPin2, OUTPUT);
      pinMode(dataPin2, OUTPUT);
    }

    void loop() {
      /************** Send HIGH to first Anode pin (16th pin) and LOW to all
      other anode pins (15, 11, 3, 10, 5, 6, 13) of LED matrix *************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin, LOW);
      //Send 0 0 0 0 0 0 0 1 (1) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 1st 74595
      shiftOut(dataPin, clockPin, MSBFIRST, 1);
      // shift out the bits:
      digitalWrite(latchPin, HIGH);

      /**************** Send LOW to the first cathode pin (4th pin) and HIGH to all
        other cathode pins (7, 2, 8, 12, 1, 14 and 9) of LED matrix *****************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin2, LOW);
      // Send 1 1 1 1 1 1 1 0 (254) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 2nd 74595
      shiftOut(dataPin2, clockPin2, MSBFIRST, 254);
      // shift out the bits:
      digitalWrite(latchPin2, HIGH);
    }

I expected this code to turn on the first LED, but when I uploaded this code nothing lights up. I checked my rows and colum connections.
Also, I want to ask if a 74hc595 can output sink current?


texts: What is the best way to attach TMP36 sensor to the copper coil?

texts:
I am very new to this site and this question may not be strictly related to Arduino, but I do small Arduino project which needs to measure the temperature of the copper coil using TMP36GZ sensor.

What is the best way to glue it to the coil for best measurements?
Shoul I use silikone or epoxy?
Should I take extra steps to ensure proper readings from the coil surface (f.ex.: using thermal paste)?


texts:
I'm trying to get telemetry data to be sent out Serial1 on the NodeMCU board.  I read that TX is (by default) mapped to pin D4.

Ultimately, there will be a Raspberry that will be listening for these messages, but I don't have it yet.  So to quickly test this, I connected an oscilloscope with Serial decoding to D4 and the GND of the probe to GND on the NodeMCU.  The problem is I'm not getting any indication of activity out D4 when I run the following code:

Serial1.begin(9600);
Serial1.printf("some text");

Am I wiring the probe correctly?  Am I missing another serial command in the sketch?

When I move to the rPI, do I GND both boards together, then write TX (D4) to RX on the rPI?


texts: Is Arduino Mega useing one buffer or multiple buffers?

texts:
So Arduino Mega has Serial, Serial1, Serial2, Serial3.

However, does those Serial lines use the same buffer? or four independent ones? i.e. are they truly receive single independently, or actually some sort of software sharing? How will that affect the coding?


texts:
Hey question is that it is possible to play MP3 file in arduino without changing it into .wav file if possible ,then your suggestions are welcome
Thanks


texts:
I want to change the output ports in a library file because I use an Arduino Mega and the file uses an arduino uno.

How to change the output ports?


texts: Arduino Digital Pins Control with ESP8266

texts:
I am currently working on my FYP. I need to control 15 servos (13 for x2 Robotic Arms + 2 for Camera) and 4 motors of my Robotic kit via webserver. I have the following options:

NodeMCU
Arduino Mega + ESP8266

Now since NodeMUC has only 10 digital pins the only option I am left with is (Arduino Mega+Esp8266).
I have used the following code to control servo on a NodeMCU.

#include <Servo.h>
#include <ESP8266WiFi.h>

Servo servo;

const char* ssid = "ssid";
const char* password = "password";
WiFiServer server(80);
void setup() {
  servo.attach(4); //or any pin

  servo.write(0);

  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  if (request.indexOf("/?30") != -1)  {
    servo.write(30);
  }

//
  if (request.indexOf("/?90") != -1)  {
    servo.write(180);

  }

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.println("

");
  client.println("<button>30</button>");
  client.println("<button>60</button>");
  client.println("<button>90</button>");
  client.println("<button>120</button>");
  client.println("<button>150</button>");
  client.println("<button>180</button>");
//  client.println("<button>Thirty Mins</button>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

My question is that the can the code written for NodeMCU be used with ESP8266 to control Arduino Digital Pins? I want the same code to be used.

PS : I don't want to use SoftwareSerial library and ATC commands.

Or some alternative to NodeMCU with same functionality as NodeMCU but with more GPIO pins.


texts: Send String to a function inside a class

texts:
I made a little class for handling menus. When creating a new instance, I pass a reference to the oled object made in main.cpp. Yet when I want to render a string using a variable, it throws an error. But I can pass a string directly to the render function with no problems. See comments in the code for what is working and what is not.

#include "Arduino.h"
#include "U8glib.h"
#pragma once

class Menu {
  U8GLIB_SSD1306_128X64& oled;

  public:
    Menu(U8GLIB_SSD1306_128X64& oled): oled(oled) {
      this->oled = oled;
    };
    void render() {
      this->oled.firstPage();
      do {
        String text = "test2";
        this->oled.setFont(u8g_font_unifont);
        this->oled.setPrintPos(0, 20);
        this->oled.drawStr(text); // not working
        this->oled.drawStr(text.c_str()); // not working
        this->oled.drawStr("works"); // works
      } while (this->oled.nextPage());
    }
  };

In the case of this->oled.drawStr(text); the error is:

error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(String&)

In case of this->oled.drawStr(text.c_str()) the error is:

error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(const char*)

How I create the instance in main.cpp:

U8GLIB_SSD1306_128X64 oled(U8G_I2C_OPT_NONE);
Menu menu(oled);
menu.render();


texts: ESP8266 (connected to Arduino) only works when plugged into USB power

texts:
The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.

UPDATE

It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.

I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.

It's still a mystery to me why it works so well when connected to my Macbook.


texts: Is it possible to use Pi's output signal as Arduino's input signal?

texts: I have a relay attached to an Arduino Uno which I want to control using my raspberry pi 3b. And yes I know it can be done by attaching the relay directly to Pi but I cannot do so. Don't ask me why. That is why I want to know whether it is possible to use Pi's output signal as input for the Arduino or not. I do not have spare parts so I don't want to experiment. If anyone knows about this, please tell me.


texts:
I have an Arduino Mega connected to an SD card reader (Catalex branded), that at least detects the card as it displays the info of the card. But when I try to create a file, it does not create it. I am using the following code:

if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}
File root=SD.open("data.txt", FILE_WRITE); //open of the File for writting
if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}

I also tried with this code:

File root2 = SD.open("file.txt", O_RDWR | O_APPEND);
    if (!root2) {
       // It failed, so try and make a new file.
        root2 = SD.open("file.txt", O_RDWR | O_CREAT);
        if (!root2) {
          // It failed too, so give up.
        Serial.println("Failed to open file.txt");
         }
    }

[Update]

I also tried with this easier code and it does not work either:

#include <SD.h>

const int chipSelect = 10;
Sd2Card card;

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  File myFile = SD.open("Data.txt", FILE_WRITE);
  if (myFile) {
    for (int i = 0; i < 101; i++) {
      myFile.print(i);
      myFile.print(" multiplied by two is ");
      myFile.println(i * 2, DEC);
    }
    Serial.println("Finished");
    myFile.close();
  } else {
    Serial.println("Error opening Data.txt");
  }
  //do nothing else
  do { } while(1);
}


texts:
Today I ordered a 2x16 character LCD with white characters on black background.

Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.

Did anyone do this before?
Is it even possible that way?

I've seen RGB negative LCDs from Adafruit and Sparkfun.


texts:
I have simple project composed of an Arduino Nano, a HC-05 module, and a small toy DC motor controlled using a L293D driver, I want to be able to power this circuit entirely using a battery, here is what I tried:
-The motor/L293D combo works when the Arduino Nano is powered through it's USB jack, except the L293D is drawing power from the Nano, which I know is very bad practice, but I only did it for testing purposes.
-The HC-05 module also works fine when the Nano is powered through it's USB jack, as expected.
-However, the power received through the USB jack is not enough power for both the HC-05 and the L293D & motor simultaneously, if I want to change the PWM through the HC-05, I have to disconnect the motor, send the instruction, then disconnect the HC-05 and re-connect the motor.
-I have tried 3, pretty much new 9V batteries, none of them were enough to power anything, not the Nano board through the Vin pin, not an Uno board through barrel plug, not the motor, nothing, except a LED diode, I've read somewhere that most brands of these kinds of batteries don't actually provide nearly as much power as they claim, so that might explain it. (In case it's relevant, the brands I tried are VARTA, Uniross and Goldmen.)
-Someone gave me the idea of using an old mouse cable to power the Arduino, by taking the VCC and GND wires from the mouse cable and using those to power the Nano board through it's Vin and GND ports, it works, but not any components connected to it, not even the HC-05 module, which I even tried powering directly from the mouse cable, which lit up it's LED, but did not get it to work.
Honestly this isn't that relevant, I just wanted to make sure the Vin pin worked.
-Also, few side notes:
My multimeter mysteriously stopped working when I actually needed it, which is why I couldn't take any measurements.
The L293D datasheet and other pinouts suggest no less than 12V supply voltage, so maybe a 9V battery wasn't the right answer to begin with.
The power coming from the mouse cable is enough to power the DC motor independently, but not through the L293D, it says online the average output for these cables is around 5V, but without measurements I can't be sure.
The battery holder for the toy train that has DC motor inside accepts 1.5V batteries wired in series, and considering there's not much else there aside from the motor itself, it's safe to say that 3V is the minimum required voltage for the motor.
So, what battery do you think would be most suitable for my project?
And if it's not against the rules, what brand would you recommend?


texts: Can Arduino Mega ADK charge connected smartphone?

texts:
I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.

Is it capable of providing power to the smartphone?


texts: Keyboard Control Not Working As Intended

texts:
I'm trying to control a single motor.

If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180

#include <Servo.h>

char key = 0;
const unsigned int BAUD_RATE = 9600;

Servo Servo_0;

void setup()
{

  Servo_0.attach(0);
  Servo_0.write(0);

  Serial.begin(BAUD_RATE);

 // Serial.println("      Arduino Serial Servo Control");
 // Serial.println("Press < or > to move, spacebar to center");
 // Serial.println();

}

/*
a - 97
s - 115
d - 100
f - 102
*/

void loop() {

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("I received: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Turning Motor 1 to 0 deg");
       Servo_0.write(0);

     }
     else if(key==byte(115))
     {
       Serial.print("Turning Motor 1 to 180 deg");
       Servo_0.write(180);

     }

     delay(1000);
}

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?


texts: How to use php file_get_contents with ESP8266

texts:
A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file_get_content function. In iframe element my browser displayes "Hello my friend!" as wanted:

The ESP8266 server mode at 192.168.4.1 address, part of code:

String webpage = "
Hello
";
webpage += "
my
";
webpage += "
friend!
";

String cipSend = "AT+CIPSEND=";
cipSend += 0;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

The php script:

 <?php

 $url="http://192.168.4.1/?cmd=SS,0,0,";
 $lines_string = file_get_contents($url);
 echo htmlspecialchars($lines_string);

?>

If i replace the url by:

$url=https://arduino.stackexchange.com

It works with php script,so what is the issue with the ESP8266 ?


texts: Arduino Uno not able to handle 2-dimensional array

texts:
Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

void setup()
{
  Serial.begin(9600);
  int image_width = 56;
  int image_height = 96;

  int image_result[image_width][image_height];
  for (int i=0; i<image_height; i++) {
    for (int j=0; j<image_width; j++) {
      image_result[j][i] = 5;
    }
  }

  Serial.print("code works");
}

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?


texts:
I m working on a project in which I am using HC04 module so can anyone give me any Arduino Library for Proteus which have HC05 in it. Or tell me how to use HC05 in Proteus.

Thanks.


texts:
I am new to arduino programming and I have bought arduino UNO a few days ago.

I am trying to read the value of pin 4 using digitalRead with pinMode INPUT_PULLUP but it keeps giving me 1 even when the pin 4 is not connected to anything.

Here is the code:

void setup() {
  pinMode(2,OUTPUT);
  pinMode(4,INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
}

void loop() {
  Serial.print(digitalRead(4));
  Serial.print('\n');
  delay(150);
}

Pin 2 is connected to one side of the button and Pin 4 is connected to other side of the button.
According to condition, when the button should be off , the value should be 0 and when the button  should be on , the value should be 1 , but the value is 1 even when I press the button is off or on.

On the other way , if I replace INPUT_PULLUP with INPUT then the value is floating.

Why the value with INPUT_PULLUP is 1?


texts: Light communication from pc/app to arduino

texts:
I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .

Is there any library or implementation or where to start guide?, if not, how would you implement it?

I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.


texts:
I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin.
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?


texts: Ribbon sensor resistance slowly drops when released

texts:
I recently bought a ribbon sensor (the one displayed here), with the intention to use it as a touch-enabled music instrument.

I used it correctly (so it seems), but I have two issues :

When not pressed, the sensor seems to give random data, as if nothing was plugged to the pin.
When unpressed, the resistance slowly decreases (and so is my sound pitch). Is that a normal behaviour ?

I don't know how to solve both issues. Has anyone an idea ?

A tinker of my test (Currently corrected thanks to @VE7JRO) can be seen here with my code here (The ribbon is replaced by a potentiometer but the principle remains the same). The code is also Available on GitHub.


texts: Is it possible to make a mathematical function generator using Arduino?

texts:
I want to build a function generator but not the ones which outputs square wave or sawtooth ect. I will input a discrete function lets say f(n) = e^n for n=0 to n=100 and the output array will be outputs as voltage samples creating a e^x like signal on a scope?

Is this possible?