text:
Scroll String Only On Second Line Using 2x16 LCD
I'm trying to scroll a string in the second row of the LCD while letting the string on the first row stay intact. I use Serial to run that part of the code as you can see. It work at first but when I try to make it run again it doesn't display anything on the second row.
I borrowed the code from :
http://code.nishantarora.in/arduino-lcd-projects/src/3f10686e7464665c5c59d7be772c00af7a4a93e8/scrollOneLine/scrollOneLine.ino?at=master
And made some changes:
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

// it's a 16x2 LCD so...
int screenWidth = 16;
int screenHeight = 2;

String line1;
String line2;

int stringStart, stringStop = 0;
int scrollCursor = screenWidth;

String CompleteString;
String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet",  "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};

String string1 = "String";

int countMovement=0;
int arraylimit = 9;

void setup() {

   lcd.begin(screenWidth,screenHeight);
   Serial.begin(9600);

}

void loop(){

   char ser = Serial.read();

   if ( ser == 'c' ) {
     CompleteString="";

     for (int i = 0 ; i <= arraylimit; i++) {
        CompleteString += stringArray[i] + " "; // Convert String Array To Single String
     }

     roop(string1,CompleteString);
  }

}

void roop(String line1, String line2) {

  countMovement = 0;

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);
     lcd.clear();

     if(stringStart == 0 && scrollCursor > 0){
        // Serial.println(scrollCursor);
        scrollCursor--;
        stringStop++;
     } else if (stringStart == stringStop){
        stringStart = stringStop = 0;
        scrollCursor = screenWidth;
     } else if (stringStop == line1.length() && scrollCursor == 0) {
        stringStart++;
     } else {
       stringStart++;
       stringStop++;
     }

     countMovement++;

  }

  lcd.setCursor(4, 0);
  lcd.print(line1);

}

From what I can see using Serial as debugging is that the problem resides in the function "roop" and in specific the line:
 if(stringStart == 0 && scrollCursor > 0){

It seems that the statement is being pass on and so it doesn't move the string as it's suppose to. I could be wrong but placing a Serial call in there yields no result the second time the function is called but the first time it did.
Any help would be much appreciated! And I know the community will be grateful too since it's difficult from what I can see in post to achieve this and make it autonomous so that no big modifications needs to be done.

You may add the LiquidCrystal.h/.cpp code to your project and modify it if necessary.

Why do I need to do that? I'm almost there. I know it only needs a little bit of understanding and a simple explanation to make it work. Someone to point what's wrong in the code.

You need to reset the stringStart, stringStop and scrollCursor at the beginning of the roop function.
void roop(String line1, String line2) {

  countMovement = 0;
  stringStart = 0;
  stringStop = 0;
  scrollCursor = screenWidth;

  ...

I think you also need to move the lcd.clear up. Or else the screen will be blanked when the roop function is done scrolling.
...

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.clear();
     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);

...

Seriously man that's what I was talking about! A simple mistake with an easy solution. I found another code that does the same in both directions so I'll be posting both codes for future reference. Thanks 4 your time

Great! Glad to have helped.

The answer from the user Gerben worked perfect. So I'll be posting another solution I came upon and the one from my original question for feature reference.
Original Code:
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

// it's a 16x2 LCD so...
int screenWidth = 16;
int screenHeight = 2;

String line1;
String line2;

int stringStart, stringStop = 0;
int scrollCursor = screenWidth;

String CompleteString;
String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet", "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};
String string1 = "String";
boolean ArrayRead = true;
int countMovement=0;
int arraylimit = 9;

// most of the part is pretty basic
void setup() {

   lcd.begin(screenWidth,screenHeight);
   Serial.begin(9600);

}

void loop(){

   char ser = Serial.read();

   if ( ser == 'c' ) {
      CompleteString="";

      for (int i = 0 ; i <= arraylimit; i++) {
         CompleteString += stringArray[i] + " "; // Convert String Array To Single String
      }

      roop(string1,CompleteString);
   }

}

void roop(String line1, String line2) {

   countMovement = 0;
   stringStart = 0;
   stringStop = 0;
   scrollCursor = screenWidth;

   while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

      lcd.clear();
      lcd.setCursor(scrollCursor, 1);
      lcd.print(line2.substring(stringStart,stringStop));
      lcd.setCursor(5, 0); // 1 = word eat array of words very cool
      lcd.print(line1);
      delay(300);
      lcd.clear();
      if(stringStart == 0 && scrollCursor > 0){
         scrollCursor--;
         stringStop++;
      } else if (stringStart == stringStop){
         stringStart = stringStop = 0;
         scrollCursor = screenWidth;
      } else if (stringStop == line1.length() && scrollCursor == 0) {
         stringStart++;
      } else {
         stringStart++;
         stringStop++;
      }

      countMovement++;

   }

   lcd.setCursor(4, 0);
   lcd.print(line1);

}

The other code provided by the user "HazardsMind" for I2C LCD Module: The changes made are Serial communication and adapted for the 6 pin LCD Module.
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

//char * SerialComm[70];
//{"s = Plane i=Car h=Boat u=Rocket d=Jet p=Submarine l=Truck b=Bicycle m=Skate enter=Train"};

#define N_CHARS  ((sizeof(MessageOut)/sizeof(MessageOut[0]))-1)
#define N_CHARS2  ((sizeof(MessageOut2)/sizeof(MessageOut2[0]))-1)

//int len = strlen(SerialComm);

char MessageOut[30];
char MessageOut2[30];

int index = 19, index2 = 0;
unsigned long oldTime = 0, oldTime2 = 0;

byte indexer = 0; // Index into array; where to store the character
char inData[58]; // Allocate some space for the string
char inChar; // Where to store the character read

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

void loop()

  while(Serial.available() > 0) // Don't read unless
                                              // there you know there is data
  {
      if(indexer < 57) // One less than the size of the array
      {
         inChar = Serial.read(); // Read a character
         inData[indexer] = inChar; // Store it
         indexer++; // Increment where to write next
         inData[indexer] = '\0'; // Null terminate the string
      }
  }
  // Now do something with the string (but not using ==)

  // Serial.print(inData);
  setHeadingRight("Royal", 0, 500);
  setHeadingLeft(inData, 1, 500);

  //setHeadingRight("Hello Welcome", 0, 1000); // message, row, duration
  // setHeadingLeft("Welcome", 1, 500);
}

void setHeadingRight(char * msg, byte row, unsigned long duration)
{
   strncpy(MessageOut, msg, sizeof(MessageOut));
   if(millis() - oldTime > duration) // check the difference of the current time "millis()" to the previous time "oldTime" against the duration you want.
   {
      oldTime = millis(); // update oldTime with the current time
      if(index >= 0) // make sure the index does not go under 0
      {
        index--; // decrecment index by 1
        for (int i = 0; i < N_CHARS; i++) // this part here displays the message on the display
        {
           lcd.setCursor(i,row); // set the column to show the element in the array
           if(index == N_CHARS) index = 0; // set index back to 0 if the index has reached the arrays max size.

              if(MessageOut[index++] != NULL) // if the element @ index is anything but NULL, show it.
                  lcd.print(MessageOut[index-1]);
              else
                  lcd.print(' '); // if the element @ index is NULL, display a space.
        }
      }
   else index = 19; // if index is less than 0, then set it back to 19
 }
}

void setHeadingLeft(char * msg, byte row, unsigned long duration2)
{
  strncpy(MessageOut2, msg, sizeof(MessageOut2));
  if(millis() - oldTime2 > duration2)
  {
     oldTime2 = millis();
     if(index2 < 20) // check to see if index2 is under the array max size
     {
        index2++; // increment index
        for (int i = 0; i < N_CHARS2; i++) // same as above
        {
           lcd.setCursor(i,row);
           if(index2 == N_CHARS2) index2 = 0;

              if(MessageOut2[index2++] != NULL)
                 lcd.print(MessageOut2[index2-1]);
              else
                 lcd.print(' ');
              }
           }
           else index2 = 0; // otherwise set it back to 0
     }
}


text:
Using an ultrasonic sensor to act as a potentiometer for a Servo?
I would just like to start off by saying that I am new to Arduino so my code and approach to the wanted outcome are probably not the best. Anyway, I had the idea of using an ultrasonic sensor and my hand to act as a potentiometer to control the position of a servo. So, I wired everything up and wrote the code but the Servo just jitters around and doesn't move the way I wanted it to. The serial readings are fine, it is just that the servo isn't responding the way I hoped. Here is the code
#include <Servo\Servo.h>
#define echoPin 7
#define trigPin 8

int maximumRange = 400;
int minimumRange = 0;
int angle;
long duration, distance;
Servo myServo;

void setup()
{
    Serial.begin(9600);
    pinMode(echoPin, INPUT);
    pinMode(trigPin, OUTPUT);
    myServo.attach(9);
}

void loop()
{
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance = duration / 58.2;

    angle = map(distance, minimumRange, maximumRange, 0, 179);
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.print(" Angle = ");
    Serial.println(angle);
    myServo.write(angle);
    delay(50);
}

If anyone can help, it would be appreciated if you could post what is wrong with my code and how to fix it.
Note: I'm using Visual Studio instead of the Arduino IDE, so that is why it says #include <Servo\Servo.h> at the top.

WHat does the serial monitor display? Do you have frequent small variations of angles? If yes, that would explain the servo jittering. The solution is then to somehow smoothen the angle to avoid small angle variations. The fact is that the ultrasonic sensor will not give the exact same value everytime, event if the distance does not change.

This question http://arduino.stackexchange.com/questions/4135/arduino-starter-kit-servo-is-shaking may be related to your problem, check its answers.

what servo are you using?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
VC0706 card failed, or not present
I'm trying to follow this tutorial here:
https://learn.adafruit.com/ttl-serial-camera/using-the-camera
Here's what my serial log is printing-- I've added a few commands for logging:
Arduino version is: 10605
Chip Select is: 4
VC0706 Camera snapshot test
Card failed, or not present

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite
it works just fine. What am I messing up?
I'm using an arduino uno with wifi shield.
Thanks!

Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.
//#if !defined(SOFTWARE_SPI)
//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
//#else
//  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
//#endif
//#endif

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino/ESP8266 to put PC to sleep and wake it up
I have a Wemos D1 mini that's connected to a pc with usb, I want to be able to sleep the pc and wake it up programmatically.
Is there a way to do this? Like sending a simulated sleep keyboard button press?
Maybe I can send a wake up on lan command from the Wemos since they both are connected to the same router, but I'm still more interested in sending a sleep command.
I found this but it's old and it looks like they don't really have a way to do it.

When I wanted to remotely sleep my laptop through WiFi I resorted to installing an application on the PC that listened on a socket. You can't do WoL on WiFi since it relies on an active network connection, which you can't do with a WiFi adaptor. Only Ethernet, and then only on cards that support it.

What application did you use? Also, the PC is connected through ethernet to the same router the Wemos is connected to, so it should be possible to send WOL to the address of the pc no? @Majenko

In that case WoL may be doable, yes. Sleep, though, is an altogether different ballgame. I forget the application I used. It was a free one I found through google.

I'm voting to close this question as off-topic because it is about PC's and their operating systems, not about Arduino.  When a viable solution for the PC is identified, implementing it with an Arduino might become a valid question, but not before.

easy way to sleep it is to create a command to press the sleep button w/ autohotkey, then fire that command from a program that can both run apps and read the serial port, like python or nodejs. to wake it up, you need a fake keyboard, which the esp can't do...

The hardware interface would be the easiest like others were saying.
Here is a project someone else shared that does that.
https://www.hackster.io/zvonko-bockaj/wemos-esp8266-remote-pc-switch-062c7a
The wake-on-lan part is easy and here is some code for that.
https://github.com/koen-github/WakeOnLan-ESP8266
I'm also interested in sending some kind of RPC call to a system (linux/windows/mac) via wifi to initiate a shutdown.  If I find a solution I will post it here.
UPDATE: I found a Sleep-On-Lan project that should work.  You can use the same code above for the ESP8266 but just reverse the MAC Address of the system you want to shutdown.
https://github.com/SR-G/sleep-on-lan
You will need to run this as a service on the system you intend to put to sleep.  There is a windows and linux version.  They didn't mention mac but I bet it will compile and run on a mac too.  :)
I hope this helps.  I will probably use this myself in the future.

Could you please add a summary of the key points from each of the links (in case the links go dead).

Sleep
If this is a Windows PC and you can write a WIN32 C++ program then you can look at the WH_KEYBOARD_LL() function and use that to inject the "sleep key", but I'm not sure the "sleep key" isn't an OEM key which might make things difficult.
You could also look at sending a remote command (shutdown) over the network, but you'd have some hefty protocols to implement.  Unless you had a service on your PC that listened to the serial connection and waited for the device to send a sleep command to it over that and converted it into a system call.  The same will work with a Linux Daemon.
Wake Up
You can get Windows (don't know about Linux) to let a USB device wake it up, but I don't know if you could get a Arduino/ESP to send the correct signals.
Like The great Majenko says WoLAN is an option, but difficult to achieve.
My preferred option would be to splice a wire into the power button of the PC in parallel (so you can still use the button) and control that with a relay.  That should give you a Wifi enabled power switch, but you need to check how the switch works and mimic it properly.  I would try it with an old, almost dead, worthless PC first if I was you.


text:
How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?
I'm debugging a couple of RS232-to-TTL converter boards that I'm trying to use to program my Arduinos and one thing I would like to try would be to reduce the upload serial speed from 115200 to 19200.
How do I do that?
I imagine that there's a setting that can be easily changed on the Arduino IDE preferences. But where is it? But then the bootloader speed would have to match that? How do I change the serial upload speed on optiboot, too?

On Arduino IDE side, the upload speed is coded in hardware/arduino/boards.txt
uno.upload.speed=115200
...

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the expected speed for the actual bootloader of every board).
Now as per the optiboot loader side, the upload speed is defined in BAUD_RATE macro, in optiboot.c:
/* set the UART baud rate defaults */
#ifndef BAUD_RATE
#if F_CPU >= 8000000L
#define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
#elsif F_CPU >= 1000000L
#define BAUD_RATE   9600L   // 19200 also supported, but with significant error
#elsif F_CPU >= 128000L
#define BAUD_RATE   4800L   // Good for 128kHz internal RC
#else
#define BAUD_RATE 1200L     // Good even at 32768Hz
#endif
#endif

So I guess you can:

#define BAUD_RATE 19200 before that block of code
recompile the optiboot loader
upload your own new bootloader version
update uno.upload.speed accordingly in boards.txt
check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing.
Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!

This isn't going to "fry" your arduino. At worst, you'd wind up with a ATmega with a
damaged boot loader, which would just mean you'd need to re-program it again via ICSP.

Then say you could render your arduino unrecoverable without a proper programmer. "Fry" implies actual hardware damage, not just mis-configuration that makes recovery involved.

no proprer progrqammer is needed, you can use ftdi/8u2 chip on-board with bit-bang mode.

Tried it and it worked great! Well, the Uno didn't like the optiboot running on 56200 bps (not sure why), but the Severino and my custom boards with serial FTDI-like programming headers all worked. I also couldn't compile the optiboot slower than that (tried 19200) because other compile errors, but that's ok. I used Arduino IDE 1.0.5 and followed the instructions on .\hardware\arduino\bootloaders\optiboot\README.TXT and didn't have to install anything beyond the IDE. Nice!!

And that solved the problem with my RS232-to-TTL converter board. It worked ok with 56200 bps. Thanks much!!


text:
ESP32 in Arduino-IDE with FS.h and SPIFFS
I'm working on a webserver on ESP32 in Arduino IDE and would like to load an html-file. Tried to use SPIFFS.open from the library FS.h from github.
Errormessage says SPIFFS was not declared in this scope. (As far as I can see, there's no bracket in the wrong place.)
I did not find any example for ESP32 and FS.h and desperately hope for some help. Thanks in advance.
Here is my code:

    #include "FS.h"
    #include "WiFi.h"
/Wifi Access data/
const char* ssid_ap = "AccessPoint";
const char* password_ap = "12345678";
const char * ssid_sta     = "";
const char * password_sta = "";
/* set global variables */
byte WiFiMode = 0;  // WIFI_STA = 1 = Workstation  WIFI_AP = 2  = Accesspoint
int request_counter;
String sHTML;
String sHTMLRequest;
/* Create instance of server on Port 80 */
WiFiServer server(80);
WiFiClient client;
/*
 * ******SETUP*******************************************************
 */
void setup() {
/initialize GPIO/
/*start serial communication */
  Serial.begin(115200);
  SPIFFS.format();
  Serial.println("Spiffs formatted");
/* start WiFi as workstation (STA), if not possible
   start as Acess Point
   initialize server */
  WiFi_Start_STA();
  if (WiFiMode == 0) WiFi_Start_AP();
}
/*
 * **LOOP*************************************************************
 */
void loop() {
/* Check if a client has connected */
  client = server.available();
  if (!client)
  {
    return;
  }
/*Wait for the client to send data */
  Serial.println("neuer Client verbunden");
  /*Count Aufruf der Seite: */
  request_counter ++;
  unsigned long clTimeout = millis()+250;
  while(!client.available() && (millis()clTimeout)
  {
    Serial.println("time-out bei Client-Verbindung!");
    return;
  }
/****** open html files  *******/
 SPIFFS.begin();
 File f = SPIFFS.open("/home.txt", "r");
    if (!f) {
    Serial.println("file open failed");
    }
    f.close();
}
/**********************************************************************
 *
 **************** FUNCTIONS ********************************************
 *

*/
/*
 * Fct tries to start WiFi in workstation mode,
 * if not possible sets WiFiMode=AP
 * starts server
 */
void WiFi_Start_STA() {
  unsigned long timeout;
WiFi.mode(WIFI_STA);   //  Try to start WiFi as Workstation
WiFi.begin(ssid_sta, password_sta);
  timeout = millis() + 12000L;
  while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
  delay(10);
  }
if (WiFi.status() == WL_CONNECTED) {
    server.begin();
    WiFiMode = WIFI_STA;
Serial.print("Verbunden mit IP - Addresse: ");
    for (int i = 0; i < 3; i++) {
      Serial.print( WiFi.localIP()[i]);
      Serial.print(".");
    }
    Serial.println(WiFi.localIP()[3]);
}
  else {
    WiFi.mode(WIFI_OFF);
Serial.println("WLAN-Verbindungsaufbau fehlgeschlagen");
}

}
/*
 *starts WiFi in AP-mode
 *starts server
 */
void WiFi_Start_AP() {
  WiFi.mode(WIFI_AP);   // Access Point mode
  WiFi.softAP(ssid_ap, password_ap);
  server.begin();       // start server
  IPAddress ApIP = WiFi.softAPIP();   //read IP of Access Point
  WiFiMode = WIFI_AP;
Serial.print("ESP-Netzwerk: ");
  Serial.print(ssid_ap);
  Serial.print(" aufgebaut. ");
  Serial.print( " IP-Addresse: ");
  Serial.println(ApIP);
}
    <code>

https://github.com/copercini/arduino-esp32-SPIFFS
This library should help you.

I have this same problem after a new install and,
Looks like the link is dead.
Can anyone please take the time to explain how to fix this problem.

The answer is belated but since the question is still open...
The code does not include spiffs library. The line below should fix the problem.Note it should be below the the include statement for FS
include <SPIFFS.h>

So the code should look like
#include "FS.h"
#include "WiFi.h"
#include "SPIFFS.h"

at the time of the question esp32 arduino core didn't have SPIFFS library

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What are the differences between the 1.0.x and 1.6.x IDEs?
What is a summary the main differences between the Arduino 1.0.x and 1.6.x IDEs?  Why do some Arduino products, such as the LightBlue Bean, still require use of the 1.0.6 IDE?

http://arduino.cc/en/Main/ReleaseNotes find 1.0.6 and start scrolling up

Question modified for an answer that fit on this page.

I think Arduino's version history is a bit confusing. I'm not an expert but I think this explanation will help. First let's note that version 1.6 was released 2015.02.09. However, back in 2012, version 1.5 BETA was created and it remained in beta for several years. Meanwhile, the 1.0.X version evolved independently here's an excerpt from the changelog

ARDUINO 1.0.6 - 2014.09.16
ARDUINO 1.0.5-r2 - 2014.01.08
ARDUINO 1.0.5 - 2013.05.15
ARDUINO 1.0.4 - 2013.03.11
ARDUINO 1.0.3 - 2012.12.10
ARDUINO 1.0.2 - 2012.11.05

So you can see that 1.0.6 isn't as old as one may think. Many vendors probably chose not to develop their products against the 1.5 version (or branch) because of its beta status. 1.5 being in beta for as long as it did lends to a confusing version history. I did get the impression that LightBlue Bean is working on compatibility with 1.6.x because their getting started page mentions

Download and extract the Arduino app, version 1.0.5. We currently do not support newer versions of the Arduino IDE.


text:
How to run Arduino 1.0.6 on OS X 10.10 with Java 7 or 8 already installed
On a new Mac (running OS X 10.10) with Java 7 or 8 already installed (for other development), how can I run the Arduino 1.0.6 IDE (which seems to be required for the LightBlue Bean BLE Arduino device), which seems to require using a very old Java 6 installer from Apple?
Is there a way to install multiple versions of Java without breaking any of them?  Or is there a way to use the Arduino 1.0.x IDE with a newer version of Java?
Or should I re-ask this question over at the apple.stackexchange.com site?

I think they have a special version of the IDE. https://punchthrough.com/bean/getting-started-osx/ . What error do you get when you run the app?

You can call java specifying each and every .jar to its -cp (classpath) parameter.
Sure you can't just use the latest 1.6.1? Or the current nightly, soon to become 1.6.2, which bundles java 8?

Reportedly the LightBlue SDK installation currently destroys an Arduino 1.6.x IDE.


text:
I need to build a char array from two integers
My C is rusty, so please forgive this simple problem.
This line works:
Tft.drawString("Test",200,200,2,WHITE);
But, this has compile errors:
String yStr = "Test";
Tft.drawString(yStr,200,200,2,WHITE);

The function in the library:
void drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

The error is "no known conversion for argument 1 from 'String' to 'char*'".
Conclusion - I need a character array. Here's what I am trying to accomplish.
I have two integers that I would like to display on my Tft screen. For example, 225 and 250 to be displayed as "225,250".
I haven't figured out a way to build the char array for the drawString() function.
Assistance would be appreciated.

Thanks for the quick reply Ignacio.
I tried that, but the compiler still doesn't like it.
Here's how I built the string:
string stringXY ;
stringXY += xStr;
stringXY += ",";
stringXY += yStr;
Tft.drawString(stringXY.c_str(),200,200,2,RED);

Error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
I am apparently using c_str() wrong?

The pure c method using a char array rather than a string is to use sprintf: char tmpBuffer[64]; sprintf(tmpBuffer,"%d,%d",xVal,yVal);

Many thanks to Ignacio.
I changed the function in the library to:
void drawString(const char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);
This fixed the problem and gave me more confidence in my vague understanding of C.

Another option in your situation is to not use String at all (which is preferrable for reasons I won't explain here) and exclusively use plain old C strings and their associated functions:
// Define a string buffer to hold the result, ensure it is long enough
// to hold "N1,N2". An additional char must be added to terminate the string with 0
char result[15+1];
unsigned int N1 = ...;
unsigned int N2 = ...;
// Format output as desired
sprintf(result, "%u,%u", N1, N2);
// Now you can use result with drawString
Tft.drawString(result, 200, 200, 2, RED);

sprintf is a very powerful formatting function that offers you plenty of options.
Note that I took it for granted that your numbers are unsigned int; if these were normal integer (possibly negative), you should replace "%u,%u" with "%d,%d".

What is the (approximate) overhead of sprintf in terms of global/static RAM allocation, dynamic allocation, and program size (flash memory)

Put it in a String and then use the c_str() method to get the associated char*.

Thanks for the quick reply Ignacio.
I tried that, but the compiler still doesn't like it.
Here's how I built the string:
String stringXY ;
stringXY += xStr;
stringXY += ",";
stringXY += yStr;
Tft.drawString(stringXY.c_str(),200,200,2,RED);
error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
I am apparently using c_str() wrong?

No, that's a bug in the TFT library. There's no reason that argument should be modified, so it should be tagged const.


text:
Problem with wrapping Adafruit Motor Controller function calls in a class
I'm working on an Arduino robot and I ran into a problem when reorganizing my code. I have an Adafruit Motor Shield v2.3 connected to an Arduino Uno. My robot can be controlled using a bluetooth connection (BlueSMIRF module) or it can be told to avoid obstacles using an ultra sonic range finder.
Everything worked fine and the robot moved nicely until I decided I wanted to organize the code better, so that my code for moving the robot would be in a separate class, my code for servo movement also in a class as well as my code for the logic for movement (received bluetooth command - do this, or avoid obstacles like so, etc.). Suddenly, none of the motors respond or just one.
I'm not sure if I have a problem with my C++ and passing pointers to my functions or what is going on...
Here is my main .ino file, its relevant parts, I left out stuff that concerns the bluetooth connection etc. And yes, I know the hardcoded include paths look ugly, I'll figure out what to do with includes at some point... :
// bluetoothRobot.ino

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <Servo.h>
#include <SonarSRF08.h>
#include <SoftwareSerial.h>
#include <MemoryFree.h>
#include "utility/Adafruit_PWMServoDriver.h"

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\AvoidObstacleController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MemoryFree-master\MemoryFree.h"

MotorController* motorController;

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

void setup()
{
    motorController->start(&AFMS, leftRearMotor, leftFrontMotor, rightFrontMotor, rightRearMotor);
    AFMS.begin();
}

void loop()
{
    if(bluetooth.available())  {
        char command = (char) bluetooth.read();

        if (controlMode == 2) {
            motorController->executeBluetoothCommand(command);
        }
    }
}

Here is my MotorController.h:
// MotorController.h

#ifndef MotorController_h
#define MotorController_h

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

class MotorController {
    public:
      int executeBluetoothCommand(char command);
      void start(Adafruit_MotorShield *AFMS, Adafruit_DCMotor *rightRearMotor, Adafruit_DCMotor *leftRearMotor, Adafruit_DCMotor *rightFrontMotor, Adafruit_DCMotor *leftFrontMotor);
      void turnRight();
      void turnLeft();
      void moveForward();
      void moveBackward();
      void stopRobot();
      void setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed);
    private:
      Adafruit_MotorShield* AFMS;
      Adafruit_DCMotor* leftRearMotor;
      Adafruit_DCMotor* rightRearMotor;
      Adafruit_DCMotor* rightFrontMotor;
      Adafruit_DCMotor* leftFrontMotor;
  };

#endif

And here is MotorController.cpp:
// MotorController.cpp

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"

void MotorController::start(Adafruit_MotorShield *shield, Adafruit_DCMotor *rrm, Adafruit_DCMotor *lrm, Adafruit_DCMotor *rfm, Adafruit_DCMotor *lfm) {
      AFMS = shield;
      rightRearMotor = rrm;
      leftRearMotor = lrm;
      rightFrontMotor = rfm;
      leftFrontMotor = lfm;
      setRobotSpeed(80,80);
  }
int MotorController::executeBluetoothCommand(char command) {
        switch(command) {
            case 'F':
              moveForward();
              break;

            case 'B':
              moveBackward();
              break;

            case 'L':
              turnLeft();
              break;

            case 'R':
              turnRight();
              break;

            case 'S':
              stopRobot();
              break;

            /*case 'W':
              stopRobot();
              controlMode = 1;
              tiltServoAngle = 120;
              panServoAngle = 90;
              motorController.setPanAndTilt(panServoAngle, tiltServoAngle);
            */
            default:
              return -1;
              }
    return 0;

}
void MotorController::setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed) {
        leftFrontMotor->setSpeed(leftWheelsSpeed);
        leftRearMotor->setSpeed(leftWheelsSpeed);
        rightRearMotor->setSpeed(rightWheelsSpeed);
        rightFrontMotor->setSpeed(rightWheelsSpeed);
  }
void MotorController::moveForward() {

        setRobotSpeed(80,80);
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(FORWARD);
        leftFrontMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);

  }

void MotorController::moveBackward() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80,80);
  }

void MotorController::turnLeft() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80, 80);
  }

void MotorController::turnRight() {
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(FORWARD);
        setRobotSpeed(80, 80);

  }

void MotorController::stopRobot() {
        leftRearMotor->run(RELEASE);
        rightRearMotor->run(RELEASE);
        rightFrontMotor->run(RELEASE);
        leftFrontMotor->run(RELEASE);
  }

I used to have a constructor for MotorController with the Motor Shield library AFMS.begin() call in it and all. But this caused the Arduino to constantly reset for some reason. I coudn't understand why but I moved the motor configurations and call to begin() to my .ino file where the problem doesn't occur.
Problem: What happens with the code as it is, is which ever pointer to motor is passed last seems to work and that particular motor turns but the others won't. If I comment out the call to setRobotSpeed in MotorController::start, nothing happens with any motor even though speed is also set in the relevant functions.
As said, the robot worked fine when the code was in my .ino file. Although, for some reason I had to call the Motor Shield library's begin() function always before any other commands to motors. So it was called every time the user told the robot to move forward, move backward etc. Otherwise nothing happened with the motors. Now, if I add a call AFMS->run() to my MotorController.cpp, the Arduino starts to constantly reset...
Also, none of the other stuff (blueSMIRF, the range finder code etc.) should interfere since they were also there when it worked and I even commented out that stuff.
I'm baffled. Maybe its some silly mistake with my C++? Or is there really something weird going on here?
Any help would be much appreciated, I've spent hours trying to figure this thing out! Thanks in advance!

I would epecte your current code to not even compile because of the backslashes \ in the include paths. \ is a special character in C and C++ and is used to escape the next character and change its meaning. In include paths you should always use / even when working on Windows.

@jfpoilpret As I said in the question, it does work just fine except for the motors not turning and does compile. But I'll fix the paths, thanks!

The obvious issue in your current code is that motorController is a pointer to your class but I don't see any place it was instantiated properly.
Hence, it points anywhere the first time you use it, which can explain resets of the MCU.
Now, either you keep it as a pointer:
MotorController* motorController;

And then you instantiate it in place:
MotorController* motorController = new MotorController();

Or you can also instantiate it in setup() as first line (ie before it is used anywhere else):
void setup() {
    motorController = new MotorController();
    ...
}

However, for reasons discussed elsewhere on this site, I would not use dynamic allocation but I'd rather define motorController as an instance of MotorController instead of a pointer:
MotorController motorController;

Now everywhere you were using motorController->xxx you'll have to replace it it with motorController.xxx.
That should remove the most important bug of your current code (I can-'t tell if there are other issues but this one must be fixed in priority).

Omg... Thanks! I had a feeling this might be something really simple. I feel a bit silly now. I just spent like a day wondering. I guess what I am learning is to pay more attention to my C++ and what exactly I'm doing. I've done a lot of coding in Java and other languages, using Eclipse and these kinds of things still take me by surprise, when I don't get a warning and the code works except it doesn't!

One thing about instantiating classes before setup() is called is that init() (which you don't see) may undo all of your careful setup.
Your code starts:
Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

but these are constructed before setup(). And then you call MotorController::start() with those values. You haven't provided the code for AFMS::getMotor() - so it may be doing things internally that is undone by init().
Instead of creating the whole pointer, why not do this:
const byte rightRearMotor = 1;
const byte leftRearMotor = 2;
const byte rightFrontMotor = 3;
const byte leftFrontMotor = 4;

and then callig AFMS.getMotor() inside MotorController::start():
void MotorController::start(Adafruit_MotorShield *shield,
                            byte rrm, byte lrm, byte rfm, byte lfm) {
    AFMS = shield;
    rightRearMotor = AFMS.getMotor(rrm);
    leftRearMotor = AFMS.getMotor(lrm);
    rightFrontMotor = AFMS.getMotor(rfm);
    leftFrontMotor = AFMS.getMotor(lfm);
    setRobotSpeed(80,80);
}


text:
Interrupt driven serial in Arduino Mega
This is the multi serial example from Arduino IDE
void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
  // plus do some operations
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    // plus do some operations
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

As you can see, the loop is running multiple times doing almost nothing at most of cycles, this will eat up battery life (if it has one).
Is it possible to read when data is available without looping, just like with an interrupt.
Also, is it a good practice to run a loop all the time? Is there any way to sleep? I have seen examples like this one http://playground.arduino.cc/Learning/ArduinoSleepCode which uses some other pin to wake up. I don't want that.

Serial input can wake the processor from sleep, assuming it is useful for it to sleep (for example, if it is battery-powered).
My page about power shows various technicques including using serial input to wake it from sleep (see reply #8 on that page). However a disadvantage of that is, it take a few microseconds to wake from sleep - sometimes quite a few - so you are likely to lose the first byte received from serial if you are asleep.

Also, is it a good practice to run a loop all the time?

There is no harm, except for battery consumption.

I am extremely newbie in these electronics. thanks man you are genius .but small question "you are likely to lose the first byte received from serial if you are asleep" don't that data will be saved in serial buffer ??

No, because the clock (used for all operations) take a few microseconds to "spool up" after sleep. The processor is held inoperative until it has - the exact time depends on fuse settings. Without a clock it can't clock in serial data. Some clock modes don't stop the clock, but they don't save as much power.

Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.
The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?


text:
I2C between Yun Shield (Dragino) and UNO R3 problem
I am having problems with I2C communications between my Dragino Yun and an Arduino UNO R3.
I can have the Dragino request data (using Wire.onRequest on UNO) from the UNO and it works great, however, when I have the UNO sending and the Dragino using Wire.onReceive it's not picking up any data!?
What are the SDA and SCL pins on the Dragino? Are they the same as the UNO? Are there any specific difficulties involved for this setup?


text:
Acrylic enclosure for Arduino
I've been browsing Aliexpress and eBay for decent Arduino enclusures, but I've found out they are even pricier then boards themselves.
Then I've realized that there are multiple firms that offer cheap laser cutting - I can buy 1 sq.m acrylic sheet and order cutting multiple parts of boxes at once.
Obviously I am not the first one who came up with this idea. Has anyone seen downloadable vector layouts I can use as something to start from? Thanks.

Found something here - https://www.thingiverse.com/tag:arduino_case/page:1 - but it is still far, far away from what I've imagined :(

What do you want to case exactly? If it's just the Arduino, wouldn't any project box of the right size do?

I'd like to have small box that would be used to store the completed assembly, protect it from dust and mechanical damage. I currently use small flat food containers - I drill holes for wires and then seal them with construction silicone glue. They are sturdy and cheap, but it looks ugly, they are usually 1.5-2 times larger than needed.

Making your own is quite possible, especially if you own a router (or even better a router table). You need a V shaped 90 degree router bit, a tube of proper perspex glue and some acrylic sheet. The glue is hard to find, but plastic sign manufacturers generally will sell it. Unless you are a DIY expert, I suggest the gap filling type of glue rather than the watery product that only fills perfectly matched surfaces. Try searching Youtube on "acrylic box making". There are several videos. My first two efforts were pretty bad, but the last couple are fine, and are of course exactly the right size.

cutting and gluing aren't the issues - as I said, there are multiple firms around that will take your blueprint and cut whatever you want, for peanuts. It is vector blueprints (in CorelDraw, or DWG format, for example) I can't find. I ended with obtaining original EAGLE schematic files for Arduino and getting exact dimensions and positions for mounting holes from there. But it looks like I'll need old-fashioned caliper and ruler for stuff like LCD screens and other peripherals :(


text:
Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1
I wanted to use both TMRpcm and VirtualWire with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:

TMRpcm: play a WAV sound from an SD Card;
VirtualWire: to receive commands from an RF remote control.

TMRpcm Advanced Features Wiki has a section on how to use TIMER2 instead, but I couldn't get it to work. They also say:

Notes:

This is usually not the best solution.

So, before I spend any more time on this, I would like to hear what you guys have to say.
So, my question is: is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?
If not, what other alternatives do I have?
My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: Playing Wave file using Arduino. And I'm using one of those
433MHz Receiver modules for the RF part (standard, working circuit).
Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).

I ended up working around the issue by building a board with two ATmegas in it. One MCU handles the sound while the other handles the RF receiver, each using its own TIMER1, both communicating via I2C.
It's kind of a low tech dual core controller board. Not the most efficient solution, but it worked great for me.

You could edit the VirtualWire.cpp source to use Timer2 instead of Timer1. For VirtualWire 1.18 the relevant section starts on line 512 with #else // ARDUINO.
On line 515 change (uint16_t)-1 to (uint8_t)-1 since Timer2 is only 8 bit. Then change all the TCCR1A, TCCR1B, OCR1A, TIMSK1 and OCIE1A to their Timer2 equivalent (hint: swap the 1's for 2's). Line 533 should be the last. On line 778 you also need to make a change to use TIMER2_COMPA_vect for VW_TIMER_VECTOR.
I hope that it helps.

For good measure also change OCIE1A to OCIE2A, and WGM12 to WGM22, though they have the same value so it will work without.

Gave it a try but couldn't make VW work with TIMER2. Instead, I'll try Manchester encoding lib a go...

Got the Manchester libs working, but also got a lot more dropouts with it, so I couldn't even get to make it work with TMRpcm.

the virtual wire library has been obsoleted, and you should now use the RadioHead library. In this RadioHead Library, you can edit the RH_ASK.cpp file, and uncomment the #define RH_ASK_ARDUINO_USE_TIMER2 near the top.


text:
Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600
This is a follow on question from How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?
I did manage recompile optiboot bootloader to work at 57600 bps and uploaded it to a couple of ATmega328-PUs. I just changed the BAUD_RATE to 57600L in Makefile and recompiled it.
They worked just fine with my Arduino Single Sided Serial (Severino) and a couple of custom standalone Arduino boards with FTDI-like header.
However, I couldn't program the same MCUs using my Arduino Uno R3. When I try to upload a sketch, avrdude just sits there waiting for a response that doesn't come. The output I got is something like this:
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Ricardo\arduino-1.0.5\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv:
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

Would that have anything to do with the 2nd MCU that acts as the USB driver on the Uno - the ATmega16U2? Do I have to patch it, too?
So, my questions are:
1. Why my recompiled optiboot didn't work with my Arduino Uno R3?
2. What can I do to check what's wrong with the upload process using my new bootloader?

What do you mean by "you couldn't program the same MCUs using your Uno R3" ?  Are you trying to use the Arduino as an ISP to program something else?  Are you putting a chip already loaded with this bootloader into your R3 and trying to talk to it there?

@ChrisStratton - It's the 2nd option. I burn the modified bootloader into an MCU (using my Uno as ISP), then I remove the ISP circuitry, put that MCU with the modified bootloader into the Uno R3 socket and try to upload a sketch using regular serial programming via USB. The Uno doesn't respond to an upload operation with the MCU with the modified bootloader in the UNO (as its main MCU).

Can you try this with some other custom baud rate than 57600?  Apparently this is special cased in the USB serial firmware; perhaps you should compare to the calculation in your bootloader.  See https://github.com/arduino/Arduino/blob/master/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial.c#L209

@ChrisStratton - I couldn't compile the bootloader with any speed below 57600. I started to get compiler errors that I couldn't fix easily. Maybe I should post that problem as a separate question and try harder now that you think there's a way out.

@ChrisStratton - Did you notice I'm using ATmega328-PU and not the more common pico-power version ATmega328P-PU? Does it matter?

@ChrisStratton - OH BOY!! WHAT ARE THE ODDS??? It worked at 76800!! Many thanks! Just got this new message avrdude: serial_baud_lookup(): Using non-standard baud rate: 76800 but other than that, uploading now works fine. Post your comment as an answer and I'll accept it.

@ChrisStratton - So, what's so special about 57600 baud?

Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account.  My gut feeling is that different implementation are using different approximations.  If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable.  If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

@Chris here's the source-code for the optiboot I've used. It's from Arduino IDE 1.0.5 for Windows:  http://pastebin.com/d8NUirfZ

Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see source-code here) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.
It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.

Note I did not say you cannot use 57600, though it seems you may have to modify one end to give them a more closely matching approximation of it.  Since the serial blocks on the two chips are similar, this should be fairly straightforward.  The problem is the software which configures the similar registers in each is fairly different.

@ChrisStratton - Ok. I tried to edit my answer to match what you said, but feel free to edit it yourself if you think you can express it better.


text:
Move robot through the waypoints
My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..
My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.
Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?

What have you tried so far? Can you get the robot to drive around (e.g. forward a while, turn left, back a while, turn right)? Can you talk over bluetooth from the PC to the robot?

Yes I can control robot movements using keyboard as a joystick. And I can talk over Bluetooth from the PC to the robot

With the arrangement you have described I would say it's very very hard to do what you want.

You know where the robot is
You know where the robot has to get to
You can easily calculate the direction the robot has to go in (simple trigonometry from school)

But:
You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.
So either you need some kind of calibration procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.
The latter is probably the easiest.  Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape.  What that shape is can be up to you, but there is one big constraint: It must have a clear direction to it (i.e., it must have no rotational symmetry.  Triangles are good since they only need 3 LEDs.  An equilateral triangle though wouldn't work since in three different rotations it would look the same.  However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.
You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.
Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.

Other option: use 2 LEDs of different colour, like RED and GREEN. That will simplify the calculation, as it only requires calculating the line passing through 2 points.
For supporting multiple robots: use blinking patterns, each robot could encode its unique ID, as long as it's not too fast for the camera.

@IgorStoppa I assumed the use of IR LEDs was specifically stipulated because it was easier for the camera to isolate from the backround image. Using visible LEDs would require considerably more complex processing.

It should be a matter of running a 1-pass filter on the image.
Should be piece of cake for OpenCV.

If IR leds is a requirement, you might still get away with having two LEDs, and have one on continuously, the other strobing; depending on the camera, either the strobing one will be dimmer (ideally), or will be there sometimes, not there the rest of the time.

This depends if you want the hypothetical best solution, or if good enough is good enough.
If good enough is good enough, I'd take the following approach:
Work out the distance from your robot to the first waypoint; move forward. Work out how fast you're moving towards (away from) the goal. Turn left a bit, go forwards again; did things improve (less away from/more towards)? If not, turn slightly right. Keep turning this way (left or right), and going forward a bit; whenever your speed towards to the goal gets worse, change your turning direction.
This should get you to where you are going.
Then, start making improvements.
If you are moving away from the goal (distance is increasing), your rotates can be quite sharp; as your approach speed to the goal increases, make the rotates smaller.
You could also try rotating while driving - if you are driving forward, and want to turn slightly left, run your left wheel at 90% of the speed of the right.
With a bit of trial and error, you should be able to end up with a table - work out your approach speed, look up in a table (or formula) how fast your slower wheel should go - from 0% (or even 100% reverse!) if moving away from your goal, to 100% if you are going at your driving speed towards your goal. Remember that if you are turning, you will approach it more slowly than if you are going straight. And if you start to turn and things get worse, then you are turning the wrong way.


text:
TCP or HTTP connection between web server and arduino
If arduino works as a client and tries to connect to web server (the server is mine), should I connect to it via TCP or HTTP connection? Data will be simple strings (20 chars at max) so TCP connection should probably be enough?
The connection has to work in both ways - web server sending data to arduino and arduino sending data back to server.

It's time you learned the OSI 7 layer model: PDNTSPA.
HTTP is a Presentation (protocol) that runs over a TCP Session.  If you are interacting with a web server then you will be opening a TCP socket and sending HTTP requests.
There is no other way of talking to a web server. It only speaks HTTP, and you can only connect to it through TCP.

Oh god this is awkward, thank you. Somehow I thought HTTP/TCP are different things in my case.


text:
Ethernet shield reset problems
I know there are multiple threads about ethernet shields not starting properly after power up and that there are versions that don't have those problems. But which versions are okay? Which versions do not require extra soldering/pin bending/physical resets?
How good are chinese rip-offs of those versions?

Does the Ethernet shield also have an SD? In that case check that the chip select pins are disabled in the setup().

It does have a SD card slot, but I don't use sd card at the moment.

This might be of some help. http://forum.arduino.cc/index.php?topic=25634.0

Yep I checked it, but I'm still looking for a way that doesn't include bending pins, extra soldering or extra code. If you look at the #41 comment in the link you posted, should that work? What about #48, what version is that?

I have worked with Ethernet Shields and modules. Most of them has reset issue. So I just put a 100nF Capacitor between the reset pin and ground pin. This solution works for most of the time.
This issue is there because the IC on board the shield does not have the power on reset option.
You can also tie the reset pin of your module with the reset pin of the Arduino.

If you don't want to make any modifications to the shield, and you don't want to make any modifications in code, then there really is only one option:

Don't use cheap knockoffs, but buy a genuine Arduino one.

If you have a board that requires modifications to work properly and if you're unwilling to make those required modifications then you can not just magic it into working by waving your magic wand.

I know, but the problem is that the same thing is happening on the original version of arduino shield. I want to buy another original, but there is no way of me buying it if the same problem will happen again.


text:
sending multiple signals at the same time, with short delay
Is it possible to do something like this: send a HIGH signal to an output pin, after a 0.33s delay arduino sends HIGH signal to another pin, and after another 0.33s delay, arduino sends signal to third pin. There has to be 90 seconds long high signal for each pin, but with 0.33s delay between each other.
Sooo something like this; start of the high signal on left, stop on right side:
pin1: 0 ...... 90.00
pin2: 0.33 ... 90.33
pin3: 0.66 ... 90.66

Is there a way to solve this?

Yes. Read the BlinkWithoutDelay example and triplicate it.

Great, thank you! So if I just need to do it once (no need to blink in my case) I can do a while loop with a counter (to 3, for 3 pins), and increment the counter (+set the signal to LOW) when there is 90s (90000ms) from the start.


text:
Arduino UNO USB not recognized
I've just received my Uno today and already I think I may have broken it :(
I was able to connect to usb and upload a sketch (the blink). However, I then tried to connect a circuit to do the Hello World LCD example. After trying this a few times, I noticed the LCD chip get very hot...and I had mis-wired it. In any case, after a few more tries, the USB connection to my Arduino UNO stopped working.
I tried swapping the cable, connecting it to another mac and to a windows with no luck. I'm worried I may have shorted the USB bus chip when trying Hello World.
I also tried connecting a 12V DC power supply.
I still get the green power light and the amber L light...
Did I break my Uno?
How do I troubleshoot this one?
thanks

What do you mean that it "has stopped working?" Any errors? Right COM/board selected? Any luck with no LCD?

Basically the serial USB didn't show in the list of ports and also it doesn't show in the mac system profiler...no luck with the lcd

Try reflashing the firmware on the atmega8u2. You might be able to do this using dfu, if the bootloader on it wasn't corrupted (too).

Very similar disscussion: http://arduino.stackexchange.com/q/129/37

When the LCD pulled enough current to overheat, the Arduino's power supply (which I gather was the Uno's USB interface, at the time) was probably stressed to the point of failure. One fortunate result is that the Arduino took the hit instead of the computer's USB port that was supplying it. It's not clear which part was involved but here's a discussion on another forum concerning a similar failure and replacing the ATMegaxU2 which does USB-interface duty on the Uno (x = 8, if it's a rev 2 Uno, x = 16, if rev 3). It may be possible to replace the failed chip - regulator or USB interface (though with LEDs working, it's probably not the regulator). Otherwise, you can probably still program it with an ISP (In System Programmer). But the easiest way to do that is probably involves another Uno.

Replacing a QFN is no easy feat. Drawing to much current however shouldn't break the atmegaXu2. The u2 is only connected to the atmega328 via TX and RX, and those connections have a resistor. My suggestion would be to try reflashing the firmware on the atmegaXu2, and maybe replacing the atmega328 (which is could be broken due to excessive current through one of the IO pins).

You can try and buy the Arduino serial board, and connect it directly to the pins on the Arduino , see if this works, basicly override the Arduino's own interface, or if you have another Arduino you can try and "serial" connect them using the first Arduino as ISP.
Else it is like JRobert says, you could move the chip from another arduino burn it on that one and then put it back, using the second Arduino as a run only.
Last but not least, you may find a cheap broken Arduino board on some online auction site, where the chip is broken, then move the defect chip to your defect board, and the working chip to the working board, and throw the defect Arduino in the electronics recycling.


text:
Arduino starter kit example LEDS modification
I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.
The point is to have a green LED shining, and when pressing the button the two red LEDs blink.
This is the code:
int switchState = 0;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // the button is pressed
  digitalWrite(3, LOW);

  digitalWrite(4, LOW);
  digitalWrite(5, HIGH);
  delay(250); // wait for a quarter second
  // toggle the LEDs
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  delay(250); // wait fo a quarter second
}

void loop()
{
  switchState = digitalRead(2);
  // this is a comment
  if(switchState == LOW)
  {
    // the button is not pressed
    digitalWrite(3, HIGH); // green LED
    digitalWrite(4, LOW); // red LED
    digitalWrite(5, LOW); // red LED
  }
  else
  {
    // the button is pressed
    digitalWrite(3, LOW);

    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
    delay(250); // wait for a quarter second
    // toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); // wait fo a quarter second
  }
} // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.

Thank you, I checked it with different LEDs and with its own resistor and everything ok.


text:
Program stops working after a minute
I have made this small program to lighten up in sequence 8 LEDs, it starts fine, but it stops working after a minute or so and the first 2 LEDs stay permanently ON, its like the chip stoped, here is the code :
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<9; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  right();
  left();

}

void left (void) {
  for (byte i = 0; i<9; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (byte i = 8; i>0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

I am using a very old arduino duemilanove.

You had several problems with your loop conditions.  Arrays are 0 indexed. If we declare const byte led[8], led[0] is the first element and led[7] is the 8th and last element.
Also, in void right(), you declared i as a byte which is an 8-bit, unsigned number from 0 to 255. While you wrote the conditional to be i>0, it needs to be i>-1 or i>=0. So, if we change the coditional and keep i as a byte the loop would decrement i like 8,7,6,5,4,3,2,1,0,255,254... forever.  So instead, i should be declared as a char which is an 8-bit, signed number from -128 to 127.
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {
  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {
  right();
  left();
}

void left (void) {
  for (byte i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (char i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

+1 even though Peter said it above, until I saw 8,7,6,5,4,3,2,1,0,255,254... the penny hadn't dropped.

Your loop conditions aren't quite right, which could be resulting in undefined behaviour. I highly doubt it would cause it to stop working spontaneously, but it's possible in theory.
In each loop that counts upwards, you basically need to stop before the counter reaches 8. For example:
for (byte i = 0; i<8; i++) ...

Note that it's i<8 instead of i<9.
The reason is that the array is only 8 elements long, so the indices run from 0 to 7 (inclusive). Currently, your loops are going all the way up to and including 8, which means it's trying to read past the end of your array.
You'll need to fix that in setup() and left().
The loop that goes downwards in right() is a little more difficult. At the moment, it runs through indices 8 to 1, meaning it has the same problem of reading past the array. However, it also never actually reaches index 0.
It's harder to fix because byte is an unsigned type, so you can't use i>=0 as your condition (as it will never terminate). Personally, I would rewrite the loop to count upwards, but then reverse the index order inside the loop, so that 0 becomes 7, and so on. For example:
for (byte i = 0; i<8; i++) {
    digitalWrite(led[7-i], HIGH);
    delay(50);
    digitalWrite(led[7-i], LOW);
}

Like I said, I doubt this will actually solve your problem. It's worth trying though.

Thank you guys, its fixed now, i just dont understand why i cant use byte if i do, i>=0, this way i never goes to 255 anyway and if does, it doesn matter, unless im missing something.
Here goes the final working code :
/*
  Blink
  Turns on all 8 leds in sequence back and forth.

 */

// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const char led[8] = {0,1,2,3,4,5,6,7};
#define speed 40

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (int i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  // Turn off the buzzer on pin 13
  digitalWrite(13, LOW);

  while(1) {
  right();
  left();
  }

}

void left (void) {
  for (int i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (int i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

yeah it will, in a for loop where the a byte is decrementing, if you use: i>=0 then this will always evaluate to true. When i==1 it will decrement to 0. When i==0 it will decrement (and rollover) to 255. This wouldn't be a problem if you used i>0 (or used a signed type), but then you wouldn't be using the 0th byte because you'd be leaving the loop before 0 was iterated over, ie led[0].

But then i == 255  will be false ?????

but i>0 would be true :)

also, it would matter because if it did go to led[255], that is pointing to another area of ram not associated with led and would be unpredictable


text:
Arduino UNO with NRF24l01 + touch screen
I have an Arduino UNO, a NRF24L01 as receiver (receive data from elsewhere), and this touch screen from Adafruit for display and control.
The Adafruit TFT is a shield so it fits the UNO perfectly.
I wonder if this TFT shield can share SPI pins with NRF24L01?
Given that I use pin 10 (=SS) for TFT and pin 8 (=SS) for NRF24L01, with set (SS, low) to toggle between two slaves (TFT and nRF24)?
Somehow it doesn't work once I start to share SPI pins (11, 12, 13) between two slaves.

Did you check the schematics for the TFT? https://cdn-learn.adafruit.com/assets/assets/000/013/453/original/adafruit_products_tftshieldv2.png?1388769644. Looks like pin 8 is already in use.

The TFT you mention is much more than just a TFT, it seems to include a touch screen and also a SD card reader. Depending on what parts you use, the list of pins available may differ.

I think you'll need to show more of what you've done so far (NRF24L01 wiring, code for your sketch, debug traces...) as of now, it is rather difficult to answer your question with the little description you made of your problem,

You also have to ensure any libraries that also use SPI are capable of operating with multiple SPI devices on the same bus. Another thing you have to look out for is with certain SPI devices is that they lock up the bus making it impossible to use more than one device on the bus. There are a lot of variables you need to define before we can help you more. So, what TFT library and what nRF24 library are you using?

Why not use SoftwareSPI with the NRF24L01? IIRC, the maniacbug and tmrh20 NRF24 libraries both support it. It would also prevent the issues mentioned by Avamander.

Look, you are making a big mess here. How about registering as one user, rather than making post after post as user27030, user27141, user27142, user27143, user27144 and user27145? That makes it very hard to follow.

Please use the Post answer button only for actual answers. You should modify your original question to add additional information. I've deleted all your "answers". Slow down and edit your original question to add further information. This isn't a forum, and answers are not for adding more details. Format code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.


text:
IRRemote send and receive same Arduino
I am an Arduino (and C/C++) newbie so apologies if I am missing something obvious.
I am using IRremote (github link) as my IR library.
I can get the simple send and receive demos working  individually.
However, I cannot get send AND receive working in the same Arduino at the same time.
I do not wish to do something like the "IRrecord" example but what I do want to do is have Arduino send and receive at all times and then trigger alarm/LED once the "beam" is broken.
I am using a TSOP 22 series as my IR receiver. I have tried to use protothreads but no luck. Any tips appreciated.
My current code snippet:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("IR Receiver... Started");
}

void loop() {
  //single threaded nature seems to break below

  // i want to start receiver here
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  //delay(5000);

  //trying to send here
  for (int i = 0; i < 3; i++) {
    irsend.sendSony(0xa90, 12);
    Serial.println("Sent Sony......");
    delay(40);
  }
  //delay(5000); //5 second delay between each signal burst
}

I managed to do this using solution from Ken Sheriff's Blog. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...
#include <IRremote.h>

#define PIN_DETECT 2
IRsend irsend;

void setup()
{
    pinMode(PIN_DETECT, INPUT);

    Serial.begin(115200);
    Serial.println("READY");

    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

    // Note : the IR emitter is on PIN #3
    irsend.enableIROut(38);
    IREmitterOn();
}

// Use this function instead of delay() as delay() does not work in interrupt callbacks
void pause(int ms) {
    // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
    for (int i = 0; i < ms; i++) {
        delayMicroseconds(1000);
    }
}

void IREmitterOff() {
    irsend.space(0);
    pause(60); // 60 ms is OK for my TSOP but should be tuned
}

void IREmitterOn() {
    irsend.mark(0);
    pause(10);
}

void switchOffOnIREmitter() {
    IREmitterOff();
    IREmitterOn();
}

void checkIRBeamBreak() {
    int val = digitalRead(PIN_DETECT);
    // LOW : no beam break
    // HIGH : beam break
    if (val == LOW)
        return;

    detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
    switchOffOnIREmitter();
    if (digitalRead(PIN_DETECT) == HIGH) {
        Serial.println("IR BEAM BREAK !!!!");
    }
    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
}

void loop() {

}

based on the concept of user1843591 answer, i researched some more and found the example of Nick Gammon in the arduino forum.
after some tweaks i came up with the following:
(based on both)
it uses Timer1 to generate a 38kHz signal and
Timer2 to generate a 760Hz cycle that switches the 38kHz signal on and off.
this way the recommend pulse-cycles and gap times for the Receiver (for me TSOP4438) is preserve.
it also implements global flags to decouple  the ISRs & mainloop.
(both files should be in a folder IR_TSOP4438_light_barrier)
IR_TSOP4438_light_barrier.ino
// simple light barrier test

extern volatile bool light_barrier_broken;

void setup(){
    Serial.begin(115200);
    Serial.println("IR_TSOP4438_light_barrier");
    Serial.println("setup...");
    setupIRLightBarrier();
    Serial.println("running.");
}

void loop() {
  if(light_barrier_broken) {
    Serial.println("light barrier 1 break detected");
    delay(20);
    digitalWrite (LED_BUILTIN, LOW);
    light_barrier_broken = false;
  }
}

ir_light_barrier.ino
// based on
// Example of modulating a 38 KHz carrier frequency at 500 Hz with a variable duty cycle
// Author: Nick Gammon
// Date: 24 September 2012
// https://forum.arduino.cc/t/how-to-create-a-38-khz-pulse-with-arduino-using-timer-or-pwm/100217/44

// tweaked for TSOP4438
// https://www.vishay.com/docs/82459/tsop48.pdf
// find max burst length and min gap times:
//
// Minimum burst length 10 cycles/burst
// After each burst of length 10 to 40 cycles
//  a minimum gap time is required of ≥ 10 cycles
// Maximum number of continuous short bursts/second: 1500
//
// translates to:
// 38kHz = 26,3 us / Pulse → *10= 263us
// max burst length: <= 1052us  (26,3*40)
// min gap   length: >=  263us  (26,3*10)
// total cycle time of (1052+263=) 1315us
// that violates the max bursts/second (666us/burst)
//
// on option is to optimize for the most bursts/second:
// so we use the min gap time as given and use the rest of the available time.
// 666us - 263us = 403 us burst length
// hopefully this way the AGC does not filter our stream...
// we now have to fit this to the best available prescaler / counter values:
// 672us fits good (this way we have less than the 1500 burst)
// this translates to 42 counts a' (0,0625us*256=) 16us
// so we use a gap length of 16us*17 = 272us
// this gives us a burst length of 16us*(42-17)= 400us
//
// second option is to optimize for the longest burst length and have less bursts/second.
// here we will use a in-between leaning towards longer bursts:
// 0,0625us*256=16us
// 16us*50counts =  800us = 0,80ms = 1250,00Hz = 1250bursts/s
// 16us*80counts = 1280us = 1,28ms =  781,25Hz = 781,25bursts/s
// gap   length: 16us*17      =  272us
// burst length: 16us*(80-17) = 1008us

// http://www.gammon.com.au/forum/?id=11504
// Timer 1
//   OC1A: D9
//   OC1B: D10
const byte LED = 9;

// Timer 2 (8bit)
//   OC2A: D11
//   OC2B: D3

// https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte light_barrier_PIN = 2;
// const byte light_barrier_PIN = 3;

// global flags to be handled in the main loop...
volatile bool light_barrier_broken = false;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;
// (16000000 / 38000) = 421,05
// this only works on Timer 1 - as it is a 16bit timer.

// // ------------------------------------------
// // this is about the slowest possible setting.
// // timer2 target counts:
// // CPU          16MHz (0,0625us)
// // target       63Hz (16000us = 16ms)
// // prescaler    1024
// const long timer2_top = F_CPU / 63L / 1024;
// // (16000000 / 63 / 1024) = 250

// // ------------------------------------------
// // optimized for ~1500 bursts /second
// // target counts:
// // CPU          16MHz (0,0625us)
// // prescaler    256
// // target       1,488kHz (672us = 0,672ms)
// const long timer2_top = (F_CPU / 256L) / 1488L;
// // (16000000 / 256) / 1488 = 42
// // calculate on / off ratio (toggle point)
// const long timer2_compare = timer2_top * 400L / 672L;
// // 42 * 400 / 672   = 42 - 17   = 25

// ------------------------------------------
// in-between -  leaning for longer bursts
// target counts:
// CPU          16MHz (0,0625us)
// prescaler    256
// target       781kHz (1280us = 1,28ms)
const long timer2_top = (F_CPU / 256L) / 781L;
// (16000000 / 256) / 781 = 80
// calculate on / off ratio (toggle point)
const long timer2_compare = timer2_top * 1008L / 1280L;
// 80 * 1008 / 1280   =  80 - 17  =  63

volatile bool sender_active = false;

void light_barrier_ISR() {
    if (
        sender_active
        && digitalRead(light_barrier_PIN) == HIGH
    ) {
        digitalWrite (LED_BUILTIN, HIGH);
        light_barrier_broken = true;
        // if() {
        // }
    } else {
        digitalWrite (LED_BUILTIN, LOW);
    }
}

ISR (TIMER2_COMPA_vect) {
    // used to combine the two timers...

    // toggle D13
    // PINB = bit (5);
    // digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)) ;

    if (sender_active == false) {
        // enable timer1 output
        TCCR1A |= bit(COM1A0) ;  // Toggle OC1A on Compare Match
        // digitalWrite (LED_BUILTIN, HIGH);
        delayMicroseconds(100);
        sender_active = true;
    } else {
        sender_active = false;
        delayMicroseconds(100);
        // disable IR-Receiver Input check
        //detachInterrupt(digitalPinToInterrupt(light_barrier_PIN));
        // disable timer1 output
        TCCR1A &= ~bit(COM1A0) ;  // DO NOT Toggle OC1A on Compare Match
        digitalWrite (LED, LOW);  // ensure off
        // digitalWrite (LED_BUILTIN, LOW);
    }
}

void setupIRLightBarrier() {
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);

    // set up Timer 1 - gives us 38.095 KHz
    TCCR1A = bit (COM1A0); // toggle OC1A on compare
    TCCR1B = _BV(WGM12) | _BV (CS10);   // CTC to OCR1A, No prescaler
    OCR1A =  (16000000L / 38000L / 2) - 1;  // zero relative

    // setup Timer 2
    TCCR2A = 0;
    TCCR2B = 0;
    // toggle OC2A on compare
    // TCCR2A |= bit(COM2A0);
    // fast pwm to OCR2A
    TCCR2A |= bit(WGM21) | bit(WGM20);
    TCCR2B |= bit(WGM22);
    // prescaler 1024
    // TCCR2B |= bit(CS22) | bit(CS21) | bit(CS20);
    // prescaler 265
    TCCR2B |= bit(CS22) | bit(CS21);
    // top
    OCR2A = timer2_top - 1;  // zero relative
    // switch point
    OCR2B = timer2_compare - 1;  // zero relative
    // enable interrupts
    TIMSK2 = bit(OCIE2A);
    // TIMSK2 = bit(OCIE2B) | bit(OCIE2A);

    // enable IR-Receiver Input check
    attachInterrupt(
        digitalPinToInterrupt(light_barrier_PIN),
        light_barrier_ISR,
        CHANGE
    );
}

I THINK the problem is that the Arduino takes some time (very minimal) to send the signal, but when it comes to receive it, the signal has already dissipated though your room.

send and receive at all times and then trigger alarm/LED once the "beam" is broken.

Use a laser, it's cheaper, more acurate, and more "James Bond'ish'" :)

Thanks for the idea @Dat Ha. I considered it, it is cooler!....but I ruled it out as this project will be used by kids so I thought best to avoid lasers! thanks for taking the time to respond

This theory here is not really correct - while the light propagation is fast enough to ignore, the response time of a demodulating detector is Arduino-scale.  The issue is one of software architecture - IR remote control schemes are not applicable here, rather what is needed is to be sending modulation (pulsing on and off) and checking the receiver at points in between.  But also note as the correct answer clarifies that the modulated signal itself must be pulsed on and off at a slower cycle time, or the detector will reject it.


text:
Sweeping servo 90 degrees
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

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

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

I have found this code that makes servo go 180 and back, but when I switch 180 degrees with 90, which is what I need, my servo doesn't do that (I tried the code in Arduino simulator).
Do I have to change something elese in the code (like delay time) so it whould go 90 degrees up and then 90 down?
Here is the link of circuit:
https://circuits.io/circuits/3597808-servo-90-degrees

when I swtich 180 degrees with 90 witch is what I need, my servo doesn't do that - So what does it do? ... (I tried the code in Arduino simulator) - What happens with a real Arduino and a real servo? Simulators are merely an approximation. They can never be as good as the real thing.

@Majenko What he does is go 180 degrees up and starts sweeping between 180 and 90 degrees. It is really strage actually, beacuse I didnt inculde 180 degrees in code at all. You think Arduino simulator isn't accurate with servo's?

It sounds like the simulator is rubbish. Get a real servo for your Arduino. They are dirt cheap.

Either that or you are misinterpreting the servo output and what you think is 180° is actually 0°.

@Majenko I will try with real servo but the odd thing is that this first code that I posted is working just for 180 degrees and back, for every other number servo is turning in range between 90 and 180 degrees. BDW simulator is from Autodesk circuits.

Make video of the output and then post it.

@DatHa I edited the question.

No you don't have to change any time delay in order to get it rotating by 90 degrees, delay would just change the speed of rotation of the servo. The simulator you are using is at fault here as the sketch with 180 changed to 90 works flawlessly.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

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

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

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

MAKE SURE THAT YOU CHANGE BOTH OF THE 180'S TO 90.

That is what I did, and still nothing..

I just created a simulation on Wokwi Arduino simulator based on your code and it works perfectly fine.
Here is the permanent link

When you first click the "play button", the servo animation jumps around wildly. Why is that happening?

This line of code will properly set up the PWM timers to output the correct signal to move the servo to the value set in 'pos'
myservo.write(pos);

It has nothing do with speed. The servo will try to reach 'pos' as fast as possible.
The delay(15) in your code is the delay time between each "myservo.write(pos);"
The for loop works like this:
myservo.write(0); // Go to 0 degrees
delay(15); // Wait 15ms
myservo.write(1); // Go to 1 degrees
delay(15); // Wait 15ms
myservo.write(2); // Go to 2 degrees
delay(15); // Wait 15ms
myservo.write(3); // Go to 3 degrees
delay(15); // Wait 15ms

etc...
The time in seconds it takes to make a rotation is (range_in_degrees x 15)/1000
e.g. 180deg x 15ms/1000 = 2.7 seconds
90deg x 15ms/1000 = 1.35 seconds
Increasing the 15ms delay will make the servo rotate slower.
Also, make sure that you change the 180 degrees to 90 in BOTH for loops. If you change the value in one, the servo will slowly sweep from 0 to 90, then jump to 180 and slowly swing back to 0 and repeat. (or vice versa, depending on which one you forgot to change)


text:
I got a missignatured ATmega328-PU. How can I fix that?
Sometime in the past, I was burning bootloaders on a fresh batch of four ATmega328-PU using the Arduino IDE (notice there's no P after 328 - it's the slightly cheaper non-picopower version of the MCU, not to be confused with the ATmega328P-PU with a P), and was surprised with the following message from avrdude:
avrdude: Device signature = 0x1e950F
avrdude: Expected signature for ATMEGA328 is 1E 95 14
Double check chip, or use -F to override this check.

That means avrdude thought the chip was not what its label said. Then I changed the chip type on my Arduino IDE to ATmega328P-PU and avrdude burned the bootloader without complaints. What that means is that the chip was labelled as one MCU and internally it responded as another, slightly different.
What I would like to know is:

How rare is this event? Has anyone had a similar experience? (Original question, off-topic)
Is it possible to fix this? How can I fix the signature so that avrdude recognize the chip correctly?

This is a cross-post from EE.SE. I posted this question there but didn't attract much attention, so I wanted to see if anyone from our community had a similar experience.

It seems that your vendor simply mislabelled some 328P's (which is what this signature represents) as 328s.

While browsing sparkfun, i have found several news posts that show their struggle with mislabeled chips. Here are a few:

https://www.sparkfun.com/news/350
https://www.sparkfun.com/news/384
https://www.sparkfun.com/news/364

Sparkfun had received a questionable shipment if ICs from a new seller in china. They decided to test them before sending them into production, and none of their test boards worked. Using nitric acid, they were able to remove the case of the ICs and fould a hunk of metal that looked like copper.
In another article, they dissected some suspicious ICs from Atmel, and found an ON semiconductor silicon wafer inside. The chips were not functional ATmegas, but they did have silicon, unlike the other ones.

Can you flesh this answer out a bit? Summarizing the articles you linked to would be a good start - right now, if sparkfun goes down for any reason your answer will be worthless.

@Shog9 Why? The question is way off base. This answer is a summary of instances of people receiving mislabeled chips (essentially people sharing experiences). Who is this going to help?

I could ask you the same, @AsheeshR - why worry about an answer when the question is the problem? Anyway, thanks for adding the detail, TheDoctor.

Not the preferred way to fix things and certainly not the first solution to consider, but you can consider programming the signature bytes. Before attempting this be absolutely sure you really want to do this and you have investigated what is involved to undo this. This may involve changing configuration files on your computer ...
Anyways the way to set the controller's signature bytes is as follows (untested, I don't have a spare AVR lying around):
avrdude -p atmega328 -c arduino -P /dev/ttyUSB003 -b 19200 -v -U signature:w:0x1E,0x95,0x14:m

I know this is very late, but I don't think it's a good idea to let this stand as the accepted answer unchallenged: The signature on an atmega328 is not writable, and to my knowledge, the signature is not writable on ANY atmega or attiny.

Out of interest, I tried the above approach, which avrdude accepted in a sense: avrdude: writing signature (3 bytes) - however it failed to do it: avrdude: verification error, first mismatch at byte 0x0002: 0x14 != 0x0f

There are several different flavors of ATMega328. The most commonly found in Arduinos Uno (et al) is the ATMega328P, which is Atmel's "picopower" version; this one has the 0x1E950F signature that AVRDude expects when it's tasked with programming an Arduino Uno. Gee, figure that.
Less common is the base model ATMega328 (no suffix) and the ATMega328PU, both of which yield a 0x1e9514 signature instead of the expected 0x1E950F.
As to commonality... that depends upon the crowd with which you run. If you are Arduino through-and-through, never use any boards that aren't teal-colored, then it's extremely uncommon for you to find a non-ATMega328P. If, on the other hand, you run in my gang and build all manner of cool stuff on funny-colored boards that don't have staggered header pin spacing in one spot... then it's very common to get non-p '328s.
There are workarounds. There was for a while a variant ArduinoISP_Multi that would translate a 0x1e9514 signature to a 0x1E950F signature, permitting you to gleefully program your breadboarded or otherwise non-teal '328 boards exactly as if they were genuine Arduino Unos. For whatever reason that "sketch" can no longer be found.
You can also edit avrdude.conf (with backup, please!) such that it (AVRDude) expects the signature that your '328 coughs up. The backup is particularly important because you may want someday to program "real teal". The avrdude.conf file can be found in your Arduino installation at ...\hardware\tools\avr\etc.
OR... wait! There's MORE! All for one money! You can also write your own hardware profile for non-P '328s and put it in your Arduino "sketchbook"'s hardware directory, then draw from that as a custom board definition. Aw, shucks... it ain't that hard! Really! I've written several of those for my own board designs.