text:
How to switch program in arduino using android app?
I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze.
                   Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

Why don't you make just one program to run all?

Never mind I just found the solution.Thank you for your reply though.

If you know the solution you should post it as an answer.

The answer is a little bit complicated.I'll post it as soon as possible.

Once I made a sketch to run multiple programs. I wrote a setup and loop function for every different "program", (e.g. setup_p1, setup_p2, ... loop_p1, ...) and then wrote a simple main sketch to handle them all.
In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.
I choose to use a callback because it's faster than just checking the mode every time, at least in my case
// callback for loop function
typedef void (*loopfunction)();
loopfunction currentloop;

void setup()
{
  // Set dip-switch pins as input
  pinMode(MODE_PIN2,INPUT_PULLUP);
  pinMode(MODE_PIN1,INPUT_PULLUP);
  pinMode(MODE_PIN0,INPUT_PULLUP);

  // Concatenate the dip-switch values
  byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

  // choose the correct mode
  switch(mode)
  {
    case 0: // Shutdown - do nothing
            break;
    case 1: // Program 1
            setup_p1();
            currentloop = loop_p1;
            break;
    case 2: // Program 2
            setup_p2();
            currentloop = loop_p2;
            break;
    ...
  }

  // Not a valid program: halt
  if (!currentloop)
  {
    while(1);
  }
}

void loop()
{
  // Execute the current loop
  currentloop();
}


text:
Is it possible for ThingSpeak to show a simple table of all data collected?
I just recently found the ThingSpeak platform for the IoT. I have been playing around with its features a bit, but I have not found a way for it to show a simple table of all the data collected. For example, the table might have humidity, temperature, and timestamp columns, and then every time data is written to ThingSpeak, a new row would be added with the latest readings. I would be surprised if this is not possible with all of its complex graphing tools. Has anybody found a feature like this?

What does this have to do with the Arduino?

Since ThingSpeak has an extensive API, you can build a tool to read in data and display it as a table. I have created a GitHub repo called, "IoT Debugger" that allows you to see data as a table as the it comes into a ThingSpeak Channel.
To use the demo, enter your channel number and the read API key.
If you want to modify the project, fork the project on GitHub.

source: Stack Exchange

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

sort: votes


text:
I want to log GPS coordinates using my Arduino and other sensors
I want to log GPS coordinates using my Arduino and other sensors.  The difficulty is that I will be in forested conditions.  Would it be better to hardwire a gps device to the Arduino or to bluetooth an external device (a much more accurate, Trimble device that I know will give me the accuracy I need)?  Can such devices pair to a bluetooth receiver that would hardwire to my Arduino, or do I need an intermediate device like my iPhone?

The GPS receiver I've always used is the Adafruit Ultimate GPS:
https://www.adafruit.com/products/746?gclid=CjwKEAjwoPG8BRCSi5uu6d6N5WcSJABHzD8FmldH1vIvTt8h-S-948CJmDR6fR_BcF20UZMS4I-AEBoCt9Tw_wcB
It comes with a spot for you to plug in an external antenna (with an adapter), so you can get more precision and presumably be able to receive data much more accurately in places like forests. However, I'm not sure of this, so an external device may be the way to go. Bluetooth would be possible, but it can be a little difficult to set up with Arduino if you lack the experience, so if you can I'd go with a wired connection (with an RS232 or other).

What's more important, GPS accuracy or GPS yield?
Normally it's a trade off between the two. Under difficult conditions such as lots of trees a high accuracy GPS may simply stop outputting locations because it can't guarantee the accuracy, it depends upon the target market for the GPS.e.g. a survey system will be very conservative, survey people don't like getting bad data. A cheaper lower accuracy GPS won't care and will still output a position no matter how dubious the signals are.
I've seen $100 GPS units output a position when a $20,000 Trimble system refuses to.
The GPS should support NMEA output over bluetooth serial port protocol which would then work fine for a direct connection to your device however you may need to change the receiver settings to enable it, the default is likely to be outputting Trimbles binary TSIP format over the bluetooth.

If the Trimble has a serial output then you could connect via that.
If the Trimble supports the same Bluetooth spec as your receiver, then there is no reason why you shouldn't be able to connect them directly. You will need to find out if the Trimble is a Master, Slave or both and buy the appropriate receiver for you Arduino.

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


text:
Arduino % symbol meaning
I dont know what meaning of this symbol - %.
for example,
buttonPressCount % numberOfLED == i
I hope anyone can tell me the name and basic function of this symbol.

I don't understand why this question was modded down so I gave it a point.

It is called the modulus operator, and it performs the modulo operation.
TL;CBR: It results in the remainder after division is performed.

It is also in the online Arduino reference: https://www.arduino.cc/en/reference/modulo


text:
How to start serial monitor on Windows startup
How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.
Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.
For Windows 10 you can make a program run at startup by following these instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.

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


text:
Ensure board is always on the same port?
I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

My experience is that the Serial-to-USB converters (of which Arduino is one) have are assigned a COM port according to the USB port they are plugged into. So if you always to connect it to the same physical USB port it will have the same number. However this number will not be the same with a different Arduino or on a different computer.

Normally, the COM port number wont change, but you cannot simply rely on this.
Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.
Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.
And, btw. it's not related to VB.net

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


text:
Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose)
I need to have several Nanos on one USB port. They will have separate power, so power constraints won't be a concern. I need them all to go through the same serial port. They will never get anything sent to them, and should never send data simultaneously. Each one is connected to a switch, and upon pressing the switch, will send an 8-digit serial number over serial. I want to have a VB.NET application which listens over this shared serial COM for numbers, and collects them all, displaying them in a history list. Can this work?

No, they can't all share one data line.  What you'll need to do is either connect all of the switches to one Arduino or connect all of the Arduinos to one "master" arduino which will communicate with the computer.

The single Master Arduino is what I'll go with. "Master" and "Slave" boards, reminds me of IDE drives lol

For a USB topology to operate one needs a USB controller which knows about all the different USB protocols necessary to communicate with all the different USB peripherals (this is why a USB controller is usually a fully capable computer) all connected through a USB hub.  It is unlikely a USB network could be created using only peripheral USB devices which were wired directly together.
To communicate between several Arduinos and a computer it would be much easier to use a serial bus made for multiple drops like RS485. There are many RS485 to USB converters available like this one for computers that do not have an RS485 port.


text:
How can I scan for a HIGH signal on digitalRead during the main loop, while running other things?
I'm working on a program which listens for certain bytes on serial through an if/then/elseif ladder. I want to also check if a pin (say, A15) has been given a HIGH state, by another Arduino with shared ground. The slave Arduino will turn a digital pin to HIGH and I want the MEGA2560 to check every time it loops if a HIGH is present from the other board. A "While button not pressed do nothing statement won't work, because that won't let the loop go. I tried doing an if statement, using something to the effect of this:
if (digitalRead(A15)==HIGH) {
  //things to do
}

But it seems no matter what I put, be it HIGH, LOW, != HIGH, != LOW, etc. or either input pinmodes, pullup or not, it always thinks the board is transmitting HIGH. In fact, it only doesn't think it's HIGH when it actually is HIGH. I'm pretty stumped on this. If you ask me, digitalRead is really odd with what's HIGH and what's LOW.

Do you declare A15 as INPUT in Setup(), pinMode(A15, INPUT);? Could you show us the entire sketch you are using?

I tried both that and input_pullup as well. I can include the whole sketch. EDIT: Actually ,unfortunately, I just looked and it looks like, because the previous sketch bricked the board, I edited it back to before this was added and neglected to save a copy of the broken code.

Do you have a custom atmega2560 pcb or a real arduino mega 2560 board or a clone? Maybe some gnd or vcc pins of the atmega2560 are not soldered. Is the arduino mega 2560 running at 5.0v? It starts to do weird things at 4.5v or lower.

It's an Elago clone of the MEGA2560 board. I have it connected to a desktop's USB port, so I doubt there's power failure.

Simplify, and show your setup code.
First, do you have a pinMode call in your setup function:
void setup() {
  pinMode(A15, INPUT_PULLUP);
  Serial.begin(115200);
}

Then use test code like this:
void loop() {
   if (digitalRead(A15) == HIGH) {
      Serial.println("Pin A15 is HIGH");
   } else {
      Serial.println("Pin A15 is LOW");
   }
}

Connect your A15 pin directly to ground with a jumper and run the sketch above. Open the serial monitor and see what is output. It should be LOW. Then disconnect the jumper and check again. It should now be HIGH. Finally, connect the jumper between A15 and +5V and check the output again. It should still show HIGH.
That lets you troubleshoot just the software piece. Once you get that working, connect pin A15 to the remote Arduino's output pin and try again.

I'll try this as soon as I get to the board tomorrow.


text:
What is the variable pot exactly for in arduino sensors boards?
I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.
Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.

It's for sensitivity adjustment.

thanks, but I still don't get what is meant by sensitivity... if there is more light for example, while it higher the threshold to which the photoresistor will saturate or will it amplify the output ?


text:
How to structure data for HTTP upload
I'm building a GPS tracker using an arduino nano, Adafruit Ultimate GPS breakout, a SD card slot and a SIM800L module.
So far everything works, the tracker uploads the data to a server as well as saving an extra copy to the SD card. The problem is now, that I don't really think that sending a HTTP request every cycle (gps data point) is very efficient and I would also like to have a way of storing information if there is no GPRS reception.
The idea is to save the GPS data to SD card and bulk send it out every 5 minutes or so.
What would be the best way to set up the data structure? I'm saving the deta in a csv style file:
2016-8-2 22:23:44, 52.53251922, 13.31121666, 18.30, 7, 1.33;

Parsing that is not the problem, but rather how to keep track of what has been sent already and what not. I was thinking about Marking the lines that I sent with a # or something similar as first character.
The only problem I could see with that would be performance, since it could take a while to go though it every time once it's getting a bit larger.
Thanks!
Lukas

The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with file.write(&your_struct, sizeof(your_struct)) and read in a similar manner into a struct.

This will reduce the number of bytes written or read for any data point, and
Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python struct module is very capable.
However, if you wish to continue with your current format, you can keep track of your current position in the file with file.position(); no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, curr_pos, and the other to hold the position of the end of the file for writing new data, end_pos. Initialize the former to 0.

You gather data as usual, and after 5 mins, you save the current file position to end_pos and seek to curr_pos with file.seek().
You read a line from the file and send it to the server.
If it's sent successfully (use the return code), you update curr_pos with file.position() so that it's now pointing to the next line in the file to be uploaded and go to step 2.
Else if the upload fails perhaps due to service, you stop uploading and don't update curr_pos. You seek to end_pos with file.seek() and go to step 1.

You will, of course, use available() to know when you've hit the end of the file to stop uploading, or you can compare curr_pos with end_pos for equality, whichever's more direct for you.
This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.


text:
Amplify Piezo Sensor
I am trying to amplify a piezo sensor per the instructions found at the link below.  I am not trying to trigger a buzzer only print to the serial monitor whether the vibration was detected or not.  I am a NOOB with respect to circuits and unable to understand why my circuit is not working.
The piezo is either giving a positive (sensing) reading or  giving a negative (not sensing) reading depending on where the poteniometer is set.  There is no state where-if all is quiet-the piezo is quite and if there is a vibration the piezo senses it and reports to the serial monitor.
I see from the blog that if the piezo get stuck on a state to lower the feedback resistor of the op-amp from 220k to 160k but again, there is never a case where it is working then get struck in state.  It is always stuck in a state!
The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor.  I am using the 10uf capacitor.  Will switching out the 10uf for a 0.1uf capacitor test potentially damage the Arduino? Is this the cause of the +-state of the piezo? Do I just have a wiring flaw?
Any advice is appreciated.
Here is a link to the post including the Fritzing diagram.
http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html
Here is a picture of my circuit.

And the Sketch...
#define VIBRATION_DIGITAL_IN_PIN 8
int DurationMillis = 1000;

void setup()
{
  Serial.begin(9600);
  pinMode(VIBRATION_DIGITAL_IN_PIN,INPUT);
}
void loop()
{
  if(digitalRead(VIBRATION_DIGITAL_IN_PIN)==HIGH)
  {
    Serial.println("I felt that");
    delay(DurationMillis);
  }
  else
  {
  Serial.println("I don't feel anything...");
  delay(DurationMillis);
  }
}

You write,

The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the high-sensitivity-vibration-sensor at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard.  This is a reasonable thing to do, to avoid power supply glitching on that board.  It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.
The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input.  This will block any DC voltage coming out of the piezo from going into the op amp input.  It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there.  A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies.  The presence or absence of that capacitor probably isn't the problem with your circuit.  Looking at your circuit photo, the wiring looks ok[*].  Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working.  If they aren't working, substitute for the LM358.
[*] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1.  Also is your comparator output connected into digital pin 8 on the Uno?  It looks more like 9 or 10 in the photo.  Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.

jwpat7, Thanks so much for your advice.  I was able to confirm that the piezo element was working by using the Knock sketch that is included in the Arduino IDE.  I finally received a  new LM358 dual-op amp (from the slow boat from China).  Using the new LM358 chip solved the problem.  My piezo amplifier is working!


text:
Amplified piezo sensor wiring problem
I am trying to amplify the signal from an Adafruit Small enclosed piezo.  The piezo is working using the Arduino Knock example but I want to increase the sensitivity using an amplifier.  The wiring shown below does not work using the Knock sketch and I am assuming it is a problem with the wetware and the wiring(NOOB here).
Any advice in amplifying the piezo is appreciated.

You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:
https://www.youtube.com/watch?v=kqCV-HGJc6A
The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...
The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.


text:
Arduino Mega 2560 Only Powers on with USB
I have an Arduino Mega 2560 board running a ramps 1.4 shield for a 3D printer.  For some reason, I can only power the Mega with USB.  It does not get power from the ramps shield and it also will not power on when plugged in to a 12v wall adapter.  I know all power sources are working because I have a second Mega that works fine on all.  What could I check on the Mega board to help figure this out.  Other than being powered only by USB, everything else works as expected with no problems.

Looking at this Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.
Looking at this ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560.  And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results.  Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.
If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.

D1 sends power from the shield down to the Arduino. I will look into the IC's on the Arduino.

st2000 In the bottom left there is the power section, where you can see that D1 puts 12V on the net labeled AM_Vin; this net is then redirected to the mega Vin pin. @JeffThomas follow the wires with a multimeter, then share the measures..

I will add a comments that it is assumed the shield is providing 12 volts through D1.   And that it is assumed testing included using a known good Arduino Mega 2560 with the RAMPS 1.4.


text:
NodeMCU : Input pullup in A0
I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.
I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.
I am setting up the gpio in the setup method like this:
void setup(void){
    pinMode(sensorPin, INPUT_PULLUP);
    ...

And my sensorPin variable is declared in the beginning of the sketch
int sensorPin = A0;

Any ideas why when I read the value in the NodeMCU I don't get the same behaviour as in an Arduino board?

Probably because the nodemcu isn't an arduino. Internal pullups on analog pins is an AVR quirk that you cannot rely on being the same on other mcus.

Sorry if I am asking really basic questions, as I am starting in this field. The final objective is to put all the code inside an esp8266, as they have an analog gpio, and I was using the nodeMCU because it was easier for me to push the code there. Is there any way to get the right analog values I get in an arduino in a nodeMCU?

The obvious way is to use an external pullup. You can guarantee it will be there then.

Reading the documentation here (https://www.arduino.cc/en/Tutorial/DigitalPins) it says that they use a 20K resistor when we activate by software the pullup resistor. I will try to use an external pullup as you have suggested. Thank you!

You're confusing Arduino with NodeMCU. NodeMCU is a completely different beast running with a different chip from a different manufacturer with a different core architecture. You cannot use Arduino documentation for low-level things like chip internals when looking at a completely different chip. That's like using a Ford manual to try and fix your VW.

What I meant is that I was activating the pullup resistor in the arduino analog gpio, and to get a similar effect I need to put an external pullup resistor in the NodeMCU to get the same values as I am getting in the Arduino. Would this work or internally the analog gpios work so differently that I won't be able to get same behaviour?

Ah, gotcha. Yes, try and keep the same value as the internal one. However the internal one could be anywhere between around 10k to 50k or more.

I just wrote this blog post you might find interesting: https://hackingmajenkoblog.wordpress.com/2016/08/12/measuring-arduino-internal-pull-up-resistors/

As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:
 .
Special thanks to Majenko for his time and patience. Cheers!

Did you have to connect the R1 across VCC (5v)? Would it still work with a 3.33v pin or should I need a lower resister in that case?

@ΕГИІИО I used the 3.3 V pin in my final project with the nodeMCU so you should be good with the same resistance. Cheers!

@PayToPwn Alternatively, you can short the A0 pin with any digital pin and pull-up that digital pin. In fact, INPUT_PULLUP on analog input pin is very useful. In that way, you can connect photo-resistor directly to the analog pin and measure light intensity without external resistors.


text:
Alternatives to read mp3 without using an sdcard as source for the files?
I am making a project that plays several sounds using a DFPlayer Mini mp3 player and a micro sd card. The size of the sounds I normally play is less than 20 MB, so a lot of space in the sd card is unused. I was wondering if there is an alternative to use an SD card to store the mp3 files, and if there is, what would be the best approach to switch to use this alternative.
Cheers!

what please is the problem you try to solve? you want a only 200 MB storage and not more?

why is the SD card free space an important factor?

The SD free space is not really important, but I wanted to know if there was a "better" alternative or a cheaper one.

The problem of all alternatives I can think of is a commercial one:Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper. Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.
Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.

I see, so it's always cheaper to use SDs to save mp3s than to store  in EEPROMs, right? As you mention commercial uses, how do they solve this issue in commercial products? Do they also use SD cards?

Depends - falsh rom in industrial use is cheap (see usb sticks) but there are no payable solutions for mkers. But if you have an old usb stick start making your own project. As an SD card is basiclly a flash rom (the biggest parts are the contacts) you could also desolder the sd-slot and directly solder the card onto the DF-Mini, but whats the difference? SD cards have no moving parts so its normally shock proof (and can be secured with tape) if thats an issue. So you see there is a difference between maker and industry ;-)

Thanks for the great explanation and examples @Codebreaker007 !


text:
Losing value of variable
I am making a project involving the AutoConnect, ArduinoJSOn and LedControl libraries to fetch some values from an endpoint.
Basically what I do is connect to the internet, fetch the values from a JSON file in a given URL, store the values in variables and display the corresponding numbers in a 7segment module (using a max 7219 module).
Everything seems to work perfectly in the first iterations of the loop program, but after some iterations switching the values from one value to another, it starts to act strangely, as the input values changed on runtime:
[AC] WiFi.config(IP=0.0.0.0, Gateway=0.0.0.0, Subnetmask=0.0.0.0,
DNS1=0.0.0.0, DNS2=0.0.0.0) [AC] DHCP client(STARTED)
[AC] WiFi.begin()
[AC] Connecting........[AC] established IP:192.168.1.139
[AC] http server started
Wifi connected: 192.168.1.139
Connected to endpoint
Daily:13.37
Monthly:1111
4
13.37
4
1111
4
13.37
4
1111
4
13.37
4
1111
4
13.37
4
1111
2
h
0

2
h
0

2
h

As you can see in the previous serial output, after the 8th iteration, everything starts malfunctioning.
The output correlates with the number of digits that will be used in the 7-segment led module ( 4 ) and the number to display ( 13.37 and 1111 ). Then it starts getting the wrong values forever.
For getting the values in the JSON I use the following code:
void fetchJSONandPutValues(){

     HTTPClient http;  //Object of class HTTPClient
     http.begin(projectURL);
     int httpCode = http.GET();
     //Check the returning code
     if (httpCode > 0) {
      //Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      daily = root["daily"];
      monthly = root["monthly"];
      // Output to serial monitor
      Serial.print("Daily:");
      Serial.println(daily);
      Serial.print("Monthly:");
      Serial.println(monthly);

      finalDaily = (char *) daily;
      finalMonthly = (char *) monthly;
    }

    http.end();   //Close connection

   //setLCDValues(daily);
}

For displaying the numeric values in the 7-segment module I have made this function:
void setLCDValues(char * value){

  int charsInValue = strlen(value);
  boolean decimalPoint = false;
  int numLEDElements = charsInValue;
  char cleanedValue[8] ;

  //look for point position
  int positionPoint = 999;

  for (int i = 0; i < charsInValue; i++){
    if (value[i] == '.')
    {
      positionPoint = i;
      numLEDElements -= 1;
      break;
    }
  }

  int j = 0 ;
  for (int i = 0; i < charsInValue; i++){
    if (value[i] != '.')
    {
      cleanedValue[j] = value[i];
      j++;
    }
  }

  Serial.println(numLEDElements);

  for (int i = 0; i < numLEDElements; i++){

    if ( i == positionPoint -1 )
    {
      ledDisplay.setChar(0, numLEDElements -1 - i, cleanedValue[i], true);
    }
    else
    {
      ledDisplay.setChar(0, numLEDElements -1 - i, cleanedValue[i], false);
    }
  }
}

And in my loop() I have the calls to setLCDValues:
currentMillis = millis();

if (currentMillis - previousMillis >= interval){

      previousMillis = currentMillis;

      if (showDaily)
      {
        setLCDValues(finalDaily);
        showDaily = false;
        Serial.println(daily);
      }
      else
      {
        setLCDValues(finalMonthly);
        showDaily = true;
        Serial.println(monthly);
      }
}

I am guessing the problem I have here might be related to using pointers, although I haven't found yet the issue here. Could it be a problem with one of the libraries ? (ArduinoJSON?)

you fragment the memory heap with DynamicJsonBuffer and http.getString()

Thanks for pointing in the right direction, @Juraj - I will try to change the DynamicJsonBuffer to a StaticJsonBuffer (as stated in https://arduinojson.org/v5/doc/memory/ )  when I get back home.

@Juraj , you were totally right here, changing the DynamicJsonBuffer to a StaticJsonBuffer solved the memory leak. Although I don't understand the issue about using the http.getString(). How does this function fragments the memory and what would be a good alternative to it?


text:
IO Control and Configuration
I am using Eclipse to program a ATMega2560 and would like to stay away from the Arduino library, While looking through AVR Examples I have seen the syntax
#include <avr/io.h>

PORTD.0 = 1

or

PORTD.DIR = 1;

instead of
PORTD = 0b11111111;

To define and control the Inputs/Outputs when I try to use this syntax I get compiler errors:
error: request for member 'DIR' in '*34u', which is of non-class type 'volatile uint8_t {aka volatile unsigned char}'

I am sure that I am simply missing a include file or something but I can't figure out what I am doing wrong.

Where did you find the example code? That is not valid syntax for the AVR io definitions. Looks like PIC.

@MikaelPatel I have seen this quite a few times while searching for AVR, here is one site http://www.elecrom.com/2008/02/12/avr-tutorial-2-avr-input-output/

That is (as below) for another compiler (CodeVisionAVR) and not AVR-GCC which is used for the Arduino IDE. I guess that something similar (e.g. PORT[0]) could be defined in C++ using a class for Ports and an index operator. The dot operator (or struct) would have to be symbols (e.g. PORT.bit0). You could have a look at Cosa, https://github.com/mikaelpatel/Cosa.

What you're doing wrong is that you're using the wrong compiler. That syntax is for CodeVision or mikroC, but the Arduino IDE uses GCC. Which follows global standards rather than making syntax up.

Holy cow! Alright I see, I thought CodeVision was an IDE or something. Too bad, that's a nice way of doing it.


text:
Arduino using LCD
I am building a project that is using A12864ZW 128X64 LCD, the question I have is should there be anything in the circuit to prevent damage to the Arduino Mega or the LCD? I am using this example here for a start.
I think I damaged one LCD with the current circuit because everything was working perfect then all of a sudden it was like the LCD Contrast was set all the way up, displaying only a dark screen but I couldn't adjust it with the U8Glib or with the V0. During programming I would disconnect the ground from the Arduino to the Breadboard, when I would do this the LCD would still flicker as it was being programmed. This is why I am wondering if I am missing something.
I read somewhere that putting a MOSFET on the Ground of the LCD that is connected to the Reset pin helps. Another problem that I am having is I am using Eclipse with the Arduino C++ add in and sometimes I can program easily, everything goes as expected but then it will fail to upload until I unplug and reset the board sometimes several times.
Because the program is using pins 11-13 it can create problems because these are the same pins used for programming if I remember correctly. I tried changing the pins used but didn't seem to help anything.

Disconnecting ground while all the other pins are connected and the Arduino is powered up is a very bad idea.  Either manually, or using a MOSFET.
Simply because the power you are feeding in to the screen wants to try and find a way to ground through some means or other - and if the ground is disconnected then that means muscling its way through the IO pins into the Arduino and through to ground that way.  The result is that you damage the LCD screen's fragile circuitry.
If you want to disconnect the ground pin at any time, you must ensure that either the power is turned off, or the power connections to the LCD are disconnected first.
If you want to have the Arduino's RESET toggle the power to the LCD to force a hard reset then you need to use a P-channel MOSFET in the power connection instead, so the ground connection is always connected.

So what is the proper procedure to keep the Mega from getting into a state where it can not be programmed? I know that continuously unplugging and plugging in the USB programming cable can not be good either.

11-13 are only used for ICSP programming (SPI). For normal USB programming it uses pins 0 and 1.

Okay, maybe it is not the LCD that is causing my problems then possibly? I have tried changing the pins used for the LCD and doesn't seem to make a difference with the Mega hanging up. Are there any "Tricks" to keeping the Mega in a state for programming? I am not sure why my Mega is getting into such a state where Eclipse cannot communicate with it until I disconnect then reconnect the USB cable.

It's highly unlikely to be the mega that is the problem, unless you are doing things with the reset pin.  It's more likely to be the computer doing something with the CDC/ACM port - maybe killing the DTR signal.


text:
Arduino Mega, ST7920 using COSA
I am trying to learn and understand the COSA Library using a 12864ZW (ST7920) 128X64 LCD Display. Right now I am able to use the LCD using the u8glib but also found that COSA has a library for the ST7920 Display, I originally used this tutorial to get things working.
The main problem that I have now is in the ST7920 Documentation there is a schematic that shows how to hook up a ST7920 Compatible LCD. The first tutorial only uses 3 lines from the Mega and the Cosa is using what looks like 6 lines.
Looking at the header file, it looks like it is derived from the HD44780 Class and what I can gather is pins 16 and 4 are hard coded for something? I am not quite clear on how to use the Cosa version of the library. Can someone please give me a explanation and perhaps a explanation on how to get this working using Cosa?

The Cosa ST7920 library uses text mode only (16X4). The ST7920 class is controlled though an adapter. There are several adapters available depending on how you wish to connect to the Arduino. They range from parallel 4-bit to SPI with shift register. The adapters implement the interface HD44780::IO. There are several LCD examples. The CosaLCDbench shows the possible configurations with LCD and Adapters. Please see the file for further details.

I saw that there are many examples but I can not for the life of me get this to compile, I opened another question at http://arduino.stackexchange.com/questions/18358/eclipse-add-library. I see that you are on the GIT for COSA can you give me any advise to get this to compile?


text:
Is there a way to pause Program execution?
I understand that Arduino programming is procedural and not so much Object Orientated and also that the Arduino or AVR are only single core processors and any kind of "Multitasking" or "Threading" is emulated at best but I was wondering if there is a way to pause program execution in one area temporarily and give another area control? For example say we have the following class:
Class A{
   void Test();
   void ProgramLoop();
}

void A::Test(){
   for (int i = 0; i < 10; i++){
      //Lots of cool stuff going on here but need to give
      //Control to someone else say ProgramLoop()
      Sleep(10);
   }
}

void A::ProgramLoop(){
   Serial.println("In Program Loop");
}

Then in the main file:
A testClass;

void Setup(){
   Serial.begin(57600);
}

void Loop(){
   testClass.Test();
   testClass.ProgramLoop();
}

I know I could do something like:
void Loop(){
   if (!testClass.isBusy){
      testClass.ProgramLoop();
   }
}

But I am trying to find out if there is a way to control how the program execution gives control? I understand that this is more of a threading topic, thats not what I am trying to get at, I just want to know if this is possible maybe using some sort of built in function or something? Or do my programs have to "Fall Through" being ONLY Procedural?

You could use a timer interrupt and build your own scheduler, like any preemptive multitasking OS on a single core machine (though resources will be tight).  But it is probably better to do your long tasks in pieces, perhaps as state machines that advance one state each time they are called.  If the thing that needs to happen in the meantime is simple, perhaps you could just do that in an interrupt on the timer or some relevant occurence (pin change, serial rx, etc)

This article gives a great example of multitasking by using FreeRTOS.
I am pasting the sample code snippet which is pretty much self explanatory.
#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}

If you have used threading before, this library-
https://github.com/ivanseidel/ArduinoThread
makes it very easy to schedule tasks in a controlled manner.
I would put this in a comment, but I don't have enough reputation yet.

I am a little confused in the readme it states "On the one hand, this means that the only way a task can “yield” the CPU is by returning to the caller, and it is thus inadvisable to delay() or do long waits inside a task." does this library have a function to give control to another process? Or would you have to put a return and let the program flow back to that point again?

I am by no means an expert on threads, but I think the writer might have confused threads and processes. As for your second question, I think you'd switch between threads by using SetInterval.


text:
AVR-STL Library
I have a project that I need to use a vector, I have tried to get several libraries to compile with out luck. The one that has gotten the closest is  Andy Brown's AVR-STL. I keep getting the error:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'

I am sure that this is a simple fix, I just have no idea how. If this library is no longer viable then can someone else recommend another one?
Here is the code I am trying to compile
#include "Arduino.h"
#include "iterator"
#include "vector"
#include "pnew.cpp"

std::vector<int> test;

void setup(void) {

    Serial.begin(57600);
}

void loop(void) {

    test.push_back(1);
    Serial.println("Pushed");
}

And the full output:
14:57:27 **** Incremental Build of configuration Release for project MegaTesting ****
"C:\\Eclipse\\eclipse\\arduinoPlugin\\tools\\make\\make" all
'Building file: ../.ino.cpp'
'Starting C++ compile'
"C:\Eclipse\eclipse\arduinoPlugin\tools\arduino\avr-gcc\4.8.1-arduino5/bin/avr-g++" -c -g -Os -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR     -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\cores\arduino" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\variants\mega" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility" -MMD -MP -MF".ino.cpp.d" -MT".ino.cpp.o" -D__IN_ECLIPSE__=1 -x c++ "../.ino.cpp"  -o  ".ino.cpp.o"   -Wall
cc1plus.exe: warning: C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility: not a directory [enabled by default]
In file included from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/stl_iterator_base.h:38:0,
                 from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/iterator:40,
                 from ../.ino.cpp:8:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _TrivialIterator_concept_specification<_TrivialIterator>::_TrivialIterator_requirement_violation(_TrivialIterator)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:572:16: warning: typedef '__T' locally defined but not used [-Wunused-local-typedefs]
     value_type __T;
                ^
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _Allocator_concept_specification<_Alloc>::_Allocator_requirement_violation(_Alloc)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:799:39: warning: typedef '_Tp' locally defined but not used [-Wunused-local-typedefs]
   typedef typename _Alloc::value_type _Tp;
                                       ^
In file included from ../MegaTesting.ino:3:0,
                 from ../.ino.cpp:14:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp: In function 'void* operator new(size_t, void*)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'
 void* operator new(size_t size_,void *ptr_){
       ^
In file included from ../.ino.cpp:10:0:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: 'void* operator new(size_t, void*)' previously defined here
 void* operator new(size_t size_,void *ptr_){
       ^
subdir.mk:24: recipe for target '.ino.cpp.o' failed
make: *** [.ino.cpp.o] Error 1

14:57:28 Build Finished (took 600ms)

I've got the "Andy Browns method" of standard library working. But I believe I didn't have the same error as you.
A redefinition would mean that something has already been defined, I think you can choose to not include it at some point, since it's already defined.

It looks like new is redefined. I see that you include cpp file, that contains implementation - this is rather unfortunate design, but that's how it is done.
Anyway, it seems that this file is already being compiled elsewhere. Have you tried to remove this include? What happens if you remove it?
Apart from that problem, you must be aware that dynamic memory management in such small system yelds risk of memory fragmentation that eventually leads to failed allocations.

That's the thing, I have tried excluding the pnew.cpp and believe it or not I get a Undefined message, even if I include Arduino.h before any of this library.

Are you able to allocate anything using new? It should be available since 1.0.5 or something. Try int *i = new int[5];.

Thats the weird thing about this, I do have the 'new' functionality at runtime thats why I am thinking that it has to do with either an include or header because new is available without using this lib


text:
What does the bootloader do?
As far as I understand it checks for a valid serial connection (new program incoming) and then either writes it to flash or starts executing the existing program.
Can't the 32u4 or EDBG fill the role of an ISP and program the MCU instead of the MCU self-programming? I know the EDBG is accessed via OpenOCD to write the bootloader to the SAMD21 on Arduino Zero boards so why is the bootloader even required?

The bootloader is there for convenience.
Yes, you understand what the bootloader does and how it operates.  However, you have missed out one benefit, and that is evident when you're not using the bootloader.  That is, when you're not using the bootloader the same connection can be used for a serial connection to the PC.  If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART and the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.
So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.
It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.

Surely the 32U4 firmware wouldn't be that much more complex to have it switch between SPI and UART depending on the serial connection speed? (iirc it's 1200 baud to program.)

@AshlynBlack But it's complexity that isn't needed, and would mean you need a special programmer to do anything with your own breadboard Arduino. It is far more convenient for most people to use a UART bootloader. Those that don't want a bootloader use a hardware programmer anyway, so it's a non-argument.


text:
Using the Tian handshake line
I've set up a Yun before to use the handshake line on pin 7 (thanks to this great forum post) and now I have a new project that I want to do something similar with the Tian. Based on the schematic, it's a similar idea: set the output, mark the output low. But so far I haven't been able to get it working. Anyone know how to adopt the following command from /etc/rc.local to the Tian?
# Added section to set the handshake line.
# GP19 is connected to D7 of the 32U4 processor.
# This requires setting GP22 high to enable the U7 level shifter.
# This GPIO is already exported.
# Then GP19 needs to be exported, set to output, and finally brought low.
echo 1 > /sys/class/gpio/gpio15/value
echo 21 > /sys/class/gpio/export
echo "high" > /sys/class/gpio/gpio21/direction
echo 0 > /sys/class/gpio/gpio21/value

This code is what I'm using now: it's the forum poster's text with my updates for the Tian.


text:
GET the first result in HTTP request
I have a String content="" and if I put an HTTP request like this:
client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

the output I get is:
 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

The little parser I created is this:
while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the String content?

if (c == ',') {       break;      } (i.e. break on the first comma, instead of the first closing bracket)

Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action_id":35"?
If both are true then your solution is simple.
First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.
But if the above is not what you needed then I am afraid you cannot get only the first response, because that has to do with the server itself.
Here is a solution, do try it.
I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.

Yes, the parser gets the whole response. I need only the first one stored in String content which in this example is :
[{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"}

Darkclaude X, please edit your answer and adjust the unconventional, hard-to-read capitalization.  Capitalize the first word of each sentence; capitalize proper nouns and the pronoun I; don't capitalize other words.  Also, please spellcheck  “Seperate”.

thx Jwpat, FunKction check the library above

Your question is not clear to me. Getting clarification on questions belongs in the comments, not in an answer. Please adjust your answer and comment accordingly.

Unfortunately i cant comment on his Post i need 50 points


text:
Do I need 3 full-size arduinos to control this LED setup?
I'm sourcing the parts now for an LED persistence of vision setup on a bicycle.  Two wheels with anywhere between 16-32 LED's per wheel, as well as 24 LED's mounted on the frame of the bike itself
Since the Arduinos have to be mounted into the wheels to drive the POV displays - do I need a total of 3 arduinos?
Driven by 2x [Nano 3.0 Atmel Atmega328P Mini-USB Board][1] + an Arduino Uno from the frame?
So far I think I'll pick up 2 x [433Mhz RF Transmitter Module + Receiver Module Link Kit][2] for wireless control, [Reed Switch Magnetic Detection Sensor Module][3] for calculating velocity from a small magnet mounted somewhere on one of the forks. 4 x [WS2811 RGB 8-LED Light Strip Module][4] as the POV LED's, or maybe some of the [DotStar Digital LED][5]
and miscellaneously perhaps are some of these required/ useful? maybe instead of the 4x8 I could go 4x [SSC Seoul P4][6], or from [SparkFun][7],  following pieces of [this guide][8]

DIY AT89S52 Microcontroller Development Board Set
[KT0026 Electronic Parts Pack][9]
[Square Prototyping Plate][10]
[ZnDiy-BRY Z-069 MB102 Breadboard + Power Supply Module][11]

My main concern is refresh rates....getting everything controlled...and making sure I have enough I/O. Any help would be greatly appreciated.  (URL's available on request :P)

NeoPixels are not great for POV stuff because they have inherent jitter of about 2ms regardless of your frame rate and how many pixels you are driving. This can make your edges look ragged at sufficient speeds. You can read more about the source of the jitter here... http://wp.josh.com/2014/06/09/neopixels-revealed-warping-time-and-space-to-actually-see-inter-pixel-jitter/

Maybe look at NeoPixels Revealed: How to (not need to) generate precisely timed signals. The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.
Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.

You wouldn't necessarily need full Arduinos - you could prototype them on Arduinos, then move them to just Atmel chips on your own board (e.g. stripboard). To do this, you would need your own resonator, power supply, and programming. Resonators are cheap and easy, you would probably want to set up your own power supply anyway (3 AA batteries is a perfect power supply for the Atmel), and you can program using a USBISP or similar, right from inside the Arduino IDE.
As for speed, I see a bicycle wheel is on the order of 26 inches/660mm diameter. This makes the perimeter about 6 foot 9 inches/2 meters (sounds like a lot, doesn't it?). Google tells me that a sprint on a bike by a fit person is about 40km/h, or 11 meters/second, making 5.5 revs/second of the wheel - about 180 milliseconds/revolution. This means that if you want 1 degree accuracy, you're going to have to change ALL the (changing) leds at about 2khz. The Arduino can run at up to 20mhz, giving you 10,000 instructions to change the leds. Plenty of time.
If you have strips, you should check the specs on the strips to see how fast you can change them. Remember that you probably have to update ALL of them, and you want most of the time to be spent between updates; while you are updating, it may show unwanted lights on/off.

500 µs (2 kHz) is not “plenty of time”. You have 384 bits to push (2 strips/wheel × 8 LEDs/strip × 24 bits/LED) at 400 kb/s (as per the WS2811 spec), and then you send a 50 µs pulse to latch the data. That's 1010 µs per refresh, of which only 50 (the latch pulse) are available for other computations. Using WS2812 (800 kb/s) would probably help. And no, you do not get unwanted lights during the update.

Also take into account the 400hz refresh rate of the WS2812.

Those WS2811 strips are a good idea. You can control them all from pins on the same port which will make the control a little more complex but multiply the refresh rate, or you can chain all of them off a single pin if you find the refresh rate high enough that way.

Controlling two LED strips in parallel would not be easy. The Adafruit NeoPixel library uses inline assembly to get the timings right. There are quite a few nops in the 400 kHz bitstream / 16 MHz CPU case, so it is certainly doable, but you will have to write it in assembly and count the CPU cycles.

That's what util/delay.h is for.

Not really helpful: if you want to keep a logic level for some specified time, you have to delay for that time minus the time needed to execute the other instructions in your loop. So you still need to count the cycles in the assembly code. We are talking sub-µs timing tolerances.

There are only three transitions needed per cycle. The hard part is putting all the bits together for the second transition, and even then that has a fixed cost which would be far less than the 50us reset period. So complex, but not anywhere near impossible.

You can drive up to 8 strings at the same time from 8 different IO pins on an arduiono. Yuo do need to get all the outgoing bytes (each byte has the bit outgoing pattern for all out outputs) ready beforehand, but you can do that outside the timing-critical loop.


text:
How to use to two different programs into one stkech
I am currently using relay module, but I am facing a problem that, when Arduino pins are LOW then all relay are going HIGH, so I want to use this code so that when arduino starts all pins are getting HIGH, and also can be control with char data/switch(data)/case break;/,
Here is my code:

setup() {
  if(conditionIsTrue) {
    aGroup::setup();
  } else {
    bGroup::setup();
  }
}

loop() {
  if(conditionIsTrue) {
    aGroup::loop();
  } else {
    bGroup::loop();
  }
}

namespace aGroup {
setup() {

    pinMode(ledPinA, OUTPUT);
    pinMode(ledPinB, OUTPUT);
    pinMode(ledPinC, OUTPUT);
    pinMode(ledPinD, OUTPUT);
    pinMode(ledPinE, OUTPUT);
    pinMode(ledPinF, OUTPUT);
    pinMode(ledPinG, OUTPUT);
    pinMode(ledPinH, OUTPUT);
    pinMode(ledPinI, OUTPUT);
    pinMode(ledPinJ, OUTPUT);
    pinMode(ledPinK, OUTPUT);
    pinMode(ledPinL, OUTPUT);

}

loop() {

  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, HIGH);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
  digitalWrite(ledPinH, HIGH);
  digitalWrite(ledPinI, HIGH);
  digitalWrite(ledPinJ, HIGH);
  digitalWrite(ledPinK, HIGH);
  digitalWrite(ledPinL, HIGH);

}
}

namespace bGroup {
setup() {
  Serial.begin(9600);
    pinMode(ledPinA, OUTPUT);
    pinMode(ledPinB, OUTPUT);
    pinMode(ledPinC, OUTPUT);
    pinMode(ledPinD, OUTPUT);
    pinMode(ledPinE, OUTPUT);
    pinMode(ledPinF, OUTPUT);
    pinMode(ledPinG, OUTPUT);
    pinMode(ledPinH, OUTPUT);
    pinMode(ledPinI, OUTPUT);
    pinMode(ledPinJ, OUTPUT);
    pinMode(ledPinK, OUTPUT);
    pinMode(ledPinL, OUTPUT);

}

loop() {

  char data = Serial.read();
    switch(data)
    {
        case 'A': digitalWrite(ledPinA, HIGH);break;
        case 'B': digitalWrite(ledPinA, LOW);break;

        case 'C': digitalWrite(ledPinB, HIGH);break;
        case 'D': digitalWrite(ledPinB, LOW);break;

        case 'E': digitalWrite(ledPinC, HIGH);break;
        case 'F': digitalWrite(ledPinC, LOW);break;

        case 'G': digitalWrite(ledPinD, HIGH);break;
        case 'H': digitalWrite(ledPinD, LOW);break;

        case 'I': digitalWrite(ledPinE, HIGH);break;
        case 'J': digitalWrite(ledPinE, LOW);break;

        case 'K': digitalWrite(ledPinF, HIGH);break;
        case 'L': digitalWrite(ledPinF, LOW);break;

        case 'M': digitalWrite(ledPinG, HIGH);break;
        case 'N': digitalWrite(ledPinG, LOW);break;

        case 'O': digitalWrite(ledPinH, HIGH);break;
        case 'P': digitalWrite(ledPinH, LOW);break;

        case 'Q': digitalWrite(ledPinI, HIGH);break;
        case 'R': digitalWrite(ledPinI, LOW);break;

        case 'S': digitalWrite(ledPinJ, HIGH);break;
        case 'T': digitalWrite(ledPinJ, LOW);break;

        case 'U': digitalWrite(ledPinK, HIGH);break;
        case 'V': digitalWrite(ledPinK, LOW);break;

        case 'W': digitalWrite(ledPinL, HIGH);break;
        case 'X': digitalWrite(ledPinL, LOW);break;

    }

}
}

But this isn't work, Please help me.

The title seems to bear absolutely no relation to the question. Could you edit one or the other so that they match, please?

In first place, you have to declare the functions setup and loop as void setup() and void loop().
If you want your output pins to be high when Arduino starts then you should do that in your setup function, instead of doing it in the loop:
void setup() {

  Serial.begin(9600);

  // Step 1: configure pins as outputs
  pinMode(ledPinA, OUTPUT);
  pinMode(ledPinB, OUTPUT);
  pinMode(ledPinC, OUTPUT);
  pinMode(ledPinD, OUTPUT);
  pinMode(ledPinE, OUTPUT);
  pinMode(ledPinF, OUTPUT);
  pinMode(ledPinG, OUTPUT);
  pinMode(ledPinH, OUTPUT);
  pinMode(ledPinI, OUTPUT);
  pinMode(ledPinJ, OUTPUT);
  pinMode(ledPinK, OUTPUT);
  pinMode(ledPinL, OUTPUT);

  // Step 2: initialize pins to output HIGH
  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, HIGH);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
  digitalWrite(ledPinH, HIGH);
  digitalWrite(ledPinI, HIGH);
  digitalWrite(ledPinJ, HIGH);
  digitalWrite(ledPinK, HIGH);
  digitalWrite(ledPinL, HIGH);
}

Also, you can't declare a variable and assign to it the value of a function other than an object constructor. Furthermore, you should check if there's data available before trying to read it. So you have replace the following sentence:
char data = Serial.read();

With something like this:
char data = 0;
if (Serial.available() > 0) {
    data = Serial.read();
    // do your stuff
}

This should do the trick.
Last but not least: I don't know why you're using two namespaces. The aGroup looks useless to me. On top of that, I fail to see where in your code do you declare, initialise and update the conditionIsTrue variable. The same goes for all those ledPinX variables. Is there more code that you're not showing here? Is your code failing at runtime, or doesn't even compile?

YES SIR, it is working very good........ Thanks a lot.......


text:
XBee, external libraries and passing structures as arguments
I have very weird problem with a library I am creating. The library will be used to communicate between Arduino modules using XBee Series 1 modules. Library is very simple wrapper library around Arduino XBee library.
I have one function that reads received packet and sends it back. At the moment it is implemented as a simple "echo" service - the function just displays the data received and sends it back to per-defined address.
At the moment I have three versions of this function, out of which one is not working.

A function taking no arguments: void processPacket()
A function taking structure as a value as an argument: void processPacket(valuesStruct valuesStructData) - THIS VERSION OF THE FUNCTION IS NOT WORKING!
A function taking pointer to the structure as an argument: void processPacket(valuesStruct* valuesStructData)

At this moment I noticed strange behavior in the 2nd version of the function. I do nothing with the passed argument - the content of all three functions is the same. In 2nd case the function reads wrong values from received XBee packet. In the 1st and 3rd case the function performs correctly.
Code:
ExampleLib.h
#ifndef ExampleLib_h
#define ExampleLib_h

#include "Arduino.h"
#include <XBee.h>

#define ADDRESS_BROADCAST 0xffff
#define ADDRESS_PC 0x3333

typedef struct
  {
    int valA;
    int valB;
    int valC;
  } valuesStruct;

class ExampleLib
{
public:
    ExampleLib();
    void setSerial(Stream &serial);
    boolean tryReceivePacket();
    void processPacket();
    // THIS FUNCTION IS NOT WORKING!
    void processPacket(valuesStruct valuesStructData);
    void processPacket(valuesStruct* valuesStructData);
private:
    XBee xbee;
    Rx16Response rx16;
};

#endif

ExampleLib.cpp
The value read in line byte* packetData = rx16.getData(); is wrong when we trigger processPacket(valuesStruct valuesStructData) function. In other cases the behavior is correct.
#include "Arduino.h"
#include <XBee.h>
#include "ExampleLib.h"

ExampleLib::ExampleLib()
{
    xbee = XBee();
    rx16 = Rx16Response();
}

void ExampleLib::setSerial(Stream &serial)
{
    xbee.setSerial(serial);
}

boolean ExampleLib::tryReceivePacket()
{
    xbee.readPacket();

  if (xbee.getResponse().isAvailable()) {
    // got something

    if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
      // got a rx packet

      xbee.getResponse().getRx16Response(rx16);
      return true;
    }
    else {
      return false;
    }
  }
  else if (xbee.getResponse().isError()) {
    //nss.print("Error reading packet.  Error code: ");
    //nss.println(xbee.getResponse().getErrorCode());
    // or flash error led
    return false;
  }

  return false;
}
void ExampleLib::processPacket()
{
  byte* packetData = rx16.getData();
  byte dataLength = rx16.getDataLength();
  Serial.print("START L:");
  Serial.println(dataLength);
  for (int i = 0; i < dataLength; i++) {
    Serial.print(packetData[i]);
    Serial.print(" - ");
  }
  Serial.println("END");

  //16-bit addressing: Enter address of remote XBee, typically the coordinator
  Tx16Request tx = Tx16Request(ADDRESS_PC, packetData, sizeof(packetData));
  xbee.send(tx);
}

void ExampleLib::processPacket(valuesStruct valuesStructData)
{
  processPacket();
}

void ExampleLib::processPacket(valuesStruct* valuesStructData)
{
  processPacket();
}

Arduino sketch
#include <XBee.h>
#include <ExampleLib.h>

ExampleLib exampleLibObj = ExampleLib();

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

void loop()
{

  boolean isPacketReceived = exampleLibObj.tryReceivePacket();

  if (isPacketReceived) {
    // leave only one section, the rest should be commented

    //Section 1: working
    exampleLibObj.processPacket();

    //Section 2: not working
//    valuesStruct test;
//    test.valA = 0;
//    test.valB = 0;
//    test.valC = 0;
//    exampleLibObj.processPacket(test);

    //Section 3: working
//  valuesStruct* test;
//  test->valA = 0;
//  test->valB = 0;
//  test->valC = 0;
//  exampleLibObj.processPacket(test);
  }
}

I am really puzzled why in this one case function is performing differently. Looking forward to any suggestions to that issue.
Thanks!

This does seem to be very puzzling.

I've read through your code 3 times now and all I've managed to glean is that your question (and your code's behaviour) seems to be beyond me

If the second isn't working, it may be best to use the other 2. Especially on the Arduino with limited RAM, you will not have enough if you pass a full struct to a function. Passing a pointer is less memory-intensive, and if it works, use it!

Thanks! I have actually made some tests using MemoryFree library and in that case memory is not an issue at all. What actually happens is, for some reason, copied version of the object, that we use in a function is written in the area of a memory, where XBee packet resides. In later tests the same happened to me with option 3 and passing a pointer - a copy of a pointer would corrupt the packet structure. Further investigation led me to the way of initializing XBee object to be the possible culprit.

Following those instructions - link - I managed to fix the problem in both cases, but I still don't know why the problem occurred in the first place.


text:
Simple Script controlled by Raspberry not working
I can't figure out why the next script is not working. I have attached the Arduino to one USB port of the raspberry pi, in which I've installed pyserial. I just want to turn off/on a led depending of the number I write on the Raspi console (1-> on, 2-> off).
    int led=13;

void setup(){
  Serial.begin(115200);
  pinMode(led,OUTPUT);
}
void loop(){
  if(Serial.available()){
     mode(Serial.read() - '0');
  }
}
void  mode(int n){

    if (n== 1){
         digitalWrite(led,HIGH);
    }
    if (n== 2){
        digitalWrite(led,LOW);
    }
  }

PS: I double checked and the baudrate is configured also at 115200 at the raspi side.
In addition, if I place digitalWrite(led,HIGH) just before  the line  "mode(Serial.read() - '0');" the led turn on when I send some information from the raspi shell (so, works well).

Finally I've found the error, it was the serial communication baud rate: 115200. It seems that at higher speeds it not works properly, lowering it to 9600 do the trick.

Have you also tried other rates that worked (or not) between 9600 and 115200 bauds?

That is weird. Anyone know why that's happening?


text:
arduino 16u2 stk500v2_command(): command failed
I'm trying to fix arduino uno r3 that was burned-out.
I changed m16u2 chip on it. and now I need burn in:  Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
I'm using stk500v2 and connecting it to isp of arduino. Output log file of avrdude:
C:\>avrdude -c stk500v2 -P COM4 -p m16u2 -U flash:w:1.hex -vvvv

avrdude: Version 6.1, compiled on Mar 13 2014 at 00:09:49
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v2
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: Recv: . [1b]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [0b]
avrdude: Recv: . [0e]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [08]
avrdude: Recv: A [41]
avrdude: Recv: V [56]
avrdude: Recv: R [52]
avrdude: Recv: I [49]
avrdude: Recv: S [53]
avrdude: Recv: P [50]
avrdude: Recv: _ [5f]
avrdude: Recv: 2 [32]
avrdude: Recv: t [74]
avrdude: stk500v2_getsync(): found AVRISP programmer
         AVR Part                      : ATmega16U2
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC6
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           eeprom        65    20     4    0 no        512    4    128  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           flash         65     6   128    0 yes     16384  128    128  4500  45
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           hfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           efuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lock           0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           calibration    0     0     0    0 no          1    0      0     0
 0 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           signature      0     0     0    0 no          3    0      0     0
 0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel STK500 Version 2.x firmware
         Programmer Model: AVRISP
avrdude: Send: . [1b] . [02] . [00] . [02] . [0e] . [03] . [90] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [02]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [15]
avrdude: Send: . [1b] . [03] . [00] . [02] . [0e] . [03] . [91] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [14]
avrdude: Send: . [1b] . [04] . [00] . [02] . [0e] . [03] . [92] . [82]
avrdude: Recv: . [1b]
avrdude: Recv: . [04]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [0a]
avrdude: Recv: . [1b]
         Hardware Version: 2
         Firmware Version Master : 2.10
avrdude: Send: . [1b] . [05] . [00] . [02] . [0e] . [03] . [94] . [85]
avrdude: Recv: . [1b]
avrdude: Recv: . [05]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: U [55]
avrdude: Recv: E [45]
         Vtarget         : 8.5 V
         SCK period      : 0.1 us

avrdude: Send: . [1b] . [06] . [00] . [0c] . [0e] . [10] . [c8] d [64] . [19]
[20] . [00] S [53] . [03] . [ac] S [53] . [00] . [00] 5 [35]
avrdude: Recv: . [1b]
avrdude: Recv: . [06]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [0e]
avrdude: Recv: . [10]
avrdude: Recv: . [c0]
avrdude: Recv: . [c1]
avrdude: stk500v2_command(): command failed
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude: Send: . [1b] . [07] . [00] . [03] . [0e] . [11] . [01] . [01] . [00]
    avrdude: Recv: . [1b]
    avrdude: Recv: . [07]
    avrdude: Recv: . [00]
    avrdude: Recv: . [02]
    avrdude: Recv: . [0e]
    avrdude: Recv: . [11]
    avrdude: Recv: . [00]
    avrdude: Recv: . [01]

    avrdude done.  Thank you.

My question is what block with error does? can it be I shorted due soldering? or maybe burned chip? any issues? how I can check?
ps. programmer works perfect. checked!

All I can tell from this log is that communication with the MCU does not work at all, i.e. it fails on the very first command sent to it (all the preceding communication is with the controller).
There could be numerous causes for this (chip rotated by 90 degrees, etc). I would start by attaching a logic analyzer to the MISO pin and see whether there are any wiggles there at all.

One important question to be sure: Arduino UNO has 2 ISP connectors, one for the ATmega328, and one for ATmega16u2 (used for USB connection); are you sure you are connecting to the 2nd one?

yes i'm sure. its connected to ATmega16u2. @microtherion does the sended bits and received bits must be same?

@Klasik it’s a bit beyond the scope of a comment to explain, so I’ve made it an answer.

Here’s a decoding of the crucial pair of messages exchanged here. Protocol is documented on Atmel’s site.
Your machine sends:
[1b]                              Beginning of message
[06]                              Message sequence number
[00] [0c]                         Message body length (big endian)
[0e]                              Beginning of message body
[10]                              Command: CMD_ENTER_PROGMODE_ISP
[c8] [64] [19] [20] [00]          Various programming parameters
[53]                              Response value to look for
[03]                              Response index
[ac] [53] [00] [00]               Enter programming mode command
[35]                              Checksum

This causes the programmer to send the 4 bytes 0xAC 0x53 0x00 0x00 to the MCU, and look for the value 0x53 in the third of the 4 response bytes, as specified on page 260 of the data sheet. However, the programmer answers:
[1b]                              Beginning of message
[06]                              Sequence number (matches message previously sent)
[00] [02]                         Response body length
[0e]                              Beginning of response body
[10]                              Command: CMD_ENTER_PROGMODE_ISP (Matches message)
[c0]                              STATUS_CMD_FAILED (This is the error message)
[c1]                              Checksum

That means that tyne very first command sent to the microcontroller “failed” (most likely by not returning the expected answer byte).

is it called post code or something?

I'm afraid I don't understand your question, @Klasik.

how thous codes called? )

Btw. the solution was resoldering SMD.


text:
Solar Tracker Code - how to limit steppers to max & min angle?
a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev).
We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated.
Cheers
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1);  // declaring horizontal stepper
Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2);  // declaring vertical stepper

int ldr1 = A0;  // right ldr
int ldr2 = A1;  // centre ldr
int ldr3 = A2;  // left ldr
int ldr4 = A3;  // top ldr
int ldr5 = A4;  // bottom ldr

const int threshold = 550;  // limit to stop tracker from moving at night

const int tol = 50;  // tolerance for ldrs // maybe vertical AND horizontal depending on difference?

//int = countv
//int = counth

//const int maxh = ?    // to prevent overturning horizontal (50 steps = 90°)
//const int minh = ?    // combine with count int's // i.e. if counth > 90 - stop
//const int maxv = ?    // to prevent overturning vertical
//const int minv = ?

void setup()
{
  AFMS.begin();
  stepperv->setSpeed(10);
  stepperh->setSpeed(10);
}

void loop()
{
  int right = analogRead(ldr1);
  int centre = analogRead(ldr2);
  int left = analogRead(ldr3);
  int up = analogRead(ldr4);
  int down = analogRead(ldr5);

  //STOP MOVEMENT//
  if ((left < threshold) && (right < threshold) && (up < threshold) && (down < threshold)) {}  // stop any movement if sensor values below threshold
                                                                                // at begining to check after every sensor reading

  //HORIZONTAL MOVEMENT//
  if((right > centre + tol) && (left + tol < centre))   // && (right - ? > tol)
  {
    stepperh->onestep(BACKWARD,DOUBLE);  // add +1 to int counth // if (minh < counth < maxh) - move // else - stop // counth=counth++ , counth=counth--
  }
  else if((left > centre + tol) && (right + tol < centre))  // && (left - ? > tol)
  {
    stepperh->onestep(FORWARD,DOUBLE);
  }
  else {}  // do nothing

  //VERTICAL MOVEMENT//
  if((up > centre + tol) && (down + tol < centre))  // && (up - ? > tol)
  {
    stepperv->onestep(BACKWARD,DOUBLE);
  }
  else if((down + tol > centre) && (up + tol < centre))  // && (down - ? > tol)
  {
    stepperv->onestep(FORWARD,DOUBLE);
  }
  else{}  // do nothing
}

Well first you'll probably need to define your limits. I see you have maxh minh and so on.. how do you know when you've reached the max/min?

Thanks for all the replies. Could i maybe use a magnetic switch or an accelerometer - something like this: Accelerometer? How accurate are these things?

"how do you know when you've reached the max/min?"... You can create a routine of track angles. Check the maximun ammount of energy that the solar pan is getting. At this point, this is the best angle.  At the end, this is the final goal.  Do you have your project concluded?

The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.
At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.

Stepper motors are nice and all but they actually make less than adequate servos for this purpose. the best way that I can see is with linear actuators that have position sensors in them and feed the Voltage divider outputs from those sensors to the Atmega chip. If you write the code to compare the signals from the light detectors with the voltage from the pos sensors it should be a lot better. Also, limit switches should be used in this arrangement too. They would be as a fail safe. The other benefit is that linear actuators usually hold a lot better without loosing their position due to outside stresses. Steppers can be used for prototyping, but it would still be better to start with small servos with sensors and get the system working first. I myself am trying to get a working system and I am having troubles with the coding also, but I am not good at coding. One other thing, I have looked at a lot of different codes to find something that might help me with my project and I have seen this. Stepper motor systems are written with minimal code which as I see it leaves room for much error. Atmega has plenty of room for code storage and plenty of ports for sensors in this use. Everyone knows that old phrase keep it simple but some times that is not always the best advice. You are working with something that needs to be somewhat complicated, to be less likely to fail. The more engineering you put into something the more likely something is to go wrong but less engineering gives you the same results. So consider all the posibilities and address them. Adding components and sub systems will in the end make your work better.

Although this is useful information, it doesn't really answer the question. Can you add a little bit more (maybe a paragraph) to better answer the question? Thanks!

It's kind of hard to read as a big block of text.

When working with steppers you have to realise that you are not dealing with absolute coordinates. Unlike with, for example servos, which you command to go to particular angle, you command steppers to rotate a particular amount of steps in a particular direction. This creates in your case the problem that you cannot actively check the positions of the steppers without some sensing element.
As a solution I would suggest that you would store the steps the steppers take in some variables, and then with the code limiting, that these variables don't go over a surtain number. With this method, you need to have a way of setting the zero point of the steppers, meaning from where to start the counting. This could for example be done by driving the system against some switch, and then setting the step variable to zero here. This is usually done once in the bootup, meaning that it is excecuted in the setup function.


text:
Using Waveshare Raspberry Pi TFT LCD with Arduino Uno
I have a 3.5 inch Waveshare Raspberry Pi TFT LCD which uses the XPT2046 Touch Controller. I want to use this LCD screen with my Arduino Uno.
I originally believed something like this was impossible, but then I found out that the XPT2046 Touch Controller is compatible with the Arduino, and a large number of libraries for the same exist. However, I'm not really very sure whether I can use this with my Arduino; the design of the screen I have is slightly different from the ones I've found online, which are supposed to be compatible with an Arduino Uno.
Is it possible for me to use this screen with my Arduino Uno? If so, what would the wiring schematics look like, and would I be able to use libraries like URTouch?

Possibly.
The XPT2046 chip is only for the touch screen, not the LCD.  That will be easy to get going on the Arduino since many many Arduino LCD screens use the same chip.
However, you will need to find out what driver chip the LCD display uses (maybe ILI9488 or HX8357 or something similar), and what pins on the Pi header relate to what function on the display (note: it is probably a 16 bit parallel interface, so uses a lot of pins).
Also note that this only applies to displays that connect only to the big 40 pin header. If it uses the FPC display connector you will have no luck trying to use it with an Arduino.

it is SPI https://www.waveshare.com/product/3.5inch-RPi-LCD-A.htm

That will be very slow over SPI at that resolution...

Is there a website where I could find which driver chip the LCD uses? The LCD connects only to the 40 pin header on the RPi, and does not use the FPC display connector. It is a parallel interface of 16 pins each side, you're right.

I've found some docs (scroll down to the Interface section) which underlines what each pin on the display does. I probably now can build a circuit, but I have no idea on how to program each pin. Is there any guide which you know of?

as I write in the first comment, it is SPI. try SPI libraries for displays. and lookup Arduino SPI wiring


text:
Is it possible to power up Arduino upon serial transmission without dropping data?
I have radiator valves that send readings about the temperature and valve opening to the serial output: Honeywell HR-25.
I want to collect those readings in a central server at home without flashing the thermostat with a custom firmware.
To do that, I need an Arduino (very bare one) that can receive the serial data, but at the same time I need it to be powered down most of the time, or it would kill the battery life of the thermostat.
Can I wake up an Arduino from power down using the serial transmission, and immediately capture the serial data without dropping bits? how?

@LookAlterno Wake up from power-down upon incoming serial? I couldn't find it.

Is the thermostat a smart one that requires a C wire? If so you can put a buck converter on it to power the arduino.

The power is provided by the thermostat, there is a connector with Vcc. Still, I want the batteries to last at least a full season. If I keep the atmega in standby, they probably won't.

I can also power down the device and wake it up (LowPower library) some seconds before the expected serial transmission...

@LookAlterno maybe this actually https://arduino.stackexchange.com/questions/13167/put-atmega328-in-very-deep-sleep-and-listen-to-serial?rq=1

OT question: where do you find how to "hack" the thermostat? I mean, I couldn't find any reference to a serial port for the HR-25

How do you power up a device before it sends the information? Does it have a clairvoyance mode?

The linked (duplicate) page now has example code that preserves the first byte received from serial in the second example in my answer.

I never tried myself, but afaik you can define an wake up/interrupt from USART, meaning that if you get a receiving byte from the UART it will wakeup the Arduino.
When powered up, you can read continuous data. I would be surprised if they make an UART wakeup signal, that bytes would be lost (i.e. that powering up would take too long to miss more UART bytes).

You can build a circuit using an electronic counter to only start supplying power to the Arduino at a specific given time. You would still need to supply the circuit, but the energy need would be a small fraction of the Arduino's needs.
On the other hand, can't you use a second power source for the Arduino? Li-On batteries are pretty cheap nowadays, and you can always savage something from an old Notebook's battery.

I don't think you can use the HW peripheral, so IF you really want/need low power you will need something like this (note: this may be very overkill for your application)

simulate this circuit – Schematic created using CircuitLab
NOTE: I assume the "serial" is a UART and its "rest" voltage is 5V. Choose the PMOS so that it is turned on with about 3V.
In this case, the circuit is normally powered off. When you receive a START, the PMOS start conducting. The ATMEL will then pull pin B to 5V, thus keeping the circuit powered. Through pin A it can sense the UART.
In this case, since you miss the start bit, you won't be able to use the usual libraries or peripherals. You can, however, implement a software uart which can avoid the first start bit to overcome this.
Just a suggestion, however. If your thermostat is transmitting frequently, maybe a more useful approach can be to listen to one transmission, then put everything to sleep for let's say 30 seconds, then turn on again and wait for the first serial transmission. This can be simpler than this solution and more effective

This is completely unworkable - in actually cutting power to the chip, you'll suffer startup delays even worse than in allowing the chip to wake itself.  You really don't need to cut power to modern MCUs, they're designed to handle that task with their internal circuitry.

@ChrisStratton I have to thank you, because I never looked into the deep hole of startup times; I always thought that the clock was stable pretty soon. In any case, Table 13-12 on the datasheet states that the internal clock can be used in a stable way, when the BOD is enabled, after 20 clock cycles. I assume that the power rises in negligible time. With a 9600bps serial (I usually find this in this kind of applications) you will have to wait 156us before sampling the first byte from the falling edge (which is 1248 clock cycles). I think you have enough time to set up everything...

Of course you will have to be quick at initialising, but I think it is doable. I'll try to implement it sooner or later... In any case the power consumption in power down is in the range of 1uA, but I think that it'll stop the clock, so you will need exactly the same time to wake as a power on (excluding the VCC rise time). The only power-save mode with the oscillator enabled is the standby one, but it consumes slightly less than 1mA (and this is too much, since a rough estimation is that the thermostat absorbs around 0.2mA)


text:
How can I control a slave ESP8266 from a local server and also from another ESP8266?
I have a power strip with a ESP8266 which is supposed to turn it on upon command from a OpenHAB server, or to stay on for a predefined time upon command from another ESP8266 (serverless).
The reason is that OpenHAB is used to directly control the strip, while the other master ESP8266 is powered on and off intermittently and periodically sends "refresh" commands to the slave, that will turn off when no more messages are received.
How should I handle the control of the ESP8266? I have never worked with master/slave and I'm confused by the number of available options. For example, MQTT seems a good choice when the server sends the control command, but it requires a software listening and relaying MQTT messages, therefore is not suitable as only control technique because the communication between ESP8266 must not rely on any further network device.
I also thought about simply controlling the slave ESP8266 via webpage and POST/GET commands, since OpenHAB can be set up to use this method as well and that would work also as direct control between ESP8266.
What are my options, their complexity and pros/cons?

let the esp8266 be a client for OpenHAB and start server for commands from the other esp8266

@Juraj do you mean using MQTT? I don't understand to which protocol you refer.

I don't know OpenHAB. Do what it requires. And for the other esp8266 start a server


text:
How to delegate code compilation to a remote machine?
Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.
My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.
Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.
The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).
How to delegate compilation of Arduino projects to a remote machine?

How about using Arduino-CLI at the server and invoking it via ssh?

And using vi as your "IDE" ;)

@chrisl I wasn't aware of Arduino-CLI. You could expand and write an answer

Sound a bit like "continuous integration". Maybe look at Jenkins to run Arduino CLI when it detects changes in the samba share. Note that you also need some way to provide feedback, in case the compilation failed.

If you don't have a GUI, you can still compile and upload sketches by using the Arduino CLI. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.
You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.
Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.