Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 8 months ago.
Serial communication with k64F semi - working
Hi.
I've created a program that is supposed to find primes using the k64F platform, but the when I try to print an int variable, it pops up error #167 and complains that the data type is not a const char. Any ideas would be great. Here is my code:
Prime Number Generator
#include "mbed.h"
Serial pc(USBTX, USBRX);
int main()
{
int i = 3;
bool flag;
pc.printf("Prime Number Generator \n\n");
while (true) {
wait(.001f);
flag = false;
for(int j = 2; (j * j < i) && (i % j != 0); j++){
if(i % j == 0){
flag = true;
break;
}
}
if(!flag)
pc.printf((int)i);
i += 2;
}
}
2 Answers
10 years, 8 months ago.
You need a format string for printf, otherwise it doesn't know what type to interpret i as. . the line should be on the order of: pc.printf("$d\n",i);
10 years, 8 months ago.
Hi,
Dave-san's comment seems to be right.
For my case I usually use
pc.printf("%d\n\r", i) ;
moto
Thanks for responding so quickly :) . Completely unrelated to the original question, it prints everything okay, but somehow a few non-primes get printed also, like 25. I've tried a very similar program on an arduino, and it works fine (i.e, only ends with the numbers 1, 3, 7 and 9). Any ideas?
posted by 06 Mar 2015Hi,
First of all '2' is a prime number, if I remember correct.
As for my trial
#include "mbed.h"
Serial pc(USBTX, USBRX);
int main()
{
int i = 3;
int j ;
bool flag;
pc.printf("Prime Number Generator \n\n");
pc.printf("2\n\r") ; // 2 is a prime
while (true) {
wait(.001f);
flag = false;
for(j = 2 ; j <= (i/2) ; j++ ) {
if((i % j) == 0){
flag = true;
break;
}
}
if(!flag)
pc.printf("%d\n\r",i);
i += 2;
}
}
I could not check if it is working perfectly, but as least 25 does not show up.
moto
posted by 07 Mar 2015I like the j <= i / 2 statement in the for() loop; it is probably considerably faster than my j * j < i. :)
posted by 10 Mar 2015