7月 28

51单片机 超声波测距测试

我使用51单片机,超声波模块是hc-sr04。以前在raspberry上用python测的,这次因为需要转到51单片机上,所以用C语言重写,原理上基本一致。

#include 
#include 
typedef unsigned char uchar;
typedef unsigned int  uint;	
  

// 测试距离
uint S;
// 非中断用计时计数器
uint hcsr_count;
sbit Led = P1^5;
sbit Trig = P1^1;
sbit ECHO =P1^2;
sbit Led4 = P1^4;


// 超声波给20us的高电平
void delay_20us()
{
	uchar bt ;
	for(bt=0;bt<4;bt++);
}

main()
{
	uint count;
	uchar us50;
	Led = 0;
	Led4 = 0;
	Trig = 0;
	ECHO = 0;
	while(1)
	{
		hcsr_count = 0;
		// 开始20us的搞电平
		Trig = 1;
		delay_20us();
		Trig = 0;
		count = 0;
		//等待Echo回波引脚变高电平
		while(ECHO ==0 )  
		{
			_nop_();
		}
		// 开始接收
		while(ECHO == 1 )
		{
			for(us50=0;us50<10;us50++);
			hcsr_count++;
			// 如果获得范围大于两米
			// 则强制返回值
			if (hcsr_count >= 2357)
				ECHO = 1;
		}
		//算出来是CM。1.7 出处。 
		// 在空气中传播速度34000cm/s。
		// hcsr_count每次计数时间约为0.00005秒,既1/20000秒
		// 34000cm/s * (1/20000)s = 1.7cm/s
		// 统计出的为往返路程,除2后为单程
		S = (hcsr_count*1.7)/2;     //算出来是CM
		if(S < 20)
		{
			Led = 1;
		}																												   
		else if(S > 21)
		{
			Led = 0;
		}
	}
}

超声波测距源码

7月 03

在linux下用python读取其他操作系统编写的配置文件

  在windows、mac、linux下编写的配置文件会有头部或者换行有区别。为了分析方便简单做个记录,只为演示,代码并不完整,需要自己修改

def conf(conf_context):
    # 替换window或mac操作系统下的换行符
    import re
    _get_file = re.sub(r'(\r\n|\r|\n)', '\n', conf_context)
    # 将配置放在内存中
    import StringIO
    _tmp_file = StringIO.StringIO()
    # 将文件写入内存
    _tmp_file.write(_get_file)
    _tmp_file.seek(0)
    # 如果是在window下编辑的文件将,utf-8 BOM开始的头替换掉
    if _tmp_file.read(3).startswith('\xef\xbb\xbf'):
        _tmp_file.seek(3)
    else:
        _tmp_file.seek(0)
    # 导入配置
    import ConfigParser
    try:
        cf = ConfigParser.SafeConfigParser()
        cf.readfp(_tmp_file)
        config_list = cf.sections()
    except:
        _tmp_file.close()
        return "error"
    _tmp_file.close()
    return "ok"
6月 24

监控mysql从机同步状态脚本1.1

  之前写了个一个检查mysql从机的脚本(http://www.simonzhang.net/?p=1823),但是在使用中发现一个问题。如果数据库被重启了,但是同步的没有启动,此脚本检查还是正常,不会进行报警,数据不会同步。
  我做了个调整,每次检查同步主机的pos,通过crontab进行调用,如果多次都没有变化则进行告警。如果10分钟调用一次,设为3次,就是半个小时内没有更新则报警。
crontab配置如下:
*/10 * * * * /bin/bash /script/check_mysql_slave/check_mysql_slave.sh start >/dev/null 2>&1
部分代码如下:

#!/usr/local/bin/python
# -*- coding:utf-8 -*-
# -------------------------------------------------------------------------------
# Filename:    check_nagios.py
# Revision:    1.1
# Date:        2013-06-24
# Author:      simonzhang
# Email:       simon-zzm@163.com
# -------------------------------------------------------------------------------
import os
import pexpect
import time
import smtplib
from email.mime.text import MIMEText

#### base se
mysql_bin = '/program/mysql5/bin/mysql'
mysql_user = 'checkslavestatus'
mysql_pass = 'xxxxxxxxxx'
#设置错多少次开始告警
max_error = 3
mail_host = 'smtp.exmail.qq.com'
mail_user = 'warning@xxx.net'
mail_pwd = 'xxxxxxxxx'
mail_cc = "simon-zzm@163.com"
####

def mail_warn(error_ip):
    content = 'IP %s mysql slave is error!'%error_ip
    msg = MIMEText(content)
    msg['From'] = mail_user
    msg['Subject'] = 'mysql warnning %s'%error_ip
    msg['To'] = mail_to
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pwd)
        s.sendmail(mail_user,[mail_to],msg.as_string())
        s.close()
    except Exception ,e:
        print e

def main():
    error_context = ''
    #读取上次检查master同步点的记录
    try:
        f = open('MasterPos.txt', 'rb').read()
        try:
            old_master_pos = f.split(':')[0]
            error_count = f.split(':')[1]
        except:
            old_master_pos = 0
            error_count = 0
    except:
        old_master_pos = 0
        error_count = 0
        pass
    # 获得数据库同步状态
    status = os.popen("%s -u%s -p%s -e 'show slave status\G'"%
                      (mysql_bin,mysql_user,mysql_pass)).readlines()
    # 查看同步主节点数据
    for status_l in status:
        if status_l.find('Read_Master_Log_Pos: ') > 0:
            f = open('MasterPos.txt', 'wb')
            # 防止出现空值
            try:
                new_master_pos = int(status_l.split(': ')[1])
            except:
                new_master_pos = 0
            if int(new_master_pos) == int(old_master_pos) or int(old_master_pos):
                f.write('%s:%s' % (new_master_pos, int(error_count)+1))
            else:
                f.write('%s:0' % new_master_pos)
            f.close()
            if int(error_count)+1 > max_error:
                error_context += 'slave error!'
    # 判断是否报警
    print error_context:
    if len(error_context) > 1:
        ip = os.popen("/sbin/ifconfig|grep 'inet addr'|awk '{print $2}'").read()
        get_local_ip = ip[ip.find(':')+1:ip.find('n')]
        mail_warn("%s"%get_local_ip)

if __name__ == "__main__":
    main()

源代码